fix recursively_compute_inclusions and add dwz test case
[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   const gdb_byte *buffer;
107   bfd_size_type size;
108   /* True if we have tried to read this section.  */
109   int readin;
110 };
111
112 typedef struct dwarf2_section_info dwarf2_section_info_def;
113 DEF_VEC_O (dwarf2_section_info_def);
114
115 /* All offsets in the index are of this type.  It must be
116    architecture-independent.  */
117 typedef uint32_t offset_type;
118
119 DEF_VEC_I (offset_type);
120
121 /* Ensure only legit values are used.  */
122 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
123   do { \
124     gdb_assert ((unsigned int) (value) <= 1); \
125     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
126   } while (0)
127
128 /* Ensure only legit values are used.  */
129 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
130   do { \
131     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
132                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
133     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
134   } while (0)
135
136 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
137 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
138   do { \
139     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
140     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
141   } while (0)
142
143 /* A description of the mapped index.  The file format is described in
144    a comment by the code that writes the index.  */
145 struct mapped_index
146 {
147   /* Index data format version.  */
148   int version;
149
150   /* The total length of the buffer.  */
151   off_t total_size;
152
153   /* A pointer to the address table data.  */
154   const gdb_byte *address_table;
155
156   /* Size of the address table data in bytes.  */
157   offset_type address_table_size;
158
159   /* The symbol table, implemented as a hash table.  */
160   const offset_type *symbol_table;
161
162   /* Size in slots, each slot is 2 offset_types.  */
163   offset_type symbol_table_slots;
164
165   /* A pointer to the constant pool.  */
166   const char *constant_pool;
167 };
168
169 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
170 DEF_VEC_P (dwarf2_per_cu_ptr);
171
172 /* Collection of data recorded per objfile.
173    This hangs off of dwarf2_objfile_data_key.  */
174
175 struct dwarf2_per_objfile
176 {
177   struct dwarf2_section_info info;
178   struct dwarf2_section_info abbrev;
179   struct dwarf2_section_info line;
180   struct dwarf2_section_info loc;
181   struct dwarf2_section_info macinfo;
182   struct dwarf2_section_info macro;
183   struct dwarf2_section_info str;
184   struct dwarf2_section_info ranges;
185   struct dwarf2_section_info addr;
186   struct dwarf2_section_info frame;
187   struct dwarf2_section_info eh_frame;
188   struct dwarf2_section_info gdb_index;
189
190   VEC (dwarf2_section_info_def) *types;
191
192   /* Back link.  */
193   struct objfile *objfile;
194
195   /* Table of all the compilation units.  This is used to locate
196      the target compilation unit of a particular reference.  */
197   struct dwarf2_per_cu_data **all_comp_units;
198
199   /* The number of compilation units in ALL_COMP_UNITS.  */
200   int n_comp_units;
201
202   /* The number of .debug_types-related CUs.  */
203   int n_type_units;
204
205   /* The .debug_types-related CUs (TUs).
206      This is stored in malloc space because we may realloc it.  */
207   struct signatured_type **all_type_units;
208
209   /* The number of entries in all_type_unit_groups.  */
210   int n_type_unit_groups;
211
212   /* Table of type unit groups.
213      This exists to make it easy to iterate over all CUs and TU groups.  */
214   struct type_unit_group **all_type_unit_groups;
215
216   /* Table of struct type_unit_group objects.
217      The hash key is the DW_AT_stmt_list value.  */
218   htab_t type_unit_groups;
219
220   /* A table mapping .debug_types signatures to its signatured_type entry.
221      This is NULL if the .debug_types section hasn't been read in yet.  */
222   htab_t signatured_types;
223
224   /* Type unit statistics, to see how well the scaling improvements
225      are doing.  */
226   struct tu_stats
227   {
228     int nr_uniq_abbrev_tables;
229     int nr_symtabs;
230     int nr_symtab_sharers;
231     int nr_stmt_less_type_units;
232   } tu_stats;
233
234   /* A chain of compilation units that are currently read in, so that
235      they can be freed later.  */
236   struct dwarf2_per_cu_data *read_in_chain;
237
238   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
239      This is NULL if the table hasn't been allocated yet.  */
240   htab_t dwo_files;
241
242   /* Non-zero if we've check for whether there is a DWP file.  */
243   int dwp_checked;
244
245   /* The DWP file if there is one, or NULL.  */
246   struct dwp_file *dwp_file;
247
248   /* The shared '.dwz' file, if one exists.  This is used when the
249      original data was compressed using 'dwz -m'.  */
250   struct dwz_file *dwz_file;
251
252   /* A flag indicating wether this objfile has a section loaded at a
253      VMA of 0.  */
254   int has_section_at_zero;
255
256   /* True if we are using the mapped index,
257      or we are faking it for OBJF_READNOW's sake.  */
258   unsigned char using_index;
259
260   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
261   struct mapped_index *index_table;
262
263   /* When using index_table, this keeps track of all quick_file_names entries.
264      TUs typically share line table entries with a CU, so we maintain a
265      separate table of all line table entries to support the sharing.
266      Note that while there can be way more TUs than CUs, we've already
267      sorted all the TUs into "type unit groups", grouped by their
268      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
269      CU and its associated TU group if there is one.  */
270   htab_t quick_file_names_table;
271
272   /* Set during partial symbol reading, to prevent queueing of full
273      symbols.  */
274   int reading_partial_symbols;
275
276   /* Table mapping type DIEs to their struct type *.
277      This is NULL if not allocated yet.
278      The mapping is done via (CU/TU + DIE offset) -> type.  */
279   htab_t die_type_hash;
280
281   /* The CUs we recently read.  */
282   VEC (dwarf2_per_cu_ptr) *just_read_cus;
283 };
284
285 static struct dwarf2_per_objfile *dwarf2_per_objfile;
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_macinfo", ".zdebug_macinfo" },
299   { ".debug_macro", ".zdebug_macro" },
300   { ".debug_str", ".zdebug_str" },
301   { ".debug_ranges", ".zdebug_ranges" },
302   { ".debug_types", ".zdebug_types" },
303   { ".debug_addr", ".zdebug_addr" },
304   { ".debug_frame", ".zdebug_frame" },
305   { ".eh_frame", NULL },
306   { ".gdb_index", ".zgdb_index" },
307   23
308 };
309
310 /* List of DWO/DWP sections.  */
311
312 static const struct dwop_section_names
313 {
314   struct dwarf2_section_names abbrev_dwo;
315   struct dwarf2_section_names info_dwo;
316   struct dwarf2_section_names line_dwo;
317   struct dwarf2_section_names loc_dwo;
318   struct dwarf2_section_names macinfo_dwo;
319   struct dwarf2_section_names macro_dwo;
320   struct dwarf2_section_names str_dwo;
321   struct dwarf2_section_names str_offsets_dwo;
322   struct dwarf2_section_names types_dwo;
323   struct dwarf2_section_names cu_index;
324   struct dwarf2_section_names tu_index;
325 }
326 dwop_section_names =
327 {
328   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
329   { ".debug_info.dwo", ".zdebug_info.dwo" },
330   { ".debug_line.dwo", ".zdebug_line.dwo" },
331   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
332   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
333   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
334   { ".debug_str.dwo", ".zdebug_str.dwo" },
335   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
336   { ".debug_types.dwo", ".zdebug_types.dwo" },
337   { ".debug_cu_index", ".zdebug_cu_index" },
338   { ".debug_tu_index", ".zdebug_tu_index" },
339 };
340
341 /* local data types */
342
343 /* The data in a compilation unit header, after target2host
344    translation, looks like this.  */
345 struct comp_unit_head
346 {
347   unsigned int length;
348   short version;
349   unsigned char addr_size;
350   unsigned char signed_addr_p;
351   sect_offset abbrev_offset;
352
353   /* Size of file offsets; either 4 or 8.  */
354   unsigned int offset_size;
355
356   /* Size of the length field; either 4 or 12.  */
357   unsigned int initial_length_size;
358
359   /* Offset to the first byte of this compilation unit header in the
360      .debug_info section, for resolving relative reference dies.  */
361   sect_offset offset;
362
363   /* Offset to first die in this cu from the start of the cu.
364      This will be the first byte following the compilation unit header.  */
365   cu_offset first_die_offset;
366 };
367
368 /* Type used for delaying computation of method physnames.
369    See comments for compute_delayed_physnames.  */
370 struct delayed_method_info
371 {
372   /* The type to which the method is attached, i.e., its parent class.  */
373   struct type *type;
374
375   /* The index of the method in the type's function fieldlists.  */
376   int fnfield_index;
377
378   /* The index of the method in the fieldlist.  */
379   int index;
380
381   /* The name of the DIE.  */
382   const char *name;
383
384   /*  The DIE associated with this method.  */
385   struct die_info *die;
386 };
387
388 typedef struct delayed_method_info delayed_method_info;
389 DEF_VEC_O (delayed_method_info);
390
391 /* Internal state when decoding a particular compilation unit.  */
392 struct dwarf2_cu
393 {
394   /* The objfile containing this compilation unit.  */
395   struct objfile *objfile;
396
397   /* The header of the compilation unit.  */
398   struct comp_unit_head header;
399
400   /* Base address of this compilation unit.  */
401   CORE_ADDR base_address;
402
403   /* Non-zero if base_address has been set.  */
404   int base_known;
405
406   /* The language we are debugging.  */
407   enum language language;
408   const struct language_defn *language_defn;
409
410   const char *producer;
411
412   /* The generic symbol table building routines have separate lists for
413      file scope symbols and all all other scopes (local scopes).  So
414      we need to select the right one to pass to add_symbol_to_list().
415      We do it by keeping a pointer to the correct list in list_in_scope.
416
417      FIXME: The original dwarf code just treated the file scope as the
418      first local scope, and all other local scopes as nested local
419      scopes, and worked fine.  Check to see if we really need to
420      distinguish these in buildsym.c.  */
421   struct pending **list_in_scope;
422
423   /* The abbrev table for this CU.
424      Normally this points to the abbrev table in the objfile.
425      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
426   struct abbrev_table *abbrev_table;
427
428   /* Hash table holding all the loaded partial DIEs
429      with partial_die->offset.SECT_OFF as hash.  */
430   htab_t partial_dies;
431
432   /* Storage for things with the same lifetime as this read-in compilation
433      unit, including partial DIEs.  */
434   struct obstack comp_unit_obstack;
435
436   /* When multiple dwarf2_cu structures are living in memory, this field
437      chains them all together, so that they can be released efficiently.
438      We will probably also want a generation counter so that most-recently-used
439      compilation units are cached...  */
440   struct dwarf2_per_cu_data *read_in_chain;
441
442   /* Backchain to our per_cu entry if the tree has been built.  */
443   struct dwarf2_per_cu_data *per_cu;
444
445   /* How many compilation units ago was this CU last referenced?  */
446   int last_used;
447
448   /* A hash table of DIE cu_offset for following references with
449      die_info->offset.sect_off as hash.  */
450   htab_t die_hash;
451
452   /* Full DIEs if read in.  */
453   struct die_info *dies;
454
455   /* A set of pointers to dwarf2_per_cu_data objects for compilation
456      units referenced by this one.  Only set during full symbol processing;
457      partial symbol tables do not have dependencies.  */
458   htab_t dependencies;
459
460   /* Header data from the line table, during full symbol processing.  */
461   struct line_header *line_header;
462
463   /* A list of methods which need to have physnames computed
464      after all type information has been read.  */
465   VEC (delayed_method_info) *method_list;
466
467   /* To be copied to symtab->call_site_htab.  */
468   htab_t call_site_htab;
469
470   /* Non-NULL if this CU came from a DWO file.
471      There is an invariant here that is important to remember:
472      Except for attributes copied from the top level DIE in the "main"
473      (or "stub") file in preparation for reading the DWO file
474      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
475      Either there isn't a DWO file (in which case this is NULL and the point
476      is moot), or there is and either we're not going to read it (in which
477      case this is NULL) or there is and we are reading it (in which case this
478      is non-NULL).  */
479   struct dwo_unit *dwo_unit;
480
481   /* The DW_AT_addr_base attribute if present, zero otherwise
482      (zero is a valid value though).
483      Note this value comes from the stub CU/TU's DIE.  */
484   ULONGEST addr_base;
485
486   /* The DW_AT_ranges_base attribute if present, zero otherwise
487      (zero is a valid value though).
488      Note this value comes from the stub CU/TU's DIE.
489      Also note that the value is zero in the non-DWO case so this value can
490      be used without needing to know whether DWO files are in use or not.
491      N.B. This does not apply to DW_AT_ranges appearing in
492      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
493      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
494      DW_AT_ranges_base *would* have to be applied, and we'd have to care
495      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
496   ULONGEST ranges_base;
497
498   /* Mark used when releasing cached dies.  */
499   unsigned int mark : 1;
500
501   /* This CU references .debug_loc.  See the symtab->locations_valid field.
502      This test is imperfect as there may exist optimized debug code not using
503      any location list and still facing inlining issues if handled as
504      unoptimized code.  For a future better test see GCC PR other/32998.  */
505   unsigned int has_loclist : 1;
506
507   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
508      if all the producer_is_* fields are valid.  This information is cached
509      because profiling CU expansion showed excessive time spent in
510      producer_is_gxx_lt_4_6.  */
511   unsigned int checked_producer : 1;
512   unsigned int producer_is_gxx_lt_4_6 : 1;
513   unsigned int producer_is_gcc_lt_4_3 : 1;
514   unsigned int producer_is_icc : 1;
515
516   /* When set, the file that we're processing is known to have
517      debugging info for C++ namespaces.  GCC 3.3.x did not produce
518      this information, but later versions do.  */
519
520   unsigned int processing_has_namespace_info : 1;
521 };
522
523 /* Persistent data held for a compilation unit, even when not
524    processing it.  We put a pointer to this structure in the
525    read_symtab_private field of the psymtab.  */
526
527 struct dwarf2_per_cu_data
528 {
529   /* The start offset and length of this compilation unit.
530      NOTE: Unlike comp_unit_head.length, this length includes
531      initial_length_size.
532      If the DIE refers to a DWO file, this is always of the original die,
533      not the DWO file.  */
534   sect_offset offset;
535   unsigned int length;
536
537   /* Flag indicating this compilation unit will be read in before
538      any of the current compilation units are processed.  */
539   unsigned int queued : 1;
540
541   /* This flag will be set when reading partial DIEs if we need to load
542      absolutely all DIEs for this compilation unit, instead of just the ones
543      we think are interesting.  It gets set if we look for a DIE in the
544      hash table and don't find it.  */
545   unsigned int load_all_dies : 1;
546
547   /* Non-zero if this CU is from .debug_types.
548      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
549      this is non-zero.  */
550   unsigned int is_debug_types : 1;
551
552   /* Non-zero if this CU is from the .dwz file.  */
553   unsigned int is_dwz : 1;
554
555   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
556      This flag is only valid if is_debug_types is true.
557      We can't read a CU directly from a DWO file: There are required
558      attributes in the stub.  */
559   unsigned int reading_dwo_directly : 1;
560
561   /* Non-zero if the TU has been read.
562      This is used to assist the "Stay in DWO Optimization" for Fission:
563      When reading a DWO, it's faster to read TUs from the DWO instead of
564      fetching them from random other DWOs (due to comdat folding).
565      If the TU has already been read, the optimization is unnecessary
566      (and unwise - we don't want to change where gdb thinks the TU lives
567      "midflight").
568      This flag is only valid if is_debug_types is true.  */
569   unsigned int tu_read : 1;
570
571   /* The section this CU/TU lives in.
572      If the DIE refers to a DWO file, this is always the original die,
573      not the DWO file.  */
574   struct dwarf2_section_info *section;
575
576   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
577      of the CU cache it gets reset to NULL again.  */
578   struct dwarf2_cu *cu;
579
580   /* The corresponding objfile.
581      Normally we can get the objfile from dwarf2_per_objfile.
582      However we can enter this file with just a "per_cu" handle.  */
583   struct objfile *objfile;
584
585   /* When using partial symbol tables, the 'psymtab' field is active.
586      Otherwise the 'quick' field is active.  */
587   union
588   {
589     /* The partial symbol table associated with this compilation unit,
590        or NULL for unread partial units.  */
591     struct partial_symtab *psymtab;
592
593     /* Data needed by the "quick" functions.  */
594     struct dwarf2_per_cu_quick_data *quick;
595   } v;
596
597   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
598      while reading psymtabs, used to compute the psymtab dependencies,
599      and then cleared.  Then it is filled in again while reading full
600      symbols, and only deleted when the objfile is destroyed.
601
602      This is also used to work around a difference between the way gold
603      generates .gdb_index version <=7 and the way gdb does.  Arguably this
604      is a gold bug.  For symbols coming from TUs, gold records in the index
605      the CU that includes the TU instead of the TU itself.  This breaks
606      dw2_lookup_symbol: It assumes that if the index says symbol X lives
607      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
608      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
609      we need to look in TU Z to find X.  Fortunately, this is akin to
610      DW_TAG_imported_unit, so we just use the same mechanism: For
611      .gdb_index version <=7 this also records the TUs that the CU referred
612      to.  Concurrently with this change gdb was modified to emit version 8
613      indices so we only pay a price for gold generated indices.  */
614   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
615 };
616
617 /* Entry in the signatured_types hash table.  */
618
619 struct signatured_type
620 {
621   /* The "per_cu" object of this type.
622      This struct is used iff per_cu.is_debug_types.
623      N.B.: This is the first member so that it's easy to convert pointers
624      between them.  */
625   struct dwarf2_per_cu_data per_cu;
626
627   /* The type's signature.  */
628   ULONGEST signature;
629
630   /* Offset in the TU of the type's DIE, as read from the TU header.
631      If this TU is a DWO stub and the definition lives in a DWO file
632      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
633   cu_offset type_offset_in_tu;
634
635   /* Offset in the section of the type's DIE.
636      If the definition lives in a DWO file, this is the offset in the
637      .debug_types.dwo section.
638      The value is zero until the actual value is known.
639      Zero is otherwise not a valid section offset.  */
640   sect_offset type_offset_in_section;
641
642   /* Type units are grouped by their DW_AT_stmt_list entry so that they
643      can share them.  This points to the containing symtab.  */
644   struct type_unit_group *type_unit_group;
645
646   /* The type.
647      The first time we encounter this type we fully read it in and install it
648      in the symbol tables.  Subsequent times we only need the type.  */
649   struct type *type;
650
651   /* Containing DWO unit.
652      This field is valid iff per_cu.reading_dwo_directly.  */
653   struct dwo_unit *dwo_unit;
654 };
655
656 typedef struct signatured_type *sig_type_ptr;
657 DEF_VEC_P (sig_type_ptr);
658
659 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
660    This includes type_unit_group and quick_file_names.  */
661
662 struct stmt_list_hash
663 {
664   /* The DWO unit this table is from or NULL if there is none.  */
665   struct dwo_unit *dwo_unit;
666
667   /* Offset in .debug_line or .debug_line.dwo.  */
668   sect_offset line_offset;
669 };
670
671 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
672    an object of this type.  */
673
674 struct type_unit_group
675 {
676   /* dwarf2read.c's main "handle" on a TU symtab.
677      To simplify things we create an artificial CU that "includes" all the
678      type units using this stmt_list so that the rest of the code still has
679      a "per_cu" handle on the symtab.
680      This PER_CU is recognized by having no section.  */
681 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
682   struct dwarf2_per_cu_data per_cu;
683
684   /* The TUs that share this DW_AT_stmt_list entry.
685      This is added to while parsing type units to build partial symtabs,
686      and is deleted afterwards and not used again.  */
687   VEC (sig_type_ptr) *tus;
688
689   /* The primary symtab.
690      Type units in a group needn't all be defined in the same source file,
691      so we create an essentially anonymous symtab as the primary symtab.  */
692   struct symtab *primary_symtab;
693
694   /* The data used to construct the hash key.  */
695   struct stmt_list_hash hash;
696
697   /* The number of symtabs from the line header.
698      The value here must match line_header.num_file_names.  */
699   unsigned int num_symtabs;
700
701   /* The symbol tables for this TU (obtained from the files listed in
702      DW_AT_stmt_list).
703      WARNING: The order of entries here must match the order of entries
704      in the line header.  After the first TU using this type_unit_group, the
705      line header for the subsequent TUs is recreated from this.  This is done
706      because we need to use the same symtabs for each TU using the same
707      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
708      there's no guarantee the line header doesn't have duplicate entries.  */
709   struct symtab **symtabs;
710 };
711
712 /* These sections are what may appear in a DWO file.  */
713
714 struct dwo_sections
715 {
716   struct dwarf2_section_info abbrev;
717   struct dwarf2_section_info line;
718   struct dwarf2_section_info loc;
719   struct dwarf2_section_info macinfo;
720   struct dwarf2_section_info macro;
721   struct dwarf2_section_info str;
722   struct dwarf2_section_info str_offsets;
723   /* In the case of a virtual DWO file, these two are unused.  */
724   struct dwarf2_section_info info;
725   VEC (dwarf2_section_info_def) *types;
726 };
727
728 /* CUs/TUs in DWP/DWO files.  */
729
730 struct dwo_unit
731 {
732   /* Backlink to the containing struct dwo_file.  */
733   struct dwo_file *dwo_file;
734
735   /* The "id" that distinguishes this CU/TU.
736      .debug_info calls this "dwo_id", .debug_types calls this "signature".
737      Since signatures came first, we stick with it for consistency.  */
738   ULONGEST signature;
739
740   /* The section this CU/TU lives in, in the DWO file.  */
741   struct dwarf2_section_info *section;
742
743   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
744   sect_offset offset;
745   unsigned int length;
746
747   /* For types, offset in the type's DIE of the type defined by this TU.  */
748   cu_offset type_offset_in_tu;
749 };
750
751 /* Data for one DWO file.
752    This includes virtual DWO files that have been packaged into a
753    DWP file.  */
754
755 struct dwo_file
756 {
757   /* The DW_AT_GNU_dwo_name attribute.
758      For virtual DWO files the name is constructed from the section offsets
759      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
760      from related CU+TUs.  */
761   const char *dwo_name;
762
763   /* The DW_AT_comp_dir attribute.  */
764   const char *comp_dir;
765
766   /* The bfd, when the file is open.  Otherwise this is NULL.
767      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
768   bfd *dbfd;
769
770   /* Section info for this file.  */
771   struct dwo_sections sections;
772
773   /* The CU in the file.
774      We only support one because having more than one requires hacking the
775      dwo_name of each to match, which is highly unlikely to happen.
776      Doing this means all TUs can share comp_dir: We also assume that
777      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
778   struct dwo_unit *cu;
779
780   /* Table of TUs in the file.
781      Each element is a struct dwo_unit.  */
782   htab_t tus;
783 };
784
785 /* These sections are what may appear in a DWP file.  */
786
787 struct dwp_sections
788 {
789   struct dwarf2_section_info str;
790   struct dwarf2_section_info cu_index;
791   struct dwarf2_section_info tu_index;
792   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
793      by section number.  We don't need to record them here.  */
794 };
795
796 /* These sections are what may appear in a virtual DWO file.  */
797
798 struct virtual_dwo_sections
799 {
800   struct dwarf2_section_info abbrev;
801   struct dwarf2_section_info line;
802   struct dwarf2_section_info loc;
803   struct dwarf2_section_info macinfo;
804   struct dwarf2_section_info macro;
805   struct dwarf2_section_info str_offsets;
806   /* Each DWP hash table entry records one CU or one TU.
807      That is recorded here, and copied to dwo_unit.section.  */
808   struct dwarf2_section_info info_or_types;
809 };
810
811 /* Contents of DWP hash tables.  */
812
813 struct dwp_hash_table
814 {
815   uint32_t nr_units, nr_slots;
816   const gdb_byte *hash_table, *unit_table, *section_pool;
817 };
818
819 /* Data for one DWP file.  */
820
821 struct dwp_file
822 {
823   /* Name of the file.  */
824   const char *name;
825
826   /* The bfd.  */
827   bfd *dbfd;
828
829   /* Section info for this file.  */
830   struct dwp_sections sections;
831
832   /* Table of CUs in the file. */
833   const struct dwp_hash_table *cus;
834
835   /* Table of TUs in the file.  */
836   const struct dwp_hash_table *tus;
837
838   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
839   htab_t loaded_cutus;
840
841   /* Table to map ELF section numbers to their sections.  */
842   unsigned int num_sections;
843   asection **elf_sections;
844 };
845
846 /* This represents a '.dwz' file.  */
847
848 struct dwz_file
849 {
850   /* A dwz file can only contain a few sections.  */
851   struct dwarf2_section_info abbrev;
852   struct dwarf2_section_info info;
853   struct dwarf2_section_info str;
854   struct dwarf2_section_info line;
855   struct dwarf2_section_info macro;
856   struct dwarf2_section_info gdb_index;
857
858   /* The dwz's BFD.  */
859   bfd *dwz_bfd;
860 };
861
862 /* Struct used to pass misc. parameters to read_die_and_children, et
863    al.  which are used for both .debug_info and .debug_types dies.
864    All parameters here are unchanging for the life of the call.  This
865    struct exists to abstract away the constant parameters of die reading.  */
866
867 struct die_reader_specs
868 {
869   /* die_section->asection->owner.  */
870   bfd* abfd;
871
872   /* The CU of the DIE we are parsing.  */
873   struct dwarf2_cu *cu;
874
875   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
876   struct dwo_file *dwo_file;
877
878   /* The section the die comes from.
879      This is either .debug_info or .debug_types, or the .dwo variants.  */
880   struct dwarf2_section_info *die_section;
881
882   /* die_section->buffer.  */
883   const gdb_byte *buffer;
884
885   /* The end of the buffer.  */
886   const gdb_byte *buffer_end;
887
888   /* The value of the DW_AT_comp_dir attribute.  */
889   const char *comp_dir;
890 };
891
892 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
893 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
894                                       const gdb_byte *info_ptr,
895                                       struct die_info *comp_unit_die,
896                                       int has_children,
897                                       void *data);
898
899 /* The line number information for a compilation unit (found in the
900    .debug_line section) begins with a "statement program header",
901    which contains the following information.  */
902 struct line_header
903 {
904   unsigned int total_length;
905   unsigned short version;
906   unsigned int header_length;
907   unsigned char minimum_instruction_length;
908   unsigned char maximum_ops_per_instruction;
909   unsigned char default_is_stmt;
910   int line_base;
911   unsigned char line_range;
912   unsigned char opcode_base;
913
914   /* standard_opcode_lengths[i] is the number of operands for the
915      standard opcode whose value is i.  This means that
916      standard_opcode_lengths[0] is unused, and the last meaningful
917      element is standard_opcode_lengths[opcode_base - 1].  */
918   unsigned char *standard_opcode_lengths;
919
920   /* The include_directories table.  NOTE!  These strings are not
921      allocated with xmalloc; instead, they are pointers into
922      debug_line_buffer.  If you try to free them, `free' will get
923      indigestion.  */
924   unsigned int num_include_dirs, include_dirs_size;
925   const char **include_dirs;
926
927   /* The file_names table.  NOTE!  These strings are not allocated
928      with xmalloc; instead, they are pointers into debug_line_buffer.
929      Don't try to free them directly.  */
930   unsigned int num_file_names, file_names_size;
931   struct file_entry
932   {
933     const char *name;
934     unsigned int dir_index;
935     unsigned int mod_time;
936     unsigned int length;
937     int included_p; /* Non-zero if referenced by the Line Number Program.  */
938     struct symtab *symtab; /* The associated symbol table, if any.  */
939   } *file_names;
940
941   /* The start and end of the statement program following this
942      header.  These point into dwarf2_per_objfile->line_buffer.  */
943   const gdb_byte *statement_program_start, *statement_program_end;
944 };
945
946 /* When we construct a partial symbol table entry we only
947    need this much information.  */
948 struct partial_die_info
949   {
950     /* Offset of this DIE.  */
951     sect_offset offset;
952
953     /* DWARF-2 tag for this DIE.  */
954     ENUM_BITFIELD(dwarf_tag) tag : 16;
955
956     /* Assorted flags describing the data found in this DIE.  */
957     unsigned int has_children : 1;
958     unsigned int is_external : 1;
959     unsigned int is_declaration : 1;
960     unsigned int has_type : 1;
961     unsigned int has_specification : 1;
962     unsigned int has_pc_info : 1;
963     unsigned int may_be_inlined : 1;
964
965     /* Flag set if the SCOPE field of this structure has been
966        computed.  */
967     unsigned int scope_set : 1;
968
969     /* Flag set if the DIE has a byte_size attribute.  */
970     unsigned int has_byte_size : 1;
971
972     /* Flag set if any of the DIE's children are template arguments.  */
973     unsigned int has_template_arguments : 1;
974
975     /* Flag set if fixup_partial_die has been called on this die.  */
976     unsigned int fixup_called : 1;
977
978     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
979     unsigned int is_dwz : 1;
980
981     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
982     unsigned int spec_is_dwz : 1;
983
984     /* The name of this DIE.  Normally the value of DW_AT_name, but
985        sometimes a default name for unnamed DIEs.  */
986     const char *name;
987
988     /* The linkage name, if present.  */
989     const char *linkage_name;
990
991     /* The scope to prepend to our children.  This is generally
992        allocated on the comp_unit_obstack, so will disappear
993        when this compilation unit leaves the cache.  */
994     const char *scope;
995
996     /* Some data associated with the partial DIE.  The tag determines
997        which field is live.  */
998     union
999     {
1000       /* The location description associated with this DIE, if any.  */
1001       struct dwarf_block *locdesc;
1002       /* The offset of an import, for DW_TAG_imported_unit.  */
1003       sect_offset offset;
1004     } d;
1005
1006     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1007     CORE_ADDR lowpc;
1008     CORE_ADDR highpc;
1009
1010     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1011        DW_AT_sibling, if any.  */
1012     /* NOTE: This member isn't strictly necessary, read_partial_die could
1013        return DW_AT_sibling values to its caller load_partial_dies.  */
1014     const gdb_byte *sibling;
1015
1016     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1017        DW_AT_specification (or DW_AT_abstract_origin or
1018        DW_AT_extension).  */
1019     sect_offset spec_offset;
1020
1021     /* Pointers to this DIE's parent, first child, and next sibling,
1022        if any.  */
1023     struct partial_die_info *die_parent, *die_child, *die_sibling;
1024   };
1025
1026 /* This data structure holds the information of an abbrev.  */
1027 struct abbrev_info
1028   {
1029     unsigned int number;        /* number identifying abbrev */
1030     enum dwarf_tag tag;         /* dwarf tag */
1031     unsigned short has_children;                /* boolean */
1032     unsigned short num_attrs;   /* number of attributes */
1033     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1034     struct abbrev_info *next;   /* next in chain */
1035   };
1036
1037 struct attr_abbrev
1038   {
1039     ENUM_BITFIELD(dwarf_attribute) name : 16;
1040     ENUM_BITFIELD(dwarf_form) form : 16;
1041   };
1042
1043 /* Size of abbrev_table.abbrev_hash_table.  */
1044 #define ABBREV_HASH_SIZE 121
1045
1046 /* Top level data structure to contain an abbreviation table.  */
1047
1048 struct abbrev_table
1049 {
1050   /* Where the abbrev table came from.
1051      This is used as a sanity check when the table is used.  */
1052   sect_offset offset;
1053
1054   /* Storage for the abbrev table.  */
1055   struct obstack abbrev_obstack;
1056
1057   /* Hash table of abbrevs.
1058      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1059      It could be statically allocated, but the previous code didn't so we
1060      don't either.  */
1061   struct abbrev_info **abbrevs;
1062 };
1063
1064 /* Attributes have a name and a value.  */
1065 struct attribute
1066   {
1067     ENUM_BITFIELD(dwarf_attribute) name : 16;
1068     ENUM_BITFIELD(dwarf_form) form : 15;
1069
1070     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1071        field should be in u.str (existing only for DW_STRING) but it is kept
1072        here for better struct attribute alignment.  */
1073     unsigned int string_is_canonical : 1;
1074
1075     union
1076       {
1077         const char *str;
1078         struct dwarf_block *blk;
1079         ULONGEST unsnd;
1080         LONGEST snd;
1081         CORE_ADDR addr;
1082         ULONGEST signature;
1083       }
1084     u;
1085   };
1086
1087 /* This data structure holds a complete die structure.  */
1088 struct die_info
1089   {
1090     /* DWARF-2 tag for this DIE.  */
1091     ENUM_BITFIELD(dwarf_tag) tag : 16;
1092
1093     /* Number of attributes */
1094     unsigned char num_attrs;
1095
1096     /* True if we're presently building the full type name for the
1097        type derived from this DIE.  */
1098     unsigned char building_fullname : 1;
1099
1100     /* Abbrev number */
1101     unsigned int abbrev;
1102
1103     /* Offset in .debug_info or .debug_types section.  */
1104     sect_offset offset;
1105
1106     /* The dies in a compilation unit form an n-ary tree.  PARENT
1107        points to this die's parent; CHILD points to the first child of
1108        this node; and all the children of a given node are chained
1109        together via their SIBLING fields.  */
1110     struct die_info *child;     /* Its first child, if any.  */
1111     struct die_info *sibling;   /* Its next sibling, if any.  */
1112     struct die_info *parent;    /* Its parent, if any.  */
1113
1114     /* An array of attributes, with NUM_ATTRS elements.  There may be
1115        zero, but it's not common and zero-sized arrays are not
1116        sufficiently portable C.  */
1117     struct attribute attrs[1];
1118   };
1119
1120 /* Get at parts of an attribute structure.  */
1121
1122 #define DW_STRING(attr)    ((attr)->u.str)
1123 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1124 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1125 #define DW_BLOCK(attr)     ((attr)->u.blk)
1126 #define DW_SND(attr)       ((attr)->u.snd)
1127 #define DW_ADDR(attr)      ((attr)->u.addr)
1128 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1129
1130 /* Blocks are a bunch of untyped bytes.  */
1131 struct dwarf_block
1132   {
1133     size_t size;
1134
1135     /* Valid only if SIZE is not zero.  */
1136     const gdb_byte *data;
1137   };
1138
1139 #ifndef ATTR_ALLOC_CHUNK
1140 #define ATTR_ALLOC_CHUNK 4
1141 #endif
1142
1143 /* Allocate fields for structs, unions and enums in this size.  */
1144 #ifndef DW_FIELD_ALLOC_CHUNK
1145 #define DW_FIELD_ALLOC_CHUNK 4
1146 #endif
1147
1148 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1149    but this would require a corresponding change in unpack_field_as_long
1150    and friends.  */
1151 static int bits_per_byte = 8;
1152
1153 /* The routines that read and process dies for a C struct or C++ class
1154    pass lists of data member fields and lists of member function fields
1155    in an instance of a field_info structure, as defined below.  */
1156 struct field_info
1157   {
1158     /* List of data member and baseclasses fields.  */
1159     struct nextfield
1160       {
1161         struct nextfield *next;
1162         int accessibility;
1163         int virtuality;
1164         struct field field;
1165       }
1166      *fields, *baseclasses;
1167
1168     /* Number of fields (including baseclasses).  */
1169     int nfields;
1170
1171     /* Number of baseclasses.  */
1172     int nbaseclasses;
1173
1174     /* Set if the accesibility of one of the fields is not public.  */
1175     int non_public_fields;
1176
1177     /* Member function fields array, entries are allocated in the order they
1178        are encountered in the object file.  */
1179     struct nextfnfield
1180       {
1181         struct nextfnfield *next;
1182         struct fn_field fnfield;
1183       }
1184      *fnfields;
1185
1186     /* Member function fieldlist array, contains name of possibly overloaded
1187        member function, number of overloaded member functions and a pointer
1188        to the head of the member function field chain.  */
1189     struct fnfieldlist
1190       {
1191         const char *name;
1192         int length;
1193         struct nextfnfield *head;
1194       }
1195      *fnfieldlists;
1196
1197     /* Number of entries in the fnfieldlists array.  */
1198     int nfnfields;
1199
1200     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1201        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1202     struct typedef_field_list
1203       {
1204         struct typedef_field field;
1205         struct typedef_field_list *next;
1206       }
1207     *typedef_field_list;
1208     unsigned typedef_field_list_count;
1209   };
1210
1211 /* One item on the queue of compilation units to read in full symbols
1212    for.  */
1213 struct dwarf2_queue_item
1214 {
1215   struct dwarf2_per_cu_data *per_cu;
1216   enum language pretend_language;
1217   struct dwarf2_queue_item *next;
1218 };
1219
1220 /* The current queue.  */
1221 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1222
1223 /* Loaded secondary compilation units are kept in memory until they
1224    have not been referenced for the processing of this many
1225    compilation units.  Set this to zero to disable caching.  Cache
1226    sizes of up to at least twenty will improve startup time for
1227    typical inter-CU-reference binaries, at an obvious memory cost.  */
1228 static int dwarf2_max_cache_age = 5;
1229 static void
1230 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1231                            struct cmd_list_element *c, const char *value)
1232 {
1233   fprintf_filtered (file, _("The upper bound on the age of cached "
1234                             "dwarf2 compilation units is %s.\n"),
1235                     value);
1236 }
1237
1238
1239 /* Various complaints about symbol reading that don't abort the process.  */
1240
1241 static void
1242 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1243 {
1244   complaint (&symfile_complaints,
1245              _("statement list doesn't fit in .debug_line section"));
1246 }
1247
1248 static void
1249 dwarf2_debug_line_missing_file_complaint (void)
1250 {
1251   complaint (&symfile_complaints,
1252              _(".debug_line section has line data without a file"));
1253 }
1254
1255 static void
1256 dwarf2_debug_line_missing_end_sequence_complaint (void)
1257 {
1258   complaint (&symfile_complaints,
1259              _(".debug_line section has line "
1260                "program sequence without an end"));
1261 }
1262
1263 static void
1264 dwarf2_complex_location_expr_complaint (void)
1265 {
1266   complaint (&symfile_complaints, _("location expression too complex"));
1267 }
1268
1269 static void
1270 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1271                                               int arg3)
1272 {
1273   complaint (&symfile_complaints,
1274              _("const value length mismatch for '%s', got %d, expected %d"),
1275              arg1, arg2, arg3);
1276 }
1277
1278 static void
1279 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1280 {
1281   complaint (&symfile_complaints,
1282              _("debug info runs off end of %s section"
1283                " [in module %s]"),
1284              section->asection->name,
1285              bfd_get_filename (section->asection->owner));
1286 }
1287
1288 static void
1289 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1290 {
1291   complaint (&symfile_complaints,
1292              _("macro debug info contains a "
1293                "malformed macro definition:\n`%s'"),
1294              arg1);
1295 }
1296
1297 static void
1298 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1299 {
1300   complaint (&symfile_complaints,
1301              _("invalid attribute class or form for '%s' in '%s'"),
1302              arg1, arg2);
1303 }
1304
1305 /* local function prototypes */
1306
1307 static void dwarf2_locate_sections (bfd *, asection *, void *);
1308
1309 static void dwarf2_find_base_address (struct die_info *die,
1310                                       struct dwarf2_cu *cu);
1311
1312 static struct partial_symtab *create_partial_symtab
1313   (struct dwarf2_per_cu_data *per_cu, const char *name);
1314
1315 static void dwarf2_build_psymtabs_hard (struct objfile *);
1316
1317 static void scan_partial_symbols (struct partial_die_info *,
1318                                   CORE_ADDR *, CORE_ADDR *,
1319                                   int, struct dwarf2_cu *);
1320
1321 static void add_partial_symbol (struct partial_die_info *,
1322                                 struct dwarf2_cu *);
1323
1324 static void add_partial_namespace (struct partial_die_info *pdi,
1325                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1326                                    int need_pc, struct dwarf2_cu *cu);
1327
1328 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1329                                 CORE_ADDR *highpc, int need_pc,
1330                                 struct dwarf2_cu *cu);
1331
1332 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1333                                      struct dwarf2_cu *cu);
1334
1335 static void add_partial_subprogram (struct partial_die_info *pdi,
1336                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1337                                     int need_pc, struct dwarf2_cu *cu);
1338
1339 static void dwarf2_read_symtab (struct partial_symtab *,
1340                                 struct objfile *);
1341
1342 static void psymtab_to_symtab_1 (struct partial_symtab *);
1343
1344 static struct abbrev_info *abbrev_table_lookup_abbrev
1345   (const struct abbrev_table *, unsigned int);
1346
1347 static struct abbrev_table *abbrev_table_read_table
1348   (struct dwarf2_section_info *, sect_offset);
1349
1350 static void abbrev_table_free (struct abbrev_table *);
1351
1352 static void abbrev_table_free_cleanup (void *);
1353
1354 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1355                                  struct dwarf2_section_info *);
1356
1357 static void dwarf2_free_abbrev_table (void *);
1358
1359 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1360
1361 static struct partial_die_info *load_partial_dies
1362   (const struct die_reader_specs *, const gdb_byte *, int);
1363
1364 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1365                                          struct partial_die_info *,
1366                                          struct abbrev_info *,
1367                                          unsigned int,
1368                                          const gdb_byte *);
1369
1370 static struct partial_die_info *find_partial_die (sect_offset, int,
1371                                                   struct dwarf2_cu *);
1372
1373 static void fixup_partial_die (struct partial_die_info *,
1374                                struct dwarf2_cu *);
1375
1376 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1377                                        struct attribute *, struct attr_abbrev *,
1378                                        const gdb_byte *);
1379
1380 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1381
1382 static int read_1_signed_byte (bfd *, const gdb_byte *);
1383
1384 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1385
1386 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1387
1388 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1389
1390 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1391                                unsigned int *);
1392
1393 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1394
1395 static LONGEST read_checked_initial_length_and_offset
1396   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1397    unsigned int *, unsigned int *);
1398
1399 static LONGEST read_offset (bfd *, const gdb_byte *,
1400                             const struct comp_unit_head *,
1401                             unsigned int *);
1402
1403 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1404
1405 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1406                                        sect_offset);
1407
1408 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1409
1410 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1411
1412 static const char *read_indirect_string (bfd *, const gdb_byte *,
1413                                          const struct comp_unit_head *,
1414                                          unsigned int *);
1415
1416 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1417
1418 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1419
1420 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1421
1422 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1423                                               const gdb_byte *,
1424                                               unsigned int *);
1425
1426 static const char *read_str_index (const struct die_reader_specs *reader,
1427                                    struct dwarf2_cu *cu, ULONGEST str_index);
1428
1429 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1430
1431 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1432                                       struct dwarf2_cu *);
1433
1434 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1435                                                 unsigned int);
1436
1437 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1438                                struct dwarf2_cu *cu);
1439
1440 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1441
1442 static struct die_info *die_specification (struct die_info *die,
1443                                            struct dwarf2_cu **);
1444
1445 static void free_line_header (struct line_header *lh);
1446
1447 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1448                                                      struct dwarf2_cu *cu);
1449
1450 static void dwarf_decode_lines (struct line_header *, const char *,
1451                                 struct dwarf2_cu *, struct partial_symtab *,
1452                                 int);
1453
1454 static void dwarf2_start_subfile (const char *, const char *, const char *);
1455
1456 static void dwarf2_start_symtab (struct dwarf2_cu *,
1457                                  const char *, const char *, CORE_ADDR);
1458
1459 static struct symbol *new_symbol (struct die_info *, struct type *,
1460                                   struct dwarf2_cu *);
1461
1462 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1463                                        struct dwarf2_cu *, struct symbol *);
1464
1465 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1466                                 struct dwarf2_cu *);
1467
1468 static void dwarf2_const_value_attr (const struct attribute *attr,
1469                                      struct type *type,
1470                                      const char *name,
1471                                      struct obstack *obstack,
1472                                      struct dwarf2_cu *cu, LONGEST *value,
1473                                      const gdb_byte **bytes,
1474                                      struct dwarf2_locexpr_baton **baton);
1475
1476 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1477
1478 static int need_gnat_info (struct dwarf2_cu *);
1479
1480 static struct type *die_descriptive_type (struct die_info *,
1481                                           struct dwarf2_cu *);
1482
1483 static void set_descriptive_type (struct type *, struct die_info *,
1484                                   struct dwarf2_cu *);
1485
1486 static struct type *die_containing_type (struct die_info *,
1487                                          struct dwarf2_cu *);
1488
1489 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1490                                      struct dwarf2_cu *);
1491
1492 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1493
1494 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1495
1496 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1497
1498 static char *typename_concat (struct obstack *obs, const char *prefix,
1499                               const char *suffix, int physname,
1500                               struct dwarf2_cu *cu);
1501
1502 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1503
1504 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1505
1506 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1507
1508 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1509
1510 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1511
1512 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1513                                struct dwarf2_cu *, struct partial_symtab *);
1514
1515 static int dwarf2_get_pc_bounds (struct die_info *,
1516                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1517                                  struct partial_symtab *);
1518
1519 static void get_scope_pc_bounds (struct die_info *,
1520                                  CORE_ADDR *, CORE_ADDR *,
1521                                  struct dwarf2_cu *);
1522
1523 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1524                                         CORE_ADDR, struct dwarf2_cu *);
1525
1526 static void dwarf2_add_field (struct field_info *, struct die_info *,
1527                               struct dwarf2_cu *);
1528
1529 static void dwarf2_attach_fields_to_type (struct field_info *,
1530                                           struct type *, struct dwarf2_cu *);
1531
1532 static void dwarf2_add_member_fn (struct field_info *,
1533                                   struct die_info *, struct type *,
1534                                   struct dwarf2_cu *);
1535
1536 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1537                                              struct type *,
1538                                              struct dwarf2_cu *);
1539
1540 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1541
1542 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1543
1544 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1545
1546 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1547
1548 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1549
1550 static struct type *read_module_type (struct die_info *die,
1551                                       struct dwarf2_cu *cu);
1552
1553 static const char *namespace_name (struct die_info *die,
1554                                    int *is_anonymous, struct dwarf2_cu *);
1555
1556 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1557
1558 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1559
1560 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1561                                                        struct dwarf2_cu *);
1562
1563 static struct die_info *read_die_and_siblings_1
1564   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1565    struct die_info *);
1566
1567 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1568                                                const gdb_byte *info_ptr,
1569                                                const gdb_byte **new_info_ptr,
1570                                                struct die_info *parent);
1571
1572 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1573                                         struct die_info **, const gdb_byte *,
1574                                         int *, int);
1575
1576 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1577                                       struct die_info **, const gdb_byte *,
1578                                       int *);
1579
1580 static void process_die (struct die_info *, struct dwarf2_cu *);
1581
1582 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1583                                              struct obstack *);
1584
1585 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1586
1587 static const char *dwarf2_full_name (const char *name,
1588                                      struct die_info *die,
1589                                      struct dwarf2_cu *cu);
1590
1591 static const char *dwarf2_physname (const char *name, struct die_info *die,
1592                                     struct dwarf2_cu *cu);
1593
1594 static struct die_info *dwarf2_extension (struct die_info *die,
1595                                           struct dwarf2_cu **);
1596
1597 static const char *dwarf_tag_name (unsigned int);
1598
1599 static const char *dwarf_attr_name (unsigned int);
1600
1601 static const char *dwarf_form_name (unsigned int);
1602
1603 static char *dwarf_bool_name (unsigned int);
1604
1605 static const char *dwarf_type_encoding_name (unsigned int);
1606
1607 static struct die_info *sibling_die (struct die_info *);
1608
1609 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1610
1611 static void dump_die_for_error (struct die_info *);
1612
1613 static void dump_die_1 (struct ui_file *, int level, int max_level,
1614                         struct die_info *);
1615
1616 /*static*/ void dump_die (struct die_info *, int max_level);
1617
1618 static void store_in_ref_table (struct die_info *,
1619                                 struct dwarf2_cu *);
1620
1621 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1622
1623 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1624
1625 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1626                                                const struct attribute *,
1627                                                struct dwarf2_cu **);
1628
1629 static struct die_info *follow_die_ref (struct die_info *,
1630                                         const struct attribute *,
1631                                         struct dwarf2_cu **);
1632
1633 static struct die_info *follow_die_sig (struct die_info *,
1634                                         const struct attribute *,
1635                                         struct dwarf2_cu **);
1636
1637 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1638                                          struct dwarf2_cu *);
1639
1640 static struct type *get_DW_AT_signature_type (struct die_info *,
1641                                               const struct attribute *,
1642                                               struct dwarf2_cu *);
1643
1644 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1645
1646 static void read_signatured_type (struct signatured_type *);
1647
1648 static struct type_unit_group *get_type_unit_group
1649     (struct dwarf2_cu *, const struct attribute *);
1650
1651 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1652
1653 /* memory allocation interface */
1654
1655 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1656
1657 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1658
1659 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1660                                  const char *, int);
1661
1662 static int attr_form_is_block (const struct attribute *);
1663
1664 static int attr_form_is_section_offset (const struct attribute *);
1665
1666 static int attr_form_is_constant (const struct attribute *);
1667
1668 static int attr_form_is_ref (const struct attribute *);
1669
1670 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1671                                    struct dwarf2_loclist_baton *baton,
1672                                    const struct attribute *attr);
1673
1674 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1675                                          struct symbol *sym,
1676                                          struct dwarf2_cu *cu,
1677                                          int is_block);
1678
1679 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1680                                      const gdb_byte *info_ptr,
1681                                      struct abbrev_info *abbrev);
1682
1683 static void free_stack_comp_unit (void *);
1684
1685 static hashval_t partial_die_hash (const void *item);
1686
1687 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1688
1689 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1690   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1691
1692 static void init_one_comp_unit (struct dwarf2_cu *cu,
1693                                 struct dwarf2_per_cu_data *per_cu);
1694
1695 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1696                                    struct die_info *comp_unit_die,
1697                                    enum language pretend_language);
1698
1699 static void free_heap_comp_unit (void *);
1700
1701 static void free_cached_comp_units (void *);
1702
1703 static void age_cached_comp_units (void);
1704
1705 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1706
1707 static struct type *set_die_type (struct die_info *, struct type *,
1708                                   struct dwarf2_cu *);
1709
1710 static void create_all_comp_units (struct objfile *);
1711
1712 static int create_all_type_units (struct objfile *);
1713
1714 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1715                                  enum language);
1716
1717 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1718                                     enum language);
1719
1720 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1721                                     enum language);
1722
1723 static void dwarf2_add_dependence (struct dwarf2_cu *,
1724                                    struct dwarf2_per_cu_data *);
1725
1726 static void dwarf2_mark (struct dwarf2_cu *);
1727
1728 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1729
1730 static struct type *get_die_type_at_offset (sect_offset,
1731                                             struct dwarf2_per_cu_data *);
1732
1733 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1734
1735 static void dwarf2_release_queue (void *dummy);
1736
1737 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1738                              enum language pretend_language);
1739
1740 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1741                                   struct dwarf2_per_cu_data *per_cu,
1742                                   enum language pretend_language);
1743
1744 static void process_queue (void);
1745
1746 static void find_file_and_directory (struct die_info *die,
1747                                      struct dwarf2_cu *cu,
1748                                      const char **name, const char **comp_dir);
1749
1750 static char *file_full_name (int file, struct line_header *lh,
1751                              const char *comp_dir);
1752
1753 static const gdb_byte *read_and_check_comp_unit_head
1754   (struct comp_unit_head *header,
1755    struct dwarf2_section_info *section,
1756    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1757    int is_debug_types_section);
1758
1759 static void init_cutu_and_read_dies
1760   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1761    int use_existing_cu, int keep,
1762    die_reader_func_ftype *die_reader_func, void *data);
1763
1764 static void init_cutu_and_read_dies_simple
1765   (struct dwarf2_per_cu_data *this_cu,
1766    die_reader_func_ftype *die_reader_func, void *data);
1767
1768 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1769
1770 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1771
1772 static struct dwo_unit *lookup_dwo_in_dwp
1773   (struct dwp_file *dwp_file, const struct dwp_hash_table *htab,
1774    const char *comp_dir, ULONGEST signature, int is_debug_types);
1775
1776 static struct dwp_file *get_dwp_file (void);
1777
1778 static struct dwo_unit *lookup_dwo_comp_unit
1779   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1780
1781 static struct dwo_unit *lookup_dwo_type_unit
1782   (struct signatured_type *, const char *, const char *);
1783
1784 static void free_dwo_file_cleanup (void *);
1785
1786 static void process_cu_includes (void);
1787
1788 static void check_producer (struct dwarf2_cu *cu);
1789
1790 #if WORDS_BIGENDIAN
1791
1792 /* Convert VALUE between big- and little-endian.  */
1793 static offset_type
1794 byte_swap (offset_type value)
1795 {
1796   offset_type result;
1797
1798   result = (value & 0xff) << 24;
1799   result |= (value & 0xff00) << 8;
1800   result |= (value & 0xff0000) >> 8;
1801   result |= (value & 0xff000000) >> 24;
1802   return result;
1803 }
1804
1805 #define MAYBE_SWAP(V)  byte_swap (V)
1806
1807 #else
1808 #define MAYBE_SWAP(V) (V)
1809 #endif /* WORDS_BIGENDIAN */
1810
1811 /* The suffix for an index file.  */
1812 #define INDEX_SUFFIX ".gdb-index"
1813
1814 /* Try to locate the sections we need for DWARF 2 debugging
1815    information and return true if we have enough to do something.
1816    NAMES points to the dwarf2 section names, or is NULL if the standard
1817    ELF names are used.  */
1818
1819 int
1820 dwarf2_has_info (struct objfile *objfile,
1821                  const struct dwarf2_debug_sections *names)
1822 {
1823   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1824   if (!dwarf2_per_objfile)
1825     {
1826       /* Initialize per-objfile state.  */
1827       struct dwarf2_per_objfile *data
1828         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1829
1830       memset (data, 0, sizeof (*data));
1831       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1832       dwarf2_per_objfile = data;
1833
1834       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1835                              (void *) names);
1836       dwarf2_per_objfile->objfile = objfile;
1837     }
1838   return (dwarf2_per_objfile->info.asection != NULL
1839           && dwarf2_per_objfile->abbrev.asection != NULL);
1840 }
1841
1842 /* When loading sections, we look either for uncompressed section or for
1843    compressed section names.  */
1844
1845 static int
1846 section_is_p (const char *section_name,
1847               const struct dwarf2_section_names *names)
1848 {
1849   if (names->normal != NULL
1850       && strcmp (section_name, names->normal) == 0)
1851     return 1;
1852   if (names->compressed != NULL
1853       && strcmp (section_name, names->compressed) == 0)
1854     return 1;
1855   return 0;
1856 }
1857
1858 /* This function is mapped across the sections and remembers the
1859    offset and size of each of the debugging sections we are interested
1860    in.  */
1861
1862 static void
1863 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1864 {
1865   const struct dwarf2_debug_sections *names;
1866   flagword aflag = bfd_get_section_flags (abfd, sectp);
1867
1868   if (vnames == NULL)
1869     names = &dwarf2_elf_names;
1870   else
1871     names = (const struct dwarf2_debug_sections *) vnames;
1872
1873   if ((aflag & SEC_HAS_CONTENTS) == 0)
1874     {
1875     }
1876   else if (section_is_p (sectp->name, &names->info))
1877     {
1878       dwarf2_per_objfile->info.asection = sectp;
1879       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1880     }
1881   else if (section_is_p (sectp->name, &names->abbrev))
1882     {
1883       dwarf2_per_objfile->abbrev.asection = sectp;
1884       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1885     }
1886   else if (section_is_p (sectp->name, &names->line))
1887     {
1888       dwarf2_per_objfile->line.asection = sectp;
1889       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1890     }
1891   else if (section_is_p (sectp->name, &names->loc))
1892     {
1893       dwarf2_per_objfile->loc.asection = sectp;
1894       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1895     }
1896   else if (section_is_p (sectp->name, &names->macinfo))
1897     {
1898       dwarf2_per_objfile->macinfo.asection = sectp;
1899       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1900     }
1901   else if (section_is_p (sectp->name, &names->macro))
1902     {
1903       dwarf2_per_objfile->macro.asection = sectp;
1904       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1905     }
1906   else if (section_is_p (sectp->name, &names->str))
1907     {
1908       dwarf2_per_objfile->str.asection = sectp;
1909       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1910     }
1911   else if (section_is_p (sectp->name, &names->addr))
1912     {
1913       dwarf2_per_objfile->addr.asection = sectp;
1914       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1915     }
1916   else if (section_is_p (sectp->name, &names->frame))
1917     {
1918       dwarf2_per_objfile->frame.asection = sectp;
1919       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1920     }
1921   else if (section_is_p (sectp->name, &names->eh_frame))
1922     {
1923       dwarf2_per_objfile->eh_frame.asection = sectp;
1924       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1925     }
1926   else if (section_is_p (sectp->name, &names->ranges))
1927     {
1928       dwarf2_per_objfile->ranges.asection = sectp;
1929       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1930     }
1931   else if (section_is_p (sectp->name, &names->types))
1932     {
1933       struct dwarf2_section_info type_section;
1934
1935       memset (&type_section, 0, sizeof (type_section));
1936       type_section.asection = sectp;
1937       type_section.size = bfd_get_section_size (sectp);
1938
1939       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1940                      &type_section);
1941     }
1942   else if (section_is_p (sectp->name, &names->gdb_index))
1943     {
1944       dwarf2_per_objfile->gdb_index.asection = sectp;
1945       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1946     }
1947
1948   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1949       && bfd_section_vma (abfd, sectp) == 0)
1950     dwarf2_per_objfile->has_section_at_zero = 1;
1951 }
1952
1953 /* A helper function that decides whether a section is empty,
1954    or not present.  */
1955
1956 static int
1957 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1958 {
1959   return info->asection == NULL || info->size == 0;
1960 }
1961
1962 /* Read the contents of the section INFO.
1963    OBJFILE is the main object file, but not necessarily the file where
1964    the section comes from.  E.g., for DWO files INFO->asection->owner
1965    is the bfd of the DWO file.
1966    If the section is compressed, uncompress it before returning.  */
1967
1968 static void
1969 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1970 {
1971   asection *sectp = info->asection;
1972   bfd *abfd;
1973   gdb_byte *buf, *retbuf;
1974   unsigned char header[4];
1975
1976   if (info->readin)
1977     return;
1978   info->buffer = NULL;
1979   info->readin = 1;
1980
1981   if (dwarf2_section_empty_p (info))
1982     return;
1983
1984   abfd = sectp->owner;
1985
1986   /* If the section has relocations, we must read it ourselves.
1987      Otherwise we attach it to the BFD.  */
1988   if ((sectp->flags & SEC_RELOC) == 0)
1989     {
1990       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1991       return;
1992     }
1993
1994   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1995   info->buffer = buf;
1996
1997   /* When debugging .o files, we may need to apply relocations; see
1998      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1999      We never compress sections in .o files, so we only need to
2000      try this when the section is not compressed.  */
2001   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2002   if (retbuf != NULL)
2003     {
2004       info->buffer = retbuf;
2005       return;
2006     }
2007
2008   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2009       || bfd_bread (buf, info->size, abfd) != info->size)
2010     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
2011            bfd_get_filename (abfd));
2012 }
2013
2014 /* A helper function that returns the size of a section in a safe way.
2015    If you are positive that the section has been read before using the
2016    size, then it is safe to refer to the dwarf2_section_info object's
2017    "size" field directly.  In other cases, you must call this
2018    function, because for compressed sections the size field is not set
2019    correctly until the section has been read.  */
2020
2021 static bfd_size_type
2022 dwarf2_section_size (struct objfile *objfile,
2023                      struct dwarf2_section_info *info)
2024 {
2025   if (!info->readin)
2026     dwarf2_read_section (objfile, info);
2027   return info->size;
2028 }
2029
2030 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2031    SECTION_NAME.  */
2032
2033 void
2034 dwarf2_get_section_info (struct objfile *objfile,
2035                          enum dwarf2_section_enum sect,
2036                          asection **sectp, const gdb_byte **bufp,
2037                          bfd_size_type *sizep)
2038 {
2039   struct dwarf2_per_objfile *data
2040     = objfile_data (objfile, dwarf2_objfile_data_key);
2041   struct dwarf2_section_info *info;
2042
2043   /* We may see an objfile without any DWARF, in which case we just
2044      return nothing.  */
2045   if (data == NULL)
2046     {
2047       *sectp = NULL;
2048       *bufp = NULL;
2049       *sizep = 0;
2050       return;
2051     }
2052   switch (sect)
2053     {
2054     case DWARF2_DEBUG_FRAME:
2055       info = &data->frame;
2056       break;
2057     case DWARF2_EH_FRAME:
2058       info = &data->eh_frame;
2059       break;
2060     default:
2061       gdb_assert_not_reached ("unexpected section");
2062     }
2063
2064   dwarf2_read_section (objfile, info);
2065
2066   *sectp = info->asection;
2067   *bufp = info->buffer;
2068   *sizep = info->size;
2069 }
2070
2071 /* A helper function to find the sections for a .dwz file.  */
2072
2073 static void
2074 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2075 {
2076   struct dwz_file *dwz_file = arg;
2077
2078   /* Note that we only support the standard ELF names, because .dwz
2079      is ELF-only (at the time of writing).  */
2080   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2081     {
2082       dwz_file->abbrev.asection = sectp;
2083       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2084     }
2085   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2086     {
2087       dwz_file->info.asection = sectp;
2088       dwz_file->info.size = bfd_get_section_size (sectp);
2089     }
2090   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2091     {
2092       dwz_file->str.asection = sectp;
2093       dwz_file->str.size = bfd_get_section_size (sectp);
2094     }
2095   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2096     {
2097       dwz_file->line.asection = sectp;
2098       dwz_file->line.size = bfd_get_section_size (sectp);
2099     }
2100   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2101     {
2102       dwz_file->macro.asection = sectp;
2103       dwz_file->macro.size = bfd_get_section_size (sectp);
2104     }
2105   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2106     {
2107       dwz_file->gdb_index.asection = sectp;
2108       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2109     }
2110 }
2111
2112 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2113    there is no .gnu_debugaltlink section in the file.  Error if there
2114    is such a section but the file cannot be found.  */
2115
2116 static struct dwz_file *
2117 dwarf2_get_dwz_file (void)
2118 {
2119   bfd *dwz_bfd;
2120   char *data;
2121   struct cleanup *cleanup;
2122   const char *filename;
2123   struct dwz_file *result;
2124   unsigned long buildid;
2125
2126   if (dwarf2_per_objfile->dwz_file != NULL)
2127     return dwarf2_per_objfile->dwz_file;
2128
2129   bfd_set_error (bfd_error_no_error);
2130   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2131                                       &buildid);
2132   if (data == NULL)
2133     {
2134       if (bfd_get_error () == bfd_error_no_error)
2135         return NULL;
2136       error (_("could not read '.gnu_debugaltlink' section: %s"),
2137              bfd_errmsg (bfd_get_error ()));
2138     }
2139   cleanup = make_cleanup (xfree, data);
2140
2141   filename = (const char *) data;
2142   if (!IS_ABSOLUTE_PATH (filename))
2143     {
2144       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2145       char *rel;
2146
2147       make_cleanup (xfree, abs);
2148       abs = ldirname (abs);
2149       make_cleanup (xfree, abs);
2150
2151       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2152       make_cleanup (xfree, rel);
2153       filename = rel;
2154     }
2155
2156   /* The format is just a NUL-terminated file name, followed by the
2157      build-id.  For now, though, we ignore the build-id.  */
2158   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2159   if (dwz_bfd == NULL)
2160     error (_("could not read '%s': %s"), filename,
2161            bfd_errmsg (bfd_get_error ()));
2162
2163   if (!bfd_check_format (dwz_bfd, bfd_object))
2164     {
2165       gdb_bfd_unref (dwz_bfd);
2166       error (_("file '%s' was not usable: %s"), filename,
2167              bfd_errmsg (bfd_get_error ()));
2168     }
2169
2170   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2171                            struct dwz_file);
2172   result->dwz_bfd = dwz_bfd;
2173
2174   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2175
2176   do_cleanups (cleanup);
2177
2178   dwarf2_per_objfile->dwz_file = result;
2179   return result;
2180 }
2181 \f
2182 /* DWARF quick_symbols_functions support.  */
2183
2184 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2185    unique line tables, so we maintain a separate table of all .debug_line
2186    derived entries to support the sharing.
2187    All the quick functions need is the list of file names.  We discard the
2188    line_header when we're done and don't need to record it here.  */
2189 struct quick_file_names
2190 {
2191   /* The data used to construct the hash key.  */
2192   struct stmt_list_hash hash;
2193
2194   /* The number of entries in file_names, real_names.  */
2195   unsigned int num_file_names;
2196
2197   /* The file names from the line table, after being run through
2198      file_full_name.  */
2199   const char **file_names;
2200
2201   /* The file names from the line table after being run through
2202      gdb_realpath.  These are computed lazily.  */
2203   const char **real_names;
2204 };
2205
2206 /* When using the index (and thus not using psymtabs), each CU has an
2207    object of this type.  This is used to hold information needed by
2208    the various "quick" methods.  */
2209 struct dwarf2_per_cu_quick_data
2210 {
2211   /* The file table.  This can be NULL if there was no file table
2212      or it's currently not read in.
2213      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2214   struct quick_file_names *file_names;
2215
2216   /* The corresponding symbol table.  This is NULL if symbols for this
2217      CU have not yet been read.  */
2218   struct symtab *symtab;
2219
2220   /* A temporary mark bit used when iterating over all CUs in
2221      expand_symtabs_matching.  */
2222   unsigned int mark : 1;
2223
2224   /* True if we've tried to read the file table and found there isn't one.
2225      There will be no point in trying to read it again next time.  */
2226   unsigned int no_file_data : 1;
2227 };
2228
2229 /* Utility hash function for a stmt_list_hash.  */
2230
2231 static hashval_t
2232 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2233 {
2234   hashval_t v = 0;
2235
2236   if (stmt_list_hash->dwo_unit != NULL)
2237     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2238   v += stmt_list_hash->line_offset.sect_off;
2239   return v;
2240 }
2241
2242 /* Utility equality function for a stmt_list_hash.  */
2243
2244 static int
2245 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2246                     const struct stmt_list_hash *rhs)
2247 {
2248   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2249     return 0;
2250   if (lhs->dwo_unit != NULL
2251       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2252     return 0;
2253
2254   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2255 }
2256
2257 /* Hash function for a quick_file_names.  */
2258
2259 static hashval_t
2260 hash_file_name_entry (const void *e)
2261 {
2262   const struct quick_file_names *file_data = e;
2263
2264   return hash_stmt_list_entry (&file_data->hash);
2265 }
2266
2267 /* Equality function for a quick_file_names.  */
2268
2269 static int
2270 eq_file_name_entry (const void *a, const void *b)
2271 {
2272   const struct quick_file_names *ea = a;
2273   const struct quick_file_names *eb = b;
2274
2275   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2276 }
2277
2278 /* Delete function for a quick_file_names.  */
2279
2280 static void
2281 delete_file_name_entry (void *e)
2282 {
2283   struct quick_file_names *file_data = e;
2284   int i;
2285
2286   for (i = 0; i < file_data->num_file_names; ++i)
2287     {
2288       xfree ((void*) file_data->file_names[i]);
2289       if (file_data->real_names)
2290         xfree ((void*) file_data->real_names[i]);
2291     }
2292
2293   /* The space for the struct itself lives on objfile_obstack,
2294      so we don't free it here.  */
2295 }
2296
2297 /* Create a quick_file_names hash table.  */
2298
2299 static htab_t
2300 create_quick_file_names_table (unsigned int nr_initial_entries)
2301 {
2302   return htab_create_alloc (nr_initial_entries,
2303                             hash_file_name_entry, eq_file_name_entry,
2304                             delete_file_name_entry, xcalloc, xfree);
2305 }
2306
2307 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2308    have to be created afterwards.  You should call age_cached_comp_units after
2309    processing PER_CU->CU.  dw2_setup must have been already called.  */
2310
2311 static void
2312 load_cu (struct dwarf2_per_cu_data *per_cu)
2313 {
2314   if (per_cu->is_debug_types)
2315     load_full_type_unit (per_cu);
2316   else
2317     load_full_comp_unit (per_cu, language_minimal);
2318
2319   gdb_assert (per_cu->cu != NULL);
2320
2321   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2322 }
2323
2324 /* Read in the symbols for PER_CU.  */
2325
2326 static void
2327 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2328 {
2329   struct cleanup *back_to;
2330
2331   /* Skip type_unit_groups, reading the type units they contain
2332      is handled elsewhere.  */
2333   if (IS_TYPE_UNIT_GROUP (per_cu))
2334     return;
2335
2336   back_to = make_cleanup (dwarf2_release_queue, NULL);
2337
2338   if (dwarf2_per_objfile->using_index
2339       ? per_cu->v.quick->symtab == NULL
2340       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2341     {
2342       queue_comp_unit (per_cu, language_minimal);
2343       load_cu (per_cu);
2344     }
2345
2346   process_queue ();
2347
2348   /* Age the cache, releasing compilation units that have not
2349      been used recently.  */
2350   age_cached_comp_units ();
2351
2352   do_cleanups (back_to);
2353 }
2354
2355 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2356    the objfile from which this CU came.  Returns the resulting symbol
2357    table.  */
2358
2359 static struct symtab *
2360 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2361 {
2362   gdb_assert (dwarf2_per_objfile->using_index);
2363   if (!per_cu->v.quick->symtab)
2364     {
2365       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2366       increment_reading_symtab ();
2367       dw2_do_instantiate_symtab (per_cu);
2368       process_cu_includes ();
2369       do_cleanups (back_to);
2370     }
2371   return per_cu->v.quick->symtab;
2372 }
2373
2374 /* Return the CU given its index.
2375
2376    This is intended for loops like:
2377
2378    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2379                     + dwarf2_per_objfile->n_type_units); ++i)
2380      {
2381        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2382
2383        ...;
2384      }
2385 */
2386
2387 static struct dwarf2_per_cu_data *
2388 dw2_get_cu (int index)
2389 {
2390   if (index >= dwarf2_per_objfile->n_comp_units)
2391     {
2392       index -= dwarf2_per_objfile->n_comp_units;
2393       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2394       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2395     }
2396
2397   return dwarf2_per_objfile->all_comp_units[index];
2398 }
2399
2400 /* Return the primary CU given its index.
2401    The difference between this function and dw2_get_cu is in the handling
2402    of type units (TUs).  Here we return the type_unit_group object.
2403
2404    This is intended for loops like:
2405
2406    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2407                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2408      {
2409        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2410
2411        ...;
2412      }
2413 */
2414
2415 static struct dwarf2_per_cu_data *
2416 dw2_get_primary_cu (int index)
2417 {
2418   if (index >= dwarf2_per_objfile->n_comp_units)
2419     {
2420       index -= dwarf2_per_objfile->n_comp_units;
2421       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2422       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2423     }
2424
2425   return dwarf2_per_objfile->all_comp_units[index];
2426 }
2427
2428 /* A helper for create_cus_from_index that handles a given list of
2429    CUs.  */
2430
2431 static void
2432 create_cus_from_index_list (struct objfile *objfile,
2433                             const gdb_byte *cu_list, offset_type n_elements,
2434                             struct dwarf2_section_info *section,
2435                             int is_dwz,
2436                             int base_offset)
2437 {
2438   offset_type i;
2439
2440   for (i = 0; i < n_elements; i += 2)
2441     {
2442       struct dwarf2_per_cu_data *the_cu;
2443       ULONGEST offset, length;
2444
2445       gdb_static_assert (sizeof (ULONGEST) >= 8);
2446       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2447       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2448       cu_list += 2 * 8;
2449
2450       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2451                                struct dwarf2_per_cu_data);
2452       the_cu->offset.sect_off = offset;
2453       the_cu->length = length;
2454       the_cu->objfile = objfile;
2455       the_cu->section = section;
2456       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2457                                         struct dwarf2_per_cu_quick_data);
2458       the_cu->is_dwz = is_dwz;
2459       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2460     }
2461 }
2462
2463 /* Read the CU list from the mapped index, and use it to create all
2464    the CU objects for this objfile.  */
2465
2466 static void
2467 create_cus_from_index (struct objfile *objfile,
2468                        const gdb_byte *cu_list, offset_type cu_list_elements,
2469                        const gdb_byte *dwz_list, offset_type dwz_elements)
2470 {
2471   struct dwz_file *dwz;
2472
2473   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2474   dwarf2_per_objfile->all_comp_units
2475     = obstack_alloc (&objfile->objfile_obstack,
2476                      dwarf2_per_objfile->n_comp_units
2477                      * sizeof (struct dwarf2_per_cu_data *));
2478
2479   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2480                               &dwarf2_per_objfile->info, 0, 0);
2481
2482   if (dwz_elements == 0)
2483     return;
2484
2485   dwz = dwarf2_get_dwz_file ();
2486   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2487                               cu_list_elements / 2);
2488 }
2489
2490 /* Create the signatured type hash table from the index.  */
2491
2492 static void
2493 create_signatured_type_table_from_index (struct objfile *objfile,
2494                                          struct dwarf2_section_info *section,
2495                                          const gdb_byte *bytes,
2496                                          offset_type elements)
2497 {
2498   offset_type i;
2499   htab_t sig_types_hash;
2500
2501   dwarf2_per_objfile->n_type_units = elements / 3;
2502   dwarf2_per_objfile->all_type_units
2503     = xmalloc (dwarf2_per_objfile->n_type_units
2504                * sizeof (struct signatured_type *));
2505
2506   sig_types_hash = allocate_signatured_type_table (objfile);
2507
2508   for (i = 0; i < elements; i += 3)
2509     {
2510       struct signatured_type *sig_type;
2511       ULONGEST offset, type_offset_in_tu, signature;
2512       void **slot;
2513
2514       gdb_static_assert (sizeof (ULONGEST) >= 8);
2515       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2516       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2517                                                     BFD_ENDIAN_LITTLE);
2518       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2519       bytes += 3 * 8;
2520
2521       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2522                                  struct signatured_type);
2523       sig_type->signature = signature;
2524       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2525       sig_type->per_cu.is_debug_types = 1;
2526       sig_type->per_cu.section = section;
2527       sig_type->per_cu.offset.sect_off = offset;
2528       sig_type->per_cu.objfile = objfile;
2529       sig_type->per_cu.v.quick
2530         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2531                           struct dwarf2_per_cu_quick_data);
2532
2533       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2534       *slot = sig_type;
2535
2536       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2537     }
2538
2539   dwarf2_per_objfile->signatured_types = sig_types_hash;
2540 }
2541
2542 /* Read the address map data from the mapped index, and use it to
2543    populate the objfile's psymtabs_addrmap.  */
2544
2545 static void
2546 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2547 {
2548   const gdb_byte *iter, *end;
2549   struct obstack temp_obstack;
2550   struct addrmap *mutable_map;
2551   struct cleanup *cleanup;
2552   CORE_ADDR baseaddr;
2553
2554   obstack_init (&temp_obstack);
2555   cleanup = make_cleanup_obstack_free (&temp_obstack);
2556   mutable_map = addrmap_create_mutable (&temp_obstack);
2557
2558   iter = index->address_table;
2559   end = iter + index->address_table_size;
2560
2561   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2562
2563   while (iter < end)
2564     {
2565       ULONGEST hi, lo, cu_index;
2566       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2567       iter += 8;
2568       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2569       iter += 8;
2570       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2571       iter += 4;
2572
2573       if (cu_index < dwarf2_per_objfile->n_comp_units)
2574         {
2575           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2576                              dw2_get_cu (cu_index));
2577         }
2578       else
2579         {
2580           complaint (&symfile_complaints,
2581                      _(".gdb_index address table has invalid CU number %u"),
2582                      (unsigned) cu_index);
2583         }
2584     }
2585
2586   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2587                                                     &objfile->objfile_obstack);
2588   do_cleanups (cleanup);
2589 }
2590
2591 /* The hash function for strings in the mapped index.  This is the same as
2592    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2593    implementation.  This is necessary because the hash function is tied to the
2594    format of the mapped index file.  The hash values do not have to match with
2595    SYMBOL_HASH_NEXT.
2596    
2597    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2598
2599 static hashval_t
2600 mapped_index_string_hash (int index_version, const void *p)
2601 {
2602   const unsigned char *str = (const unsigned char *) p;
2603   hashval_t r = 0;
2604   unsigned char c;
2605
2606   while ((c = *str++) != 0)
2607     {
2608       if (index_version >= 5)
2609         c = tolower (c);
2610       r = r * 67 + c - 113;
2611     }
2612
2613   return r;
2614 }
2615
2616 /* Find a slot in the mapped index INDEX for the object named NAME.
2617    If NAME is found, set *VEC_OUT to point to the CU vector in the
2618    constant pool and return 1.  If NAME cannot be found, return 0.  */
2619
2620 static int
2621 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2622                           offset_type **vec_out)
2623 {
2624   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2625   offset_type hash;
2626   offset_type slot, step;
2627   int (*cmp) (const char *, const char *);
2628
2629   if (current_language->la_language == language_cplus
2630       || current_language->la_language == language_java
2631       || current_language->la_language == language_fortran)
2632     {
2633       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2634          not contain any.  */
2635       const char *paren = strchr (name, '(');
2636
2637       if (paren)
2638         {
2639           char *dup;
2640
2641           dup = xmalloc (paren - name + 1);
2642           memcpy (dup, name, paren - name);
2643           dup[paren - name] = 0;
2644
2645           make_cleanup (xfree, dup);
2646           name = dup;
2647         }
2648     }
2649
2650   /* Index version 4 did not support case insensitive searches.  But the
2651      indices for case insensitive languages are built in lowercase, therefore
2652      simulate our NAME being searched is also lowercased.  */
2653   hash = mapped_index_string_hash ((index->version == 4
2654                                     && case_sensitivity == case_sensitive_off
2655                                     ? 5 : index->version),
2656                                    name);
2657
2658   slot = hash & (index->symbol_table_slots - 1);
2659   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2660   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2661
2662   for (;;)
2663     {
2664       /* Convert a slot number to an offset into the table.  */
2665       offset_type i = 2 * slot;
2666       const char *str;
2667       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2668         {
2669           do_cleanups (back_to);
2670           return 0;
2671         }
2672
2673       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2674       if (!cmp (name, str))
2675         {
2676           *vec_out = (offset_type *) (index->constant_pool
2677                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2678           do_cleanups (back_to);
2679           return 1;
2680         }
2681
2682       slot = (slot + step) & (index->symbol_table_slots - 1);
2683     }
2684 }
2685
2686 /* A helper function that reads the .gdb_index from SECTION and fills
2687    in MAP.  FILENAME is the name of the file containing the section;
2688    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2689    ok to use deprecated sections.
2690
2691    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2692    out parameters that are filled in with information about the CU and
2693    TU lists in the section.
2694
2695    Returns 1 if all went well, 0 otherwise.  */
2696
2697 static int
2698 read_index_from_section (struct objfile *objfile,
2699                          const char *filename,
2700                          int deprecated_ok,
2701                          struct dwarf2_section_info *section,
2702                          struct mapped_index *map,
2703                          const gdb_byte **cu_list,
2704                          offset_type *cu_list_elements,
2705                          const gdb_byte **types_list,
2706                          offset_type *types_list_elements)
2707 {
2708   const gdb_byte *addr;
2709   offset_type version;
2710   offset_type *metadata;
2711   int i;
2712
2713   if (dwarf2_section_empty_p (section))
2714     return 0;
2715
2716   /* Older elfutils strip versions could keep the section in the main
2717      executable while splitting it for the separate debug info file.  */
2718   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2719     return 0;
2720
2721   dwarf2_read_section (objfile, section);
2722
2723   addr = section->buffer;
2724   /* Version check.  */
2725   version = MAYBE_SWAP (*(offset_type *) addr);
2726   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2727      causes the index to behave very poorly for certain requests.  Version 3
2728      contained incomplete addrmap.  So, it seems better to just ignore such
2729      indices.  */
2730   if (version < 4)
2731     {
2732       static int warning_printed = 0;
2733       if (!warning_printed)
2734         {
2735           warning (_("Skipping obsolete .gdb_index section in %s."),
2736                    filename);
2737           warning_printed = 1;
2738         }
2739       return 0;
2740     }
2741   /* Index version 4 uses a different hash function than index version
2742      5 and later.
2743
2744      Versions earlier than 6 did not emit psymbols for inlined
2745      functions.  Using these files will cause GDB not to be able to
2746      set breakpoints on inlined functions by name, so we ignore these
2747      indices unless the user has done
2748      "set use-deprecated-index-sections on".  */
2749   if (version < 6 && !deprecated_ok)
2750     {
2751       static int warning_printed = 0;
2752       if (!warning_printed)
2753         {
2754           warning (_("\
2755 Skipping deprecated .gdb_index section in %s.\n\
2756 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2757 to use the section anyway."),
2758                    filename);
2759           warning_printed = 1;
2760         }
2761       return 0;
2762     }
2763   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2764      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2765      we can't distinguish gdb-generated indices from gold-generated ones, so
2766      nothing to do here.  */
2767
2768   /* Indexes with higher version than the one supported by GDB may be no
2769      longer backward compatible.  */
2770   if (version > 8)
2771     return 0;
2772
2773   map->version = version;
2774   map->total_size = section->size;
2775
2776   metadata = (offset_type *) (addr + sizeof (offset_type));
2777
2778   i = 0;
2779   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2780   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2781                        / 8);
2782   ++i;
2783
2784   *types_list = addr + MAYBE_SWAP (metadata[i]);
2785   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2786                            - MAYBE_SWAP (metadata[i]))
2787                           / 8);
2788   ++i;
2789
2790   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2791   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2792                              - MAYBE_SWAP (metadata[i]));
2793   ++i;
2794
2795   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2796   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2797                               - MAYBE_SWAP (metadata[i]))
2798                              / (2 * sizeof (offset_type)));
2799   ++i;
2800
2801   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2802
2803   return 1;
2804 }
2805
2806
2807 /* Read the index file.  If everything went ok, initialize the "quick"
2808    elements of all the CUs and return 1.  Otherwise, return 0.  */
2809
2810 static int
2811 dwarf2_read_index (struct objfile *objfile)
2812 {
2813   struct mapped_index local_map, *map;
2814   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2815   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2816   struct dwz_file *dwz;
2817
2818   if (!read_index_from_section (objfile, objfile->name,
2819                                 use_deprecated_index_sections,
2820                                 &dwarf2_per_objfile->gdb_index, &local_map,
2821                                 &cu_list, &cu_list_elements,
2822                                 &types_list, &types_list_elements))
2823     return 0;
2824
2825   /* Don't use the index if it's empty.  */
2826   if (local_map.symbol_table_slots == 0)
2827     return 0;
2828
2829   /* If there is a .dwz file, read it so we can get its CU list as
2830      well.  */
2831   dwz = dwarf2_get_dwz_file ();
2832   if (dwz != NULL)
2833     {
2834       struct mapped_index dwz_map;
2835       const gdb_byte *dwz_types_ignore;
2836       offset_type dwz_types_elements_ignore;
2837
2838       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2839                                     1,
2840                                     &dwz->gdb_index, &dwz_map,
2841                                     &dwz_list, &dwz_list_elements,
2842                                     &dwz_types_ignore,
2843                                     &dwz_types_elements_ignore))
2844         {
2845           warning (_("could not read '.gdb_index' section from %s; skipping"),
2846                    bfd_get_filename (dwz->dwz_bfd));
2847           return 0;
2848         }
2849     }
2850
2851   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2852                          dwz_list_elements);
2853
2854   if (types_list_elements)
2855     {
2856       struct dwarf2_section_info *section;
2857
2858       /* We can only handle a single .debug_types when we have an
2859          index.  */
2860       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2861         return 0;
2862
2863       section = VEC_index (dwarf2_section_info_def,
2864                            dwarf2_per_objfile->types, 0);
2865
2866       create_signatured_type_table_from_index (objfile, section, types_list,
2867                                                types_list_elements);
2868     }
2869
2870   create_addrmap_from_index (objfile, &local_map);
2871
2872   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2873   *map = local_map;
2874
2875   dwarf2_per_objfile->index_table = map;
2876   dwarf2_per_objfile->using_index = 1;
2877   dwarf2_per_objfile->quick_file_names_table =
2878     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2879
2880   return 1;
2881 }
2882
2883 /* A helper for the "quick" functions which sets the global
2884    dwarf2_per_objfile according to OBJFILE.  */
2885
2886 static void
2887 dw2_setup (struct objfile *objfile)
2888 {
2889   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2890   gdb_assert (dwarf2_per_objfile);
2891 }
2892
2893 /* die_reader_func for dw2_get_file_names.  */
2894
2895 static void
2896 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2897                            const gdb_byte *info_ptr,
2898                            struct die_info *comp_unit_die,
2899                            int has_children,
2900                            void *data)
2901 {
2902   struct dwarf2_cu *cu = reader->cu;
2903   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2904   struct objfile *objfile = dwarf2_per_objfile->objfile;
2905   struct dwarf2_per_cu_data *lh_cu;
2906   struct line_header *lh;
2907   struct attribute *attr;
2908   int i;
2909   const char *name, *comp_dir;
2910   void **slot;
2911   struct quick_file_names *qfn;
2912   unsigned int line_offset;
2913
2914   gdb_assert (! this_cu->is_debug_types);
2915
2916   /* Our callers never want to match partial units -- instead they
2917      will match the enclosing full CU.  */
2918   if (comp_unit_die->tag == DW_TAG_partial_unit)
2919     {
2920       this_cu->v.quick->no_file_data = 1;
2921       return;
2922     }
2923
2924   lh_cu = this_cu;
2925   lh = NULL;
2926   slot = NULL;
2927   line_offset = 0;
2928
2929   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2930   if (attr)
2931     {
2932       struct quick_file_names find_entry;
2933
2934       line_offset = DW_UNSND (attr);
2935
2936       /* We may have already read in this line header (TU line header sharing).
2937          If we have we're done.  */
2938       find_entry.hash.dwo_unit = cu->dwo_unit;
2939       find_entry.hash.line_offset.sect_off = line_offset;
2940       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2941                              &find_entry, INSERT);
2942       if (*slot != NULL)
2943         {
2944           lh_cu->v.quick->file_names = *slot;
2945           return;
2946         }
2947
2948       lh = dwarf_decode_line_header (line_offset, cu);
2949     }
2950   if (lh == NULL)
2951     {
2952       lh_cu->v.quick->no_file_data = 1;
2953       return;
2954     }
2955
2956   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2957   qfn->hash.dwo_unit = cu->dwo_unit;
2958   qfn->hash.line_offset.sect_off = line_offset;
2959   gdb_assert (slot != NULL);
2960   *slot = qfn;
2961
2962   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2963
2964   qfn->num_file_names = lh->num_file_names;
2965   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2966                                    lh->num_file_names * sizeof (char *));
2967   for (i = 0; i < lh->num_file_names; ++i)
2968     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2969   qfn->real_names = NULL;
2970
2971   free_line_header (lh);
2972
2973   lh_cu->v.quick->file_names = qfn;
2974 }
2975
2976 /* A helper for the "quick" functions which attempts to read the line
2977    table for THIS_CU.  */
2978
2979 static struct quick_file_names *
2980 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2981 {
2982   /* This should never be called for TUs.  */
2983   gdb_assert (! this_cu->is_debug_types);
2984   /* Nor type unit groups.  */
2985   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
2986
2987   if (this_cu->v.quick->file_names != NULL)
2988     return this_cu->v.quick->file_names;
2989   /* If we know there is no line data, no point in looking again.  */
2990   if (this_cu->v.quick->no_file_data)
2991     return NULL;
2992
2993   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2994
2995   if (this_cu->v.quick->no_file_data)
2996     return NULL;
2997   return this_cu->v.quick->file_names;
2998 }
2999
3000 /* A helper for the "quick" functions which computes and caches the
3001    real path for a given file name from the line table.  */
3002
3003 static const char *
3004 dw2_get_real_path (struct objfile *objfile,
3005                    struct quick_file_names *qfn, int index)
3006 {
3007   if (qfn->real_names == NULL)
3008     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3009                                       qfn->num_file_names, sizeof (char *));
3010
3011   if (qfn->real_names[index] == NULL)
3012     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3013
3014   return qfn->real_names[index];
3015 }
3016
3017 static struct symtab *
3018 dw2_find_last_source_symtab (struct objfile *objfile)
3019 {
3020   int index;
3021
3022   dw2_setup (objfile);
3023   index = dwarf2_per_objfile->n_comp_units - 1;
3024   return dw2_instantiate_symtab (dw2_get_cu (index));
3025 }
3026
3027 /* Traversal function for dw2_forget_cached_source_info.  */
3028
3029 static int
3030 dw2_free_cached_file_names (void **slot, void *info)
3031 {
3032   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3033
3034   if (file_data->real_names)
3035     {
3036       int i;
3037
3038       for (i = 0; i < file_data->num_file_names; ++i)
3039         {
3040           xfree ((void*) file_data->real_names[i]);
3041           file_data->real_names[i] = NULL;
3042         }
3043     }
3044
3045   return 1;
3046 }
3047
3048 static void
3049 dw2_forget_cached_source_info (struct objfile *objfile)
3050 {
3051   dw2_setup (objfile);
3052
3053   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3054                           dw2_free_cached_file_names, NULL);
3055 }
3056
3057 /* Helper function for dw2_map_symtabs_matching_filename that expands
3058    the symtabs and calls the iterator.  */
3059
3060 static int
3061 dw2_map_expand_apply (struct objfile *objfile,
3062                       struct dwarf2_per_cu_data *per_cu,
3063                       const char *name, const char *real_path,
3064                       int (*callback) (struct symtab *, void *),
3065                       void *data)
3066 {
3067   struct symtab *last_made = objfile->symtabs;
3068
3069   /* Don't visit already-expanded CUs.  */
3070   if (per_cu->v.quick->symtab)
3071     return 0;
3072
3073   /* This may expand more than one symtab, and we want to iterate over
3074      all of them.  */
3075   dw2_instantiate_symtab (per_cu);
3076
3077   return iterate_over_some_symtabs (name, real_path, callback, data,
3078                                     objfile->symtabs, last_made);
3079 }
3080
3081 /* Implementation of the map_symtabs_matching_filename method.  */
3082
3083 static int
3084 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3085                                    const char *real_path,
3086                                    int (*callback) (struct symtab *, void *),
3087                                    void *data)
3088 {
3089   int i;
3090   const char *name_basename = lbasename (name);
3091
3092   dw2_setup (objfile);
3093
3094   /* The rule is CUs specify all the files, including those used by
3095      any TU, so there's no need to scan TUs here.  */
3096
3097   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3098     {
3099       int j;
3100       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3101       struct quick_file_names *file_data;
3102
3103       /* We only need to look at symtabs not already expanded.  */
3104       if (per_cu->v.quick->symtab)
3105         continue;
3106
3107       file_data = dw2_get_file_names (per_cu);
3108       if (file_data == NULL)
3109         continue;
3110
3111       for (j = 0; j < file_data->num_file_names; ++j)
3112         {
3113           const char *this_name = file_data->file_names[j];
3114           const char *this_real_name;
3115
3116           if (compare_filenames_for_search (this_name, name))
3117             {
3118               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3119                                         callback, data))
3120                 return 1;
3121               continue;
3122             }
3123
3124           /* Before we invoke realpath, which can get expensive when many
3125              files are involved, do a quick comparison of the basenames.  */
3126           if (! basenames_may_differ
3127               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3128             continue;
3129
3130           this_real_name = dw2_get_real_path (objfile, file_data, j);
3131           if (compare_filenames_for_search (this_real_name, name))
3132             {
3133               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3134                                         callback, data))
3135                 return 1;
3136               continue;
3137             }
3138
3139           if (real_path != NULL)
3140             {
3141               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3142               gdb_assert (IS_ABSOLUTE_PATH (name));
3143               if (this_real_name != NULL
3144                   && FILENAME_CMP (real_path, this_real_name) == 0)
3145                 {
3146                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3147                                             callback, data))
3148                     return 1;
3149                   continue;
3150                 }
3151             }
3152         }
3153     }
3154
3155   return 0;
3156 }
3157
3158 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3159
3160 struct dw2_symtab_iterator
3161 {
3162   /* The internalized form of .gdb_index.  */
3163   struct mapped_index *index;
3164   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3165   int want_specific_block;
3166   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3167      Unused if !WANT_SPECIFIC_BLOCK.  */
3168   int block_index;
3169   /* The kind of symbol we're looking for.  */
3170   domain_enum domain;
3171   /* The list of CUs from the index entry of the symbol,
3172      or NULL if not found.  */
3173   offset_type *vec;
3174   /* The next element in VEC to look at.  */
3175   int next;
3176   /* The number of elements in VEC, or zero if there is no match.  */
3177   int length;
3178 };
3179
3180 /* Initialize the index symtab iterator ITER.
3181    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3182    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3183
3184 static void
3185 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3186                       struct mapped_index *index,
3187                       int want_specific_block,
3188                       int block_index,
3189                       domain_enum domain,
3190                       const char *name)
3191 {
3192   iter->index = index;
3193   iter->want_specific_block = want_specific_block;
3194   iter->block_index = block_index;
3195   iter->domain = domain;
3196   iter->next = 0;
3197
3198   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3199     iter->length = MAYBE_SWAP (*iter->vec);
3200   else
3201     {
3202       iter->vec = NULL;
3203       iter->length = 0;
3204     }
3205 }
3206
3207 /* Return the next matching CU or NULL if there are no more.  */
3208
3209 static struct dwarf2_per_cu_data *
3210 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3211 {
3212   for ( ; iter->next < iter->length; ++iter->next)
3213     {
3214       offset_type cu_index_and_attrs =
3215         MAYBE_SWAP (iter->vec[iter->next + 1]);
3216       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3217       struct dwarf2_per_cu_data *per_cu;
3218       int want_static = iter->block_index != GLOBAL_BLOCK;
3219       /* This value is only valid for index versions >= 7.  */
3220       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3221       gdb_index_symbol_kind symbol_kind =
3222         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3223       /* Only check the symbol attributes if they're present.
3224          Indices prior to version 7 don't record them,
3225          and indices >= 7 may elide them for certain symbols
3226          (gold does this).  */
3227       int attrs_valid =
3228         (iter->index->version >= 7
3229          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3230
3231       /* Don't crash on bad data.  */
3232       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3233                        + dwarf2_per_objfile->n_type_units))
3234         {
3235           complaint (&symfile_complaints,
3236                      _(".gdb_index entry has bad CU index"
3237                        " [in module %s]"), dwarf2_per_objfile->objfile->name);
3238           continue;
3239         }
3240
3241       per_cu = dw2_get_cu (cu_index);
3242
3243       /* Skip if already read in.  */
3244       if (per_cu->v.quick->symtab)
3245         continue;
3246
3247       if (attrs_valid
3248           && iter->want_specific_block
3249           && want_static != is_static)
3250         continue;
3251
3252       /* Only check the symbol's kind if it has one.  */
3253       if (attrs_valid)
3254         {
3255           switch (iter->domain)
3256             {
3257             case VAR_DOMAIN:
3258               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3259                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3260                   /* Some types are also in VAR_DOMAIN.  */
3261                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3262                 continue;
3263               break;
3264             case STRUCT_DOMAIN:
3265               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3266                 continue;
3267               break;
3268             case LABEL_DOMAIN:
3269               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3270                 continue;
3271               break;
3272             default:
3273               break;
3274             }
3275         }
3276
3277       ++iter->next;
3278       return per_cu;
3279     }
3280
3281   return NULL;
3282 }
3283
3284 static struct symtab *
3285 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3286                    const char *name, domain_enum domain)
3287 {
3288   struct symtab *stab_best = NULL;
3289   struct mapped_index *index;
3290
3291   dw2_setup (objfile);
3292
3293   index = dwarf2_per_objfile->index_table;
3294
3295   /* index is NULL if OBJF_READNOW.  */
3296   if (index)
3297     {
3298       struct dw2_symtab_iterator iter;
3299       struct dwarf2_per_cu_data *per_cu;
3300
3301       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3302
3303       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3304         {
3305           struct symbol *sym = NULL;
3306           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3307
3308           /* Some caution must be observed with overloaded functions
3309              and methods, since the index will not contain any overload
3310              information (but NAME might contain it).  */
3311           if (stab->primary)
3312             {
3313               struct blockvector *bv = BLOCKVECTOR (stab);
3314               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3315
3316               sym = lookup_block_symbol (block, name, domain);
3317             }
3318
3319           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3320             {
3321               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3322                 return stab;
3323
3324               stab_best = stab;
3325             }
3326
3327           /* Keep looking through other CUs.  */
3328         }
3329     }
3330
3331   return stab_best;
3332 }
3333
3334 static void
3335 dw2_print_stats (struct objfile *objfile)
3336 {
3337   int i, total, count;
3338
3339   dw2_setup (objfile);
3340   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3341   count = 0;
3342   for (i = 0; i < total; ++i)
3343     {
3344       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3345
3346       if (!per_cu->v.quick->symtab)
3347         ++count;
3348     }
3349   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3350   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3351 }
3352
3353 static void
3354 dw2_dump (struct objfile *objfile)
3355 {
3356   /* Nothing worth printing.  */
3357 }
3358
3359 static void
3360 dw2_relocate (struct objfile *objfile,
3361               const struct section_offsets *new_offsets,
3362               const struct section_offsets *delta)
3363 {
3364   /* There's nothing to relocate here.  */
3365 }
3366
3367 static void
3368 dw2_expand_symtabs_for_function (struct objfile *objfile,
3369                                  const char *func_name)
3370 {
3371   struct mapped_index *index;
3372
3373   dw2_setup (objfile);
3374
3375   index = dwarf2_per_objfile->index_table;
3376
3377   /* index is NULL if OBJF_READNOW.  */
3378   if (index)
3379     {
3380       struct dw2_symtab_iterator iter;
3381       struct dwarf2_per_cu_data *per_cu;
3382
3383       /* Note: It doesn't matter what we pass for block_index here.  */
3384       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3385                             func_name);
3386
3387       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3388         dw2_instantiate_symtab (per_cu);
3389     }
3390 }
3391
3392 static void
3393 dw2_expand_all_symtabs (struct objfile *objfile)
3394 {
3395   int i;
3396
3397   dw2_setup (objfile);
3398
3399   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3400                    + dwarf2_per_objfile->n_type_units); ++i)
3401     {
3402       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3403
3404       dw2_instantiate_symtab (per_cu);
3405     }
3406 }
3407
3408 static void
3409 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3410                                   const char *fullname)
3411 {
3412   int i;
3413
3414   dw2_setup (objfile);
3415
3416   /* We don't need to consider type units here.
3417      This is only called for examining code, e.g. expand_line_sal.
3418      There can be an order of magnitude (or more) more type units
3419      than comp units, and we avoid them if we can.  */
3420
3421   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3422     {
3423       int j;
3424       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3425       struct quick_file_names *file_data;
3426
3427       /* We only need to look at symtabs not already expanded.  */
3428       if (per_cu->v.quick->symtab)
3429         continue;
3430
3431       file_data = dw2_get_file_names (per_cu);
3432       if (file_data == NULL)
3433         continue;
3434
3435       for (j = 0; j < file_data->num_file_names; ++j)
3436         {
3437           const char *this_fullname = file_data->file_names[j];
3438
3439           if (filename_cmp (this_fullname, fullname) == 0)
3440             {
3441               dw2_instantiate_symtab (per_cu);
3442               break;
3443             }
3444         }
3445     }
3446 }
3447
3448 /* A helper function for dw2_find_symbol_file that finds the primary
3449    file name for a given CU.  This is a die_reader_func.  */
3450
3451 static void
3452 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3453                                  const gdb_byte *info_ptr,
3454                                  struct die_info *comp_unit_die,
3455                                  int has_children,
3456                                  void *data)
3457 {
3458   const char **result_ptr = data;
3459   struct dwarf2_cu *cu = reader->cu;
3460   struct attribute *attr;
3461
3462   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3463   if (attr == NULL)
3464     *result_ptr = NULL;
3465   else
3466     *result_ptr = DW_STRING (attr);
3467 }
3468
3469 static const char *
3470 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3471 {
3472   struct dwarf2_per_cu_data *per_cu;
3473   offset_type *vec;
3474   const char *filename;
3475
3476   dw2_setup (objfile);
3477
3478   /* index_table is NULL if OBJF_READNOW.  */
3479   if (!dwarf2_per_objfile->index_table)
3480     {
3481       struct symtab *s;
3482
3483       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3484         {
3485           struct blockvector *bv = BLOCKVECTOR (s);
3486           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3487           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3488
3489           if (sym)
3490             {
3491               /* Only file extension of returned filename is recognized.  */
3492               return SYMBOL_SYMTAB (sym)->filename;
3493             }
3494         }
3495       return NULL;
3496     }
3497
3498   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3499                                  name, &vec))
3500     return NULL;
3501
3502   /* Note that this just looks at the very first one named NAME -- but
3503      actually we are looking for a function.  find_main_filename
3504      should be rewritten so that it doesn't require a custom hook.  It
3505      could just use the ordinary symbol tables.  */
3506   /* vec[0] is the length, which must always be >0.  */
3507   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3508
3509   if (per_cu->v.quick->symtab != NULL)
3510     {
3511       /* Only file extension of returned filename is recognized.  */
3512       return per_cu->v.quick->symtab->filename;
3513     }
3514
3515   /* Initialize filename in case there's a problem reading the DWARF,
3516      dw2_get_primary_filename_reader may not get called.  */
3517   filename = NULL;
3518   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3519                            dw2_get_primary_filename_reader, &filename);
3520
3521   /* Only file extension of returned filename is recognized.  */
3522   return filename;
3523 }
3524
3525 static void
3526 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3527                           struct objfile *objfile, int global,
3528                           int (*callback) (struct block *,
3529                                            struct symbol *, void *),
3530                           void *data, symbol_compare_ftype *match,
3531                           symbol_compare_ftype *ordered_compare)
3532 {
3533   /* Currently unimplemented; used for Ada.  The function can be called if the
3534      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3535      does not look for non-Ada symbols this function should just return.  */
3536 }
3537
3538 static void
3539 dw2_expand_symtabs_matching
3540   (struct objfile *objfile,
3541    int (*file_matcher) (const char *, void *, int basenames),
3542    int (*name_matcher) (const char *, void *),
3543    enum search_domain kind,
3544    void *data)
3545 {
3546   int i;
3547   offset_type iter;
3548   struct mapped_index *index;
3549
3550   dw2_setup (objfile);
3551
3552   /* index_table is NULL if OBJF_READNOW.  */
3553   if (!dwarf2_per_objfile->index_table)
3554     return;
3555   index = dwarf2_per_objfile->index_table;
3556
3557   if (file_matcher != NULL)
3558     {
3559       struct cleanup *cleanup;
3560       htab_t visited_found, visited_not_found;
3561
3562       visited_found = htab_create_alloc (10,
3563                                          htab_hash_pointer, htab_eq_pointer,
3564                                          NULL, xcalloc, xfree);
3565       cleanup = make_cleanup_htab_delete (visited_found);
3566       visited_not_found = htab_create_alloc (10,
3567                                              htab_hash_pointer, htab_eq_pointer,
3568                                              NULL, xcalloc, xfree);
3569       make_cleanup_htab_delete (visited_not_found);
3570
3571       /* The rule is CUs specify all the files, including those used by
3572          any TU, so there's no need to scan TUs here.  */
3573
3574       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3575         {
3576           int j;
3577           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3578           struct quick_file_names *file_data;
3579           void **slot;
3580
3581           per_cu->v.quick->mark = 0;
3582
3583           /* We only need to look at symtabs not already expanded.  */
3584           if (per_cu->v.quick->symtab)
3585             continue;
3586
3587           file_data = dw2_get_file_names (per_cu);
3588           if (file_data == NULL)
3589             continue;
3590
3591           if (htab_find (visited_not_found, file_data) != NULL)
3592             continue;
3593           else if (htab_find (visited_found, file_data) != NULL)
3594             {
3595               per_cu->v.quick->mark = 1;
3596               continue;
3597             }
3598
3599           for (j = 0; j < file_data->num_file_names; ++j)
3600             {
3601               const char *this_real_name;
3602
3603               if (file_matcher (file_data->file_names[j], data, 0))
3604                 {
3605                   per_cu->v.quick->mark = 1;
3606                   break;
3607                 }
3608
3609               /* Before we invoke realpath, which can get expensive when many
3610                  files are involved, do a quick comparison of the basenames.  */
3611               if (!basenames_may_differ
3612                   && !file_matcher (lbasename (file_data->file_names[j]),
3613                                     data, 1))
3614                 continue;
3615
3616               this_real_name = dw2_get_real_path (objfile, file_data, j);
3617               if (file_matcher (this_real_name, data, 0))
3618                 {
3619                   per_cu->v.quick->mark = 1;
3620                   break;
3621                 }
3622             }
3623
3624           slot = htab_find_slot (per_cu->v.quick->mark
3625                                  ? visited_found
3626                                  : visited_not_found,
3627                                  file_data, INSERT);
3628           *slot = file_data;
3629         }
3630
3631       do_cleanups (cleanup);
3632     }
3633
3634   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3635     {
3636       offset_type idx = 2 * iter;
3637       const char *name;
3638       offset_type *vec, vec_len, vec_idx;
3639
3640       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3641         continue;
3642
3643       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3644
3645       if (! (*name_matcher) (name, data))
3646         continue;
3647
3648       /* The name was matched, now expand corresponding CUs that were
3649          marked.  */
3650       vec = (offset_type *) (index->constant_pool
3651                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3652       vec_len = MAYBE_SWAP (vec[0]);
3653       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3654         {
3655           struct dwarf2_per_cu_data *per_cu;
3656           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3657           gdb_index_symbol_kind symbol_kind =
3658             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3659           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3660           /* Only check the symbol attributes if they're present.
3661              Indices prior to version 7 don't record them,
3662              and indices >= 7 may elide them for certain symbols
3663              (gold does this).  */
3664           int attrs_valid =
3665             (index->version >= 7
3666              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3667
3668           /* Only check the symbol's kind if it has one.  */
3669           if (attrs_valid)
3670             {
3671               switch (kind)
3672                 {
3673                 case VARIABLES_DOMAIN:
3674                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3675                     continue;
3676                   break;
3677                 case FUNCTIONS_DOMAIN:
3678                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3679                     continue;
3680                   break;
3681                 case TYPES_DOMAIN:
3682                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3683                     continue;
3684                   break;
3685                 default:
3686                   break;
3687                 }
3688             }
3689
3690           /* Don't crash on bad data.  */
3691           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3692                            + dwarf2_per_objfile->n_type_units))
3693             {
3694               complaint (&symfile_complaints,
3695                          _(".gdb_index entry has bad CU index"
3696                            " [in module %s]"), objfile->name);
3697               continue;
3698             }
3699
3700           per_cu = dw2_get_cu (cu_index);
3701           if (file_matcher == NULL || per_cu->v.quick->mark)
3702             dw2_instantiate_symtab (per_cu);
3703         }
3704     }
3705 }
3706
3707 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3708    symtab.  */
3709
3710 static struct symtab *
3711 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3712 {
3713   int i;
3714
3715   if (BLOCKVECTOR (symtab) != NULL
3716       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3717     return symtab;
3718
3719   if (symtab->includes == NULL)
3720     return NULL;
3721
3722   for (i = 0; symtab->includes[i]; ++i)
3723     {
3724       struct symtab *s = symtab->includes[i];
3725
3726       s = recursively_find_pc_sect_symtab (s, pc);
3727       if (s != NULL)
3728         return s;
3729     }
3730
3731   return NULL;
3732 }
3733
3734 static struct symtab *
3735 dw2_find_pc_sect_symtab (struct objfile *objfile,
3736                          struct minimal_symbol *msymbol,
3737                          CORE_ADDR pc,
3738                          struct obj_section *section,
3739                          int warn_if_readin)
3740 {
3741   struct dwarf2_per_cu_data *data;
3742   struct symtab *result;
3743
3744   dw2_setup (objfile);
3745
3746   if (!objfile->psymtabs_addrmap)
3747     return NULL;
3748
3749   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3750   if (!data)
3751     return NULL;
3752
3753   if (warn_if_readin && data->v.quick->symtab)
3754     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3755              paddress (get_objfile_arch (objfile), pc));
3756
3757   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3758   gdb_assert (result != NULL);
3759   return result;
3760 }
3761
3762 static void
3763 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3764                           void *data, int need_fullname)
3765 {
3766   int i;
3767   struct cleanup *cleanup;
3768   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3769                                       NULL, xcalloc, xfree);
3770
3771   cleanup = make_cleanup_htab_delete (visited);
3772   dw2_setup (objfile);
3773
3774   /* The rule is CUs specify all the files, including those used by
3775      any TU, so there's no need to scan TUs here.
3776      We can ignore file names coming from already-expanded CUs.  */
3777
3778   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3779     {
3780       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3781
3782       if (per_cu->v.quick->symtab)
3783         {
3784           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3785                                         INSERT);
3786
3787           *slot = per_cu->v.quick->file_names;
3788         }
3789     }
3790
3791   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3792     {
3793       int j;
3794       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3795       struct quick_file_names *file_data;
3796       void **slot;
3797
3798       /* We only need to look at symtabs not already expanded.  */
3799       if (per_cu->v.quick->symtab)
3800         continue;
3801
3802       file_data = dw2_get_file_names (per_cu);
3803       if (file_data == NULL)
3804         continue;
3805
3806       slot = htab_find_slot (visited, file_data, INSERT);
3807       if (*slot)
3808         {
3809           /* Already visited.  */
3810           continue;
3811         }
3812       *slot = file_data;
3813
3814       for (j = 0; j < file_data->num_file_names; ++j)
3815         {
3816           const char *this_real_name;
3817
3818           if (need_fullname)
3819             this_real_name = dw2_get_real_path (objfile, file_data, j);
3820           else
3821             this_real_name = NULL;
3822           (*fun) (file_data->file_names[j], this_real_name, data);
3823         }
3824     }
3825
3826   do_cleanups (cleanup);
3827 }
3828
3829 static int
3830 dw2_has_symbols (struct objfile *objfile)
3831 {
3832   return 1;
3833 }
3834
3835 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3836 {
3837   dw2_has_symbols,
3838   dw2_find_last_source_symtab,
3839   dw2_forget_cached_source_info,
3840   dw2_map_symtabs_matching_filename,
3841   dw2_lookup_symbol,
3842   dw2_print_stats,
3843   dw2_dump,
3844   dw2_relocate,
3845   dw2_expand_symtabs_for_function,
3846   dw2_expand_all_symtabs,
3847   dw2_expand_symtabs_with_fullname,
3848   dw2_find_symbol_file,
3849   dw2_map_matching_symbols,
3850   dw2_expand_symtabs_matching,
3851   dw2_find_pc_sect_symtab,
3852   dw2_map_symbol_filenames
3853 };
3854
3855 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3856    file will use psymtabs, or 1 if using the GNU index.  */
3857
3858 int
3859 dwarf2_initialize_objfile (struct objfile *objfile)
3860 {
3861   /* If we're about to read full symbols, don't bother with the
3862      indices.  In this case we also don't care if some other debug
3863      format is making psymtabs, because they are all about to be
3864      expanded anyway.  */
3865   if ((objfile->flags & OBJF_READNOW))
3866     {
3867       int i;
3868
3869       dwarf2_per_objfile->using_index = 1;
3870       create_all_comp_units (objfile);
3871       create_all_type_units (objfile);
3872       dwarf2_per_objfile->quick_file_names_table =
3873         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3874
3875       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3876                        + dwarf2_per_objfile->n_type_units); ++i)
3877         {
3878           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3879
3880           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3881                                             struct dwarf2_per_cu_quick_data);
3882         }
3883
3884       /* Return 1 so that gdb sees the "quick" functions.  However,
3885          these functions will be no-ops because we will have expanded
3886          all symtabs.  */
3887       return 1;
3888     }
3889
3890   if (dwarf2_read_index (objfile))
3891     return 1;
3892
3893   return 0;
3894 }
3895
3896 \f
3897
3898 /* Build a partial symbol table.  */
3899
3900 void
3901 dwarf2_build_psymtabs (struct objfile *objfile)
3902 {
3903   volatile struct gdb_exception except;
3904
3905   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3906     {
3907       init_psymbol_list (objfile, 1024);
3908     }
3909
3910   TRY_CATCH (except, RETURN_MASK_ERROR)
3911     {
3912       /* This isn't really ideal: all the data we allocate on the
3913          objfile's obstack is still uselessly kept around.  However,
3914          freeing it seems unsafe.  */
3915       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3916
3917       dwarf2_build_psymtabs_hard (objfile);
3918       discard_cleanups (cleanups);
3919     }
3920   if (except.reason < 0)
3921     exception_print (gdb_stderr, except);
3922 }
3923
3924 /* Return the total length of the CU described by HEADER.  */
3925
3926 static unsigned int
3927 get_cu_length (const struct comp_unit_head *header)
3928 {
3929   return header->initial_length_size + header->length;
3930 }
3931
3932 /* Return TRUE if OFFSET is within CU_HEADER.  */
3933
3934 static inline int
3935 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3936 {
3937   sect_offset bottom = { cu_header->offset.sect_off };
3938   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3939
3940   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3941 }
3942
3943 /* Find the base address of the compilation unit for range lists and
3944    location lists.  It will normally be specified by DW_AT_low_pc.
3945    In DWARF-3 draft 4, the base address could be overridden by
3946    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3947    compilation units with discontinuous ranges.  */
3948
3949 static void
3950 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3951 {
3952   struct attribute *attr;
3953
3954   cu->base_known = 0;
3955   cu->base_address = 0;
3956
3957   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3958   if (attr)
3959     {
3960       cu->base_address = DW_ADDR (attr);
3961       cu->base_known = 1;
3962     }
3963   else
3964     {
3965       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3966       if (attr)
3967         {
3968           cu->base_address = DW_ADDR (attr);
3969           cu->base_known = 1;
3970         }
3971     }
3972 }
3973
3974 /* Read in the comp unit header information from the debug_info at info_ptr.
3975    NOTE: This leaves members offset, first_die_offset to be filled in
3976    by the caller.  */
3977
3978 static const gdb_byte *
3979 read_comp_unit_head (struct comp_unit_head *cu_header,
3980                      const gdb_byte *info_ptr, bfd *abfd)
3981 {
3982   int signed_addr;
3983   unsigned int bytes_read;
3984
3985   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3986   cu_header->initial_length_size = bytes_read;
3987   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3988   info_ptr += bytes_read;
3989   cu_header->version = read_2_bytes (abfd, info_ptr);
3990   info_ptr += 2;
3991   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3992                                              &bytes_read);
3993   info_ptr += bytes_read;
3994   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3995   info_ptr += 1;
3996   signed_addr = bfd_get_sign_extend_vma (abfd);
3997   if (signed_addr < 0)
3998     internal_error (__FILE__, __LINE__,
3999                     _("read_comp_unit_head: dwarf from non elf file"));
4000   cu_header->signed_addr_p = signed_addr;
4001
4002   return info_ptr;
4003 }
4004
4005 /* Helper function that returns the proper abbrev section for
4006    THIS_CU.  */
4007
4008 static struct dwarf2_section_info *
4009 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4010 {
4011   struct dwarf2_section_info *abbrev;
4012
4013   if (this_cu->is_dwz)
4014     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4015   else
4016     abbrev = &dwarf2_per_objfile->abbrev;
4017
4018   return abbrev;
4019 }
4020
4021 /* Subroutine of read_and_check_comp_unit_head and
4022    read_and_check_type_unit_head to simplify them.
4023    Perform various error checking on the header.  */
4024
4025 static void
4026 error_check_comp_unit_head (struct comp_unit_head *header,
4027                             struct dwarf2_section_info *section,
4028                             struct dwarf2_section_info *abbrev_section)
4029 {
4030   bfd *abfd = section->asection->owner;
4031   const char *filename = bfd_get_filename (abfd);
4032
4033   if (header->version != 2 && header->version != 3 && header->version != 4)
4034     error (_("Dwarf Error: wrong version in compilation unit header "
4035            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4036            filename);
4037
4038   if (header->abbrev_offset.sect_off
4039       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4040     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4041            "(offset 0x%lx + 6) [in module %s]"),
4042            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4043            filename);
4044
4045   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4046      avoid potential 32-bit overflow.  */
4047   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4048       > section->size)
4049     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4050            "(offset 0x%lx + 0) [in module %s]"),
4051            (long) header->length, (long) header->offset.sect_off,
4052            filename);
4053 }
4054
4055 /* Read in a CU/TU header and perform some basic error checking.
4056    The contents of the header are stored in HEADER.
4057    The result is a pointer to the start of the first DIE.  */
4058
4059 static const gdb_byte *
4060 read_and_check_comp_unit_head (struct comp_unit_head *header,
4061                                struct dwarf2_section_info *section,
4062                                struct dwarf2_section_info *abbrev_section,
4063                                const gdb_byte *info_ptr,
4064                                int is_debug_types_section)
4065 {
4066   const gdb_byte *beg_of_comp_unit = info_ptr;
4067   bfd *abfd = section->asection->owner;
4068
4069   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4070
4071   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4072
4073   /* If we're reading a type unit, skip over the signature and
4074      type_offset fields.  */
4075   if (is_debug_types_section)
4076     info_ptr += 8 /*signature*/ + header->offset_size;
4077
4078   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4079
4080   error_check_comp_unit_head (header, section, abbrev_section);
4081
4082   return info_ptr;
4083 }
4084
4085 /* Read in the types comp unit header information from .debug_types entry at
4086    types_ptr.  The result is a pointer to one past the end of the header.  */
4087
4088 static const gdb_byte *
4089 read_and_check_type_unit_head (struct comp_unit_head *header,
4090                                struct dwarf2_section_info *section,
4091                                struct dwarf2_section_info *abbrev_section,
4092                                const gdb_byte *info_ptr,
4093                                ULONGEST *signature,
4094                                cu_offset *type_offset_in_tu)
4095 {
4096   const gdb_byte *beg_of_comp_unit = info_ptr;
4097   bfd *abfd = section->asection->owner;
4098
4099   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4100
4101   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4102
4103   /* If we're reading a type unit, skip over the signature and
4104      type_offset fields.  */
4105   if (signature != NULL)
4106     *signature = read_8_bytes (abfd, info_ptr);
4107   info_ptr += 8;
4108   if (type_offset_in_tu != NULL)
4109     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4110                                                header->offset_size);
4111   info_ptr += header->offset_size;
4112
4113   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4114
4115   error_check_comp_unit_head (header, section, abbrev_section);
4116
4117   return info_ptr;
4118 }
4119
4120 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4121
4122 static sect_offset
4123 read_abbrev_offset (struct dwarf2_section_info *section,
4124                     sect_offset offset)
4125 {
4126   bfd *abfd = section->asection->owner;
4127   const gdb_byte *info_ptr;
4128   unsigned int length, initial_length_size, offset_size;
4129   sect_offset abbrev_offset;
4130
4131   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4132   info_ptr = section->buffer + offset.sect_off;
4133   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4134   offset_size = initial_length_size == 4 ? 4 : 8;
4135   info_ptr += initial_length_size + 2 /*version*/;
4136   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4137   return abbrev_offset;
4138 }
4139
4140 /* Allocate a new partial symtab for file named NAME and mark this new
4141    partial symtab as being an include of PST.  */
4142
4143 static void
4144 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4145                                struct objfile *objfile)
4146 {
4147   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4148
4149   if (!IS_ABSOLUTE_PATH (subpst->filename))
4150     {
4151       /* It shares objfile->objfile_obstack.  */
4152       subpst->dirname = pst->dirname;
4153     }
4154
4155   subpst->section_offsets = pst->section_offsets;
4156   subpst->textlow = 0;
4157   subpst->texthigh = 0;
4158
4159   subpst->dependencies = (struct partial_symtab **)
4160     obstack_alloc (&objfile->objfile_obstack,
4161                    sizeof (struct partial_symtab *));
4162   subpst->dependencies[0] = pst;
4163   subpst->number_of_dependencies = 1;
4164
4165   subpst->globals_offset = 0;
4166   subpst->n_global_syms = 0;
4167   subpst->statics_offset = 0;
4168   subpst->n_static_syms = 0;
4169   subpst->symtab = NULL;
4170   subpst->read_symtab = pst->read_symtab;
4171   subpst->readin = 0;
4172
4173   /* No private part is necessary for include psymtabs.  This property
4174      can be used to differentiate between such include psymtabs and
4175      the regular ones.  */
4176   subpst->read_symtab_private = NULL;
4177 }
4178
4179 /* Read the Line Number Program data and extract the list of files
4180    included by the source file represented by PST.  Build an include
4181    partial symtab for each of these included files.  */
4182
4183 static void
4184 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4185                                struct die_info *die,
4186                                struct partial_symtab *pst)
4187 {
4188   struct line_header *lh = NULL;
4189   struct attribute *attr;
4190
4191   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4192   if (attr)
4193     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4194   if (lh == NULL)
4195     return;  /* No linetable, so no includes.  */
4196
4197   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4198   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4199
4200   free_line_header (lh);
4201 }
4202
4203 static hashval_t
4204 hash_signatured_type (const void *item)
4205 {
4206   const struct signatured_type *sig_type = item;
4207
4208   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4209   return sig_type->signature;
4210 }
4211
4212 static int
4213 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4214 {
4215   const struct signatured_type *lhs = item_lhs;
4216   const struct signatured_type *rhs = item_rhs;
4217
4218   return lhs->signature == rhs->signature;
4219 }
4220
4221 /* Allocate a hash table for signatured types.  */
4222
4223 static htab_t
4224 allocate_signatured_type_table (struct objfile *objfile)
4225 {
4226   return htab_create_alloc_ex (41,
4227                                hash_signatured_type,
4228                                eq_signatured_type,
4229                                NULL,
4230                                &objfile->objfile_obstack,
4231                                hashtab_obstack_allocate,
4232                                dummy_obstack_deallocate);
4233 }
4234
4235 /* A helper function to add a signatured type CU to a table.  */
4236
4237 static int
4238 add_signatured_type_cu_to_table (void **slot, void *datum)
4239 {
4240   struct signatured_type *sigt = *slot;
4241   struct signatured_type ***datap = datum;
4242
4243   **datap = sigt;
4244   ++*datap;
4245
4246   return 1;
4247 }
4248
4249 /* Create the hash table of all entries in the .debug_types
4250    (or .debug_types.dwo) section(s).
4251    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4252    otherwise it is NULL.
4253
4254    The result is a pointer to the hash table or NULL if there are no types.
4255
4256    Note: This function processes DWO files only, not DWP files.  */
4257
4258 static htab_t
4259 create_debug_types_hash_table (struct dwo_file *dwo_file,
4260                                VEC (dwarf2_section_info_def) *types)
4261 {
4262   struct objfile *objfile = dwarf2_per_objfile->objfile;
4263   htab_t types_htab = NULL;
4264   int ix;
4265   struct dwarf2_section_info *section;
4266   struct dwarf2_section_info *abbrev_section;
4267
4268   if (VEC_empty (dwarf2_section_info_def, types))
4269     return NULL;
4270
4271   abbrev_section = (dwo_file != NULL
4272                     ? &dwo_file->sections.abbrev
4273                     : &dwarf2_per_objfile->abbrev);
4274
4275   if (dwarf2_read_debug)
4276     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4277                         dwo_file ? ".dwo" : "",
4278                         bfd_get_filename (abbrev_section->asection->owner));
4279
4280   for (ix = 0;
4281        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4282        ++ix)
4283     {
4284       bfd *abfd;
4285       const gdb_byte *info_ptr, *end_ptr;
4286       struct dwarf2_section_info *abbrev_section;
4287
4288       dwarf2_read_section (objfile, section);
4289       info_ptr = section->buffer;
4290
4291       if (info_ptr == NULL)
4292         continue;
4293
4294       /* We can't set abfd until now because the section may be empty or
4295          not present, in which case section->asection will be NULL.  */
4296       abfd = section->asection->owner;
4297
4298       if (dwo_file)
4299         abbrev_section = &dwo_file->sections.abbrev;
4300       else
4301         abbrev_section = &dwarf2_per_objfile->abbrev;
4302
4303       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4304          because we don't need to read any dies: the signature is in the
4305          header.  */
4306
4307       end_ptr = info_ptr + section->size;
4308       while (info_ptr < end_ptr)
4309         {
4310           sect_offset offset;
4311           cu_offset type_offset_in_tu;
4312           ULONGEST signature;
4313           struct signatured_type *sig_type;
4314           struct dwo_unit *dwo_tu;
4315           void **slot;
4316           const gdb_byte *ptr = info_ptr;
4317           struct comp_unit_head header;
4318           unsigned int length;
4319
4320           offset.sect_off = ptr - section->buffer;
4321
4322           /* We need to read the type's signature in order to build the hash
4323              table, but we don't need anything else just yet.  */
4324
4325           ptr = read_and_check_type_unit_head (&header, section,
4326                                                abbrev_section, ptr,
4327                                                &signature, &type_offset_in_tu);
4328
4329           length = get_cu_length (&header);
4330
4331           /* Skip dummy type units.  */
4332           if (ptr >= info_ptr + length
4333               || peek_abbrev_code (abfd, ptr) == 0)
4334             {
4335               info_ptr += length;
4336               continue;
4337             }
4338
4339           if (types_htab == NULL)
4340             {
4341               if (dwo_file)
4342                 types_htab = allocate_dwo_unit_table (objfile);
4343               else
4344                 types_htab = allocate_signatured_type_table (objfile);
4345             }
4346
4347           if (dwo_file)
4348             {
4349               sig_type = NULL;
4350               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4351                                        struct dwo_unit);
4352               dwo_tu->dwo_file = dwo_file;
4353               dwo_tu->signature = signature;
4354               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4355               dwo_tu->section = section;
4356               dwo_tu->offset = offset;
4357               dwo_tu->length = length;
4358             }
4359           else
4360             {
4361               /* N.B.: type_offset is not usable if this type uses a DWO file.
4362                  The real type_offset is in the DWO file.  */
4363               dwo_tu = NULL;
4364               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4365                                          struct signatured_type);
4366               sig_type->signature = signature;
4367               sig_type->type_offset_in_tu = type_offset_in_tu;
4368               sig_type->per_cu.objfile = objfile;
4369               sig_type->per_cu.is_debug_types = 1;
4370               sig_type->per_cu.section = section;
4371               sig_type->per_cu.offset = offset;
4372               sig_type->per_cu.length = length;
4373             }
4374
4375           slot = htab_find_slot (types_htab,
4376                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4377                                  INSERT);
4378           gdb_assert (slot != NULL);
4379           if (*slot != NULL)
4380             {
4381               sect_offset dup_offset;
4382
4383               if (dwo_file)
4384                 {
4385                   const struct dwo_unit *dup_tu = *slot;
4386
4387                   dup_offset = dup_tu->offset;
4388                 }
4389               else
4390                 {
4391                   const struct signatured_type *dup_tu = *slot;
4392
4393                   dup_offset = dup_tu->per_cu.offset;
4394                 }
4395
4396               complaint (&symfile_complaints,
4397                          _("debug type entry at offset 0x%x is duplicate to"
4398                            " the entry at offset 0x%x, signature %s"),
4399                          offset.sect_off, dup_offset.sect_off,
4400                          hex_string (signature));
4401             }
4402           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4403
4404           if (dwarf2_read_debug)
4405             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4406                                 offset.sect_off,
4407                                 hex_string (signature));
4408
4409           info_ptr += length;
4410         }
4411     }
4412
4413   return types_htab;
4414 }
4415
4416 /* Create the hash table of all entries in the .debug_types section,
4417    and initialize all_type_units.
4418    The result is zero if there is an error (e.g. missing .debug_types section),
4419    otherwise non-zero.  */
4420
4421 static int
4422 create_all_type_units (struct objfile *objfile)
4423 {
4424   htab_t types_htab;
4425   struct signatured_type **iter;
4426
4427   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4428   if (types_htab == NULL)
4429     {
4430       dwarf2_per_objfile->signatured_types = NULL;
4431       return 0;
4432     }
4433
4434   dwarf2_per_objfile->signatured_types = types_htab;
4435
4436   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4437   dwarf2_per_objfile->all_type_units
4438     = xmalloc (dwarf2_per_objfile->n_type_units
4439                * sizeof (struct signatured_type *));
4440   iter = &dwarf2_per_objfile->all_type_units[0];
4441   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4442   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4443               == dwarf2_per_objfile->n_type_units);
4444
4445   return 1;
4446 }
4447
4448 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4449    Fill in SIG_ENTRY with DWO_ENTRY.  */
4450
4451 static void
4452 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4453                                   struct signatured_type *sig_entry,
4454                                   struct dwo_unit *dwo_entry)
4455 {
4456   /* Make sure we're not clobbering something we don't expect to.  */
4457   gdb_assert (! sig_entry->per_cu.queued);
4458   gdb_assert (sig_entry->per_cu.cu == NULL);
4459   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4460   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4461   gdb_assert (sig_entry->signature == dwo_entry->signature);
4462   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4463   gdb_assert (sig_entry->type_unit_group == NULL);
4464   gdb_assert (sig_entry->dwo_unit == NULL);
4465
4466   sig_entry->per_cu.section = dwo_entry->section;
4467   sig_entry->per_cu.offset = dwo_entry->offset;
4468   sig_entry->per_cu.length = dwo_entry->length;
4469   sig_entry->per_cu.reading_dwo_directly = 1;
4470   sig_entry->per_cu.objfile = objfile;
4471   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4472   sig_entry->dwo_unit = dwo_entry;
4473 }
4474
4475 /* Subroutine of lookup_signatured_type.
4476    If we haven't read the TU yet, create the signatured_type data structure
4477    for a TU to be read in directly from a DWO file, bypassing the stub.
4478    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4479    using .gdb_index, then when reading a CU we want to stay in the DWO file
4480    containing that CU.  Otherwise we could end up reading several other DWO
4481    files (due to comdat folding) to process the transitive closure of all the
4482    mentioned TUs, and that can be slow.  The current DWO file will have every
4483    type signature that it needs.
4484    We only do this for .gdb_index because in the psymtab case we already have
4485    to read all the DWOs to build the type unit groups.  */
4486
4487 static struct signatured_type *
4488 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4489 {
4490   struct objfile *objfile = dwarf2_per_objfile->objfile;
4491   struct dwo_file *dwo_file;
4492   struct dwo_unit find_dwo_entry, *dwo_entry;
4493   struct signatured_type find_sig_entry, *sig_entry;
4494
4495   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4496
4497   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4498      dwo_unit of the TU itself.  */
4499   dwo_file = cu->dwo_unit->dwo_file;
4500
4501   /* We only ever need to read in one copy of a signatured type.
4502      Just use the global signatured_types array.  If this is the first time
4503      we're reading this type, replace the recorded data from .gdb_index with
4504      this TU.  */
4505
4506   if (dwarf2_per_objfile->signatured_types == NULL)
4507     return NULL;
4508   find_sig_entry.signature = sig;
4509   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4510   if (sig_entry == NULL)
4511     return NULL;
4512
4513   /* We can get here with the TU already read, *or* in the process of being
4514      read.  Don't reassign it if that's the case.  Also note that if the TU is
4515      already being read, it may not have come from a DWO, the program may be
4516      a mix of Fission-compiled code and non-Fission-compiled code.  */
4517   /* Have we already tried to read this TU?  */
4518   if (sig_entry->per_cu.tu_read)
4519     return sig_entry;
4520
4521   /* Ok, this is the first time we're reading this TU.  */
4522   if (dwo_file->tus == NULL)
4523     return NULL;
4524   find_dwo_entry.signature = sig;
4525   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4526   if (dwo_entry == NULL)
4527     return NULL;
4528
4529   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4530   return sig_entry;
4531 }
4532
4533 /* Subroutine of lookup_dwp_signatured_type.
4534    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4535
4536 static struct signatured_type *
4537 add_type_unit (ULONGEST sig)
4538 {
4539   struct objfile *objfile = dwarf2_per_objfile->objfile;
4540   int n_type_units = dwarf2_per_objfile->n_type_units;
4541   struct signatured_type *sig_type;
4542   void **slot;
4543
4544   ++n_type_units;
4545   dwarf2_per_objfile->all_type_units =
4546     xrealloc (dwarf2_per_objfile->all_type_units,
4547               n_type_units * sizeof (struct signatured_type *));
4548   dwarf2_per_objfile->n_type_units = n_type_units;
4549   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4550                              struct signatured_type);
4551   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4552   sig_type->signature = sig;
4553   sig_type->per_cu.is_debug_types = 1;
4554   sig_type->per_cu.v.quick =
4555     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4556                     struct dwarf2_per_cu_quick_data);
4557   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4558                          sig_type, INSERT);
4559   gdb_assert (*slot == NULL);
4560   *slot = sig_type;
4561   /* The rest of sig_type must be filled in by the caller.  */
4562   return sig_type;
4563 }
4564
4565 /* Subroutine of lookup_signatured_type.
4566    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4567    then try the DWP file.
4568    Normally this "can't happen", but if there's a bug in signature
4569    generation and/or the DWP file is built incorrectly, it can happen.
4570    Using the type directly from the DWP file means we don't have the stub
4571    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4572    not critical.  [Eventually the stub may go away for type units anyway.]  */
4573
4574 static struct signatured_type *
4575 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4576 {
4577   struct objfile *objfile = dwarf2_per_objfile->objfile;
4578   struct dwp_file *dwp_file = get_dwp_file ();
4579   struct dwo_unit *dwo_entry;
4580   struct signatured_type find_sig_entry, *sig_entry;
4581
4582   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4583   gdb_assert (dwp_file != NULL);
4584
4585   if (dwarf2_per_objfile->signatured_types != NULL)
4586     {
4587       find_sig_entry.signature = sig;
4588       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4589                              &find_sig_entry);
4590       if (sig_entry != NULL)
4591         return sig_entry;
4592     }
4593
4594   /* This is the "shouldn't happen" case.
4595      Try the DWP file and hope for the best.  */
4596   if (dwp_file->tus == NULL)
4597     return NULL;
4598   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4599                                  sig, 1 /* is_debug_types */);
4600   if (dwo_entry == NULL)
4601     return NULL;
4602
4603   sig_entry = add_type_unit (sig);
4604   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4605
4606   /* The caller will signal a complaint if we return NULL.
4607      Here we don't return NULL but we still want to complain.  */
4608   complaint (&symfile_complaints,
4609              _("Bad type signature %s referenced by %s at 0x%x,"
4610                " coping by using copy in DWP [in module %s]"),
4611              hex_string (sig),
4612              cu->per_cu->is_debug_types ? "TU" : "CU",
4613              cu->per_cu->offset.sect_off,
4614              objfile->name);
4615
4616   return sig_entry;
4617 }
4618
4619 /* Lookup a signature based type for DW_FORM_ref_sig8.
4620    Returns NULL if signature SIG is not present in the table.
4621    It is up to the caller to complain about this.  */
4622
4623 static struct signatured_type *
4624 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4625 {
4626   if (cu->dwo_unit
4627       && dwarf2_per_objfile->using_index)
4628     {
4629       /* We're in a DWO/DWP file, and we're using .gdb_index.
4630          These cases require special processing.  */
4631       if (get_dwp_file () == NULL)
4632         return lookup_dwo_signatured_type (cu, sig);
4633       else
4634         return lookup_dwp_signatured_type (cu, sig);
4635     }
4636   else
4637     {
4638       struct signatured_type find_entry, *entry;
4639
4640       if (dwarf2_per_objfile->signatured_types == NULL)
4641         return NULL;
4642       find_entry.signature = sig;
4643       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4644       return entry;
4645     }
4646 }
4647 \f
4648 /* Low level DIE reading support.  */
4649
4650 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4651
4652 static void
4653 init_cu_die_reader (struct die_reader_specs *reader,
4654                     struct dwarf2_cu *cu,
4655                     struct dwarf2_section_info *section,
4656                     struct dwo_file *dwo_file)
4657 {
4658   gdb_assert (section->readin && section->buffer != NULL);
4659   reader->abfd = section->asection->owner;
4660   reader->cu = cu;
4661   reader->dwo_file = dwo_file;
4662   reader->die_section = section;
4663   reader->buffer = section->buffer;
4664   reader->buffer_end = section->buffer + section->size;
4665   reader->comp_dir = NULL;
4666 }
4667
4668 /* Subroutine of init_cutu_and_read_dies to simplify it.
4669    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4670    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4671    already.
4672
4673    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4674    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4675    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4676    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4677    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4678    COMP_DIR must be non-NULL.
4679    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4680    are filled in with the info of the DIE from the DWO file.
4681    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4682    provided an abbrev table to use.
4683    The result is non-zero if a valid (non-dummy) DIE was found.  */
4684
4685 static int
4686 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4687                         struct dwo_unit *dwo_unit,
4688                         int abbrev_table_provided,
4689                         struct die_info *stub_comp_unit_die,
4690                         const char *stub_comp_dir,
4691                         struct die_reader_specs *result_reader,
4692                         const gdb_byte **result_info_ptr,
4693                         struct die_info **result_comp_unit_die,
4694                         int *result_has_children)
4695 {
4696   struct objfile *objfile = dwarf2_per_objfile->objfile;
4697   struct dwarf2_cu *cu = this_cu->cu;
4698   struct dwarf2_section_info *section;
4699   bfd *abfd;
4700   const gdb_byte *begin_info_ptr, *info_ptr;
4701   const char *comp_dir_string;
4702   ULONGEST signature; /* Or dwo_id.  */
4703   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4704   int i,num_extra_attrs;
4705   struct dwarf2_section_info *dwo_abbrev_section;
4706   struct attribute *attr;
4707   struct attribute comp_dir_attr;
4708   struct die_info *comp_unit_die;
4709
4710   /* Both can't be provided.  */
4711   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4712
4713   /* These attributes aren't processed until later:
4714      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4715      However, the attribute is found in the stub which we won't have later.
4716      In order to not impose this complication on the rest of the code,
4717      we read them here and copy them to the DWO CU/TU die.  */
4718
4719   stmt_list = NULL;
4720   low_pc = NULL;
4721   high_pc = NULL;
4722   ranges = NULL;
4723   comp_dir = NULL;
4724
4725   if (stub_comp_unit_die != NULL)
4726     {
4727       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4728          DWO file.  */
4729       if (! this_cu->is_debug_types)
4730         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4731       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4732       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4733       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4734       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4735
4736       /* There should be a DW_AT_addr_base attribute here (if needed).
4737          We need the value before we can process DW_FORM_GNU_addr_index.  */
4738       cu->addr_base = 0;
4739       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4740       if (attr)
4741         cu->addr_base = DW_UNSND (attr);
4742
4743       /* There should be a DW_AT_ranges_base attribute here (if needed).
4744          We need the value before we can process DW_AT_ranges.  */
4745       cu->ranges_base = 0;
4746       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4747       if (attr)
4748         cu->ranges_base = DW_UNSND (attr);
4749     }
4750   else if (stub_comp_dir != NULL)
4751     {
4752       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4753       comp_dir = (struct attribute *)
4754         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4755       comp_dir->name = DW_AT_comp_dir;
4756       comp_dir->form = DW_FORM_string;
4757       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4758       DW_STRING (comp_dir) = stub_comp_dir;
4759     }
4760
4761   /* Set up for reading the DWO CU/TU.  */
4762   cu->dwo_unit = dwo_unit;
4763   section = dwo_unit->section;
4764   dwarf2_read_section (objfile, section);
4765   abfd = section->asection->owner;
4766   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4767   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4768   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4769
4770   if (this_cu->is_debug_types)
4771     {
4772       ULONGEST header_signature;
4773       cu_offset type_offset_in_tu;
4774       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4775
4776       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4777                                                 dwo_abbrev_section,
4778                                                 info_ptr,
4779                                                 &header_signature,
4780                                                 &type_offset_in_tu);
4781       /* This is not an assert because it can be caused by bad debug info.  */
4782       if (sig_type->signature != header_signature)
4783         {
4784           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4785                    " TU at offset 0x%x [in module %s]"),
4786                  hex_string (sig_type->signature),
4787                  hex_string (header_signature),
4788                  dwo_unit->offset.sect_off,
4789                  bfd_get_filename (abfd));
4790         }
4791       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4792       /* For DWOs coming from DWP files, we don't know the CU length
4793          nor the type's offset in the TU until now.  */
4794       dwo_unit->length = get_cu_length (&cu->header);
4795       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4796
4797       /* Establish the type offset that can be used to lookup the type.
4798          For DWO files, we don't know it until now.  */
4799       sig_type->type_offset_in_section.sect_off =
4800         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4801     }
4802   else
4803     {
4804       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4805                                                 dwo_abbrev_section,
4806                                                 info_ptr, 0);
4807       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4808       /* For DWOs coming from DWP files, we don't know the CU length
4809          until now.  */
4810       dwo_unit->length = get_cu_length (&cu->header);
4811     }
4812
4813   /* Replace the CU's original abbrev table with the DWO's.
4814      Reminder: We can't read the abbrev table until we've read the header.  */
4815   if (abbrev_table_provided)
4816     {
4817       /* Don't free the provided abbrev table, the caller of
4818          init_cutu_and_read_dies owns it.  */
4819       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4820       /* Ensure the DWO abbrev table gets freed.  */
4821       make_cleanup (dwarf2_free_abbrev_table, cu);
4822     }
4823   else
4824     {
4825       dwarf2_free_abbrev_table (cu);
4826       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4827       /* Leave any existing abbrev table cleanup as is.  */
4828     }
4829
4830   /* Read in the die, but leave space to copy over the attributes
4831      from the stub.  This has the benefit of simplifying the rest of
4832      the code - all the work to maintain the illusion of a single
4833      DW_TAG_{compile,type}_unit DIE is done here.  */
4834   num_extra_attrs = ((stmt_list != NULL)
4835                      + (low_pc != NULL)
4836                      + (high_pc != NULL)
4837                      + (ranges != NULL)
4838                      + (comp_dir != NULL));
4839   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4840                               result_has_children, num_extra_attrs);
4841
4842   /* Copy over the attributes from the stub to the DIE we just read in.  */
4843   comp_unit_die = *result_comp_unit_die;
4844   i = comp_unit_die->num_attrs;
4845   if (stmt_list != NULL)
4846     comp_unit_die->attrs[i++] = *stmt_list;
4847   if (low_pc != NULL)
4848     comp_unit_die->attrs[i++] = *low_pc;
4849   if (high_pc != NULL)
4850     comp_unit_die->attrs[i++] = *high_pc;
4851   if (ranges != NULL)
4852     comp_unit_die->attrs[i++] = *ranges;
4853   if (comp_dir != NULL)
4854     comp_unit_die->attrs[i++] = *comp_dir;
4855   comp_unit_die->num_attrs += num_extra_attrs;
4856
4857   if (dwarf2_die_debug)
4858     {
4859       fprintf_unfiltered (gdb_stdlog,
4860                           "Read die from %s@0x%x of %s:\n",
4861                           bfd_section_name (abfd, section->asection),
4862                           (unsigned) (begin_info_ptr - section->buffer),
4863                           bfd_get_filename (abfd));
4864       dump_die (comp_unit_die, dwarf2_die_debug);
4865     }
4866
4867   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4868      TUs by skipping the stub and going directly to the entry in the DWO file.
4869      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4870      to get it via circuitous means.  Blech.  */
4871   if (comp_dir != NULL)
4872     result_reader->comp_dir = DW_STRING (comp_dir);
4873
4874   /* Skip dummy compilation units.  */
4875   if (info_ptr >= begin_info_ptr + dwo_unit->length
4876       || peek_abbrev_code (abfd, info_ptr) == 0)
4877     return 0;
4878
4879   *result_info_ptr = info_ptr;
4880   return 1;
4881 }
4882
4883 /* Subroutine of init_cutu_and_read_dies to simplify it.
4884    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4885    Returns NULL if the specified DWO unit cannot be found.  */
4886
4887 static struct dwo_unit *
4888 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4889                  struct die_info *comp_unit_die)
4890 {
4891   struct dwarf2_cu *cu = this_cu->cu;
4892   struct attribute *attr;
4893   ULONGEST signature;
4894   struct dwo_unit *dwo_unit;
4895   const char *comp_dir, *dwo_name;
4896
4897   gdb_assert (cu != NULL);
4898
4899   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4900   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4901   gdb_assert (attr != NULL);
4902   dwo_name = DW_STRING (attr);
4903   comp_dir = NULL;
4904   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4905   if (attr)
4906     comp_dir = DW_STRING (attr);
4907
4908   if (this_cu->is_debug_types)
4909     {
4910       struct signatured_type *sig_type;
4911
4912       /* Since this_cu is the first member of struct signatured_type,
4913          we can go from a pointer to one to a pointer to the other.  */
4914       sig_type = (struct signatured_type *) this_cu;
4915       signature = sig_type->signature;
4916       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4917     }
4918   else
4919     {
4920       struct attribute *attr;
4921
4922       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4923       if (! attr)
4924         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4925                  " [in module %s]"),
4926                dwo_name, this_cu->objfile->name);
4927       signature = DW_UNSND (attr);
4928       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4929                                        signature);
4930     }
4931
4932   return dwo_unit;
4933 }
4934
4935 /* Subroutine of init_cutu_and_read_dies to simplify it.
4936    Read a TU directly from a DWO file, bypassing the stub.  */
4937
4938 static void
4939 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4940                            die_reader_func_ftype *die_reader_func,
4941                            void *data)
4942 {
4943   struct dwarf2_cu *cu;
4944   struct signatured_type *sig_type;
4945   struct cleanup *cleanups, *free_cu_cleanup;
4946   struct die_reader_specs reader;
4947   const gdb_byte *info_ptr;
4948   struct die_info *comp_unit_die;
4949   int has_children;
4950
4951   /* Verify we can do the following downcast, and that we have the
4952      data we need.  */
4953   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4954   sig_type = (struct signatured_type *) this_cu;
4955   gdb_assert (sig_type->dwo_unit != NULL);
4956
4957   cleanups = make_cleanup (null_cleanup, NULL);
4958
4959   gdb_assert (this_cu->cu == NULL);
4960   cu = xmalloc (sizeof (*cu));
4961   init_one_comp_unit (cu, this_cu);
4962   /* If an error occurs while loading, release our storage.  */
4963   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4964
4965   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4966                               0 /* abbrev_table_provided */,
4967                               NULL /* stub_comp_unit_die */,
4968                               sig_type->dwo_unit->dwo_file->comp_dir,
4969                               &reader, &info_ptr,
4970                               &comp_unit_die, &has_children) == 0)
4971     {
4972       /* Dummy die.  */
4973       do_cleanups (cleanups);
4974       return;
4975     }
4976
4977   /* All the "real" work is done here.  */
4978   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4979
4980   /* This duplicates some code in init_cutu_and_read_dies,
4981      but the alternative is making the latter more complex.
4982      This function is only for the special case of using DWO files directly:
4983      no point in overly complicating the general case just to handle this.  */
4984   if (keep)
4985     {
4986       /* We've successfully allocated this compilation unit.  Let our
4987          caller clean it up when finished with it.  */
4988       discard_cleanups (free_cu_cleanup);
4989
4990       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4991          So we have to manually free the abbrev table.  */
4992       dwarf2_free_abbrev_table (cu);
4993
4994       /* Link this CU into read_in_chain.  */
4995       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4996       dwarf2_per_objfile->read_in_chain = this_cu;
4997     }
4998   else
4999     do_cleanups (free_cu_cleanup);
5000
5001   do_cleanups (cleanups);
5002 }
5003
5004 /* Initialize a CU (or TU) and read its DIEs.
5005    If the CU defers to a DWO file, read the DWO file as well.
5006
5007    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5008    Otherwise the table specified in the comp unit header is read in and used.
5009    This is an optimization for when we already have the abbrev table.
5010
5011    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5012    Otherwise, a new CU is allocated with xmalloc.
5013
5014    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5015    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5016
5017    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5018    linker) then DIE_READER_FUNC will not get called.  */
5019
5020 static void
5021 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5022                          struct abbrev_table *abbrev_table,
5023                          int use_existing_cu, int keep,
5024                          die_reader_func_ftype *die_reader_func,
5025                          void *data)
5026 {
5027   struct objfile *objfile = dwarf2_per_objfile->objfile;
5028   struct dwarf2_section_info *section = this_cu->section;
5029   bfd *abfd = section->asection->owner;
5030   struct dwarf2_cu *cu;
5031   const gdb_byte *begin_info_ptr, *info_ptr;
5032   struct die_reader_specs reader;
5033   struct die_info *comp_unit_die;
5034   int has_children;
5035   struct attribute *attr;
5036   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5037   struct signatured_type *sig_type = NULL;
5038   struct dwarf2_section_info *abbrev_section;
5039   /* Non-zero if CU currently points to a DWO file and we need to
5040      reread it.  When this happens we need to reread the skeleton die
5041      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5042   int rereading_dwo_cu = 0;
5043
5044   if (dwarf2_die_debug)
5045     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5046                         this_cu->is_debug_types ? "type" : "comp",
5047                         this_cu->offset.sect_off);
5048
5049   if (use_existing_cu)
5050     gdb_assert (keep);
5051
5052   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5053      file (instead of going through the stub), short-circuit all of this.  */
5054   if (this_cu->reading_dwo_directly)
5055     {
5056       /* Narrow down the scope of possibilities to have to understand.  */
5057       gdb_assert (this_cu->is_debug_types);
5058       gdb_assert (abbrev_table == NULL);
5059       gdb_assert (!use_existing_cu);
5060       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5061       return;
5062     }
5063
5064   cleanups = make_cleanup (null_cleanup, NULL);
5065
5066   /* This is cheap if the section is already read in.  */
5067   dwarf2_read_section (objfile, section);
5068
5069   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5070
5071   abbrev_section = get_abbrev_section_for_cu (this_cu);
5072
5073   if (use_existing_cu && this_cu->cu != NULL)
5074     {
5075       cu = this_cu->cu;
5076
5077       /* If this CU is from a DWO file we need to start over, we need to
5078          refetch the attributes from the skeleton CU.
5079          This could be optimized by retrieving those attributes from when we
5080          were here the first time: the previous comp_unit_die was stored in
5081          comp_unit_obstack.  But there's no data yet that we need this
5082          optimization.  */
5083       if (cu->dwo_unit != NULL)
5084         rereading_dwo_cu = 1;
5085     }
5086   else
5087     {
5088       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5089       gdb_assert (this_cu->cu == NULL);
5090
5091       cu = xmalloc (sizeof (*cu));
5092       init_one_comp_unit (cu, this_cu);
5093
5094       /* If an error occurs while loading, release our storage.  */
5095       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5096     }
5097
5098   /* Get the header.  */
5099   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5100     {
5101       /* We already have the header, there's no need to read it in again.  */
5102       info_ptr += cu->header.first_die_offset.cu_off;
5103     }
5104   else
5105     {
5106       if (this_cu->is_debug_types)
5107         {
5108           ULONGEST signature;
5109           cu_offset type_offset_in_tu;
5110
5111           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5112                                                     abbrev_section, info_ptr,
5113                                                     &signature,
5114                                                     &type_offset_in_tu);
5115
5116           /* Since per_cu is the first member of struct signatured_type,
5117              we can go from a pointer to one to a pointer to the other.  */
5118           sig_type = (struct signatured_type *) this_cu;
5119           gdb_assert (sig_type->signature == signature);
5120           gdb_assert (sig_type->type_offset_in_tu.cu_off
5121                       == type_offset_in_tu.cu_off);
5122           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5123
5124           /* LENGTH has not been set yet for type units if we're
5125              using .gdb_index.  */
5126           this_cu->length = get_cu_length (&cu->header);
5127
5128           /* Establish the type offset that can be used to lookup the type.  */
5129           sig_type->type_offset_in_section.sect_off =
5130             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5131         }
5132       else
5133         {
5134           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5135                                                     abbrev_section,
5136                                                     info_ptr, 0);
5137
5138           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5139           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5140         }
5141     }
5142
5143   /* Skip dummy compilation units.  */
5144   if (info_ptr >= begin_info_ptr + this_cu->length
5145       || peek_abbrev_code (abfd, info_ptr) == 0)
5146     {
5147       do_cleanups (cleanups);
5148       return;
5149     }
5150
5151   /* If we don't have them yet, read the abbrevs for this compilation unit.
5152      And if we need to read them now, make sure they're freed when we're
5153      done.  Note that it's important that if the CU had an abbrev table
5154      on entry we don't free it when we're done: Somewhere up the call stack
5155      it may be in use.  */
5156   if (abbrev_table != NULL)
5157     {
5158       gdb_assert (cu->abbrev_table == NULL);
5159       gdb_assert (cu->header.abbrev_offset.sect_off
5160                   == abbrev_table->offset.sect_off);
5161       cu->abbrev_table = abbrev_table;
5162     }
5163   else if (cu->abbrev_table == NULL)
5164     {
5165       dwarf2_read_abbrevs (cu, abbrev_section);
5166       make_cleanup (dwarf2_free_abbrev_table, cu);
5167     }
5168   else if (rereading_dwo_cu)
5169     {
5170       dwarf2_free_abbrev_table (cu);
5171       dwarf2_read_abbrevs (cu, abbrev_section);
5172     }
5173
5174   /* Read the top level CU/TU die.  */
5175   init_cu_die_reader (&reader, cu, section, NULL);
5176   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5177
5178   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5179      from the DWO file.
5180      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5181      DWO CU, that this test will fail (the attribute will not be present).  */
5182   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5183   if (attr)
5184     {
5185       struct dwo_unit *dwo_unit;
5186       struct die_info *dwo_comp_unit_die;
5187
5188       if (has_children)
5189         {
5190           complaint (&symfile_complaints,
5191                      _("compilation unit with DW_AT_GNU_dwo_name"
5192                        " has children (offset 0x%x) [in module %s]"),
5193                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5194         }
5195       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5196       if (dwo_unit != NULL)
5197         {
5198           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5199                                       abbrev_table != NULL,
5200                                       comp_unit_die, NULL,
5201                                       &reader, &info_ptr,
5202                                       &dwo_comp_unit_die, &has_children) == 0)
5203             {
5204               /* Dummy die.  */
5205               do_cleanups (cleanups);
5206               return;
5207             }
5208           comp_unit_die = dwo_comp_unit_die;
5209         }
5210       else
5211         {
5212           /* Yikes, we couldn't find the rest of the DIE, we only have
5213              the stub.  A complaint has already been logged.  There's
5214              not much more we can do except pass on the stub DIE to
5215              die_reader_func.  We don't want to throw an error on bad
5216              debug info.  */
5217         }
5218     }
5219
5220   /* All of the above is setup for this call.  Yikes.  */
5221   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5222
5223   /* Done, clean up.  */
5224   if (free_cu_cleanup != NULL)
5225     {
5226       if (keep)
5227         {
5228           /* We've successfully allocated this compilation unit.  Let our
5229              caller clean it up when finished with it.  */
5230           discard_cleanups (free_cu_cleanup);
5231
5232           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5233              So we have to manually free the abbrev table.  */
5234           dwarf2_free_abbrev_table (cu);
5235
5236           /* Link this CU into read_in_chain.  */
5237           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5238           dwarf2_per_objfile->read_in_chain = this_cu;
5239         }
5240       else
5241         do_cleanups (free_cu_cleanup);
5242     }
5243
5244   do_cleanups (cleanups);
5245 }
5246
5247 /* Read CU/TU THIS_CU in section SECTION,
5248    but do not follow DW_AT_GNU_dwo_name if present.
5249    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5250    to have already done the lookup to find the DWO/DWP file).
5251
5252    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5253    THIS_CU->is_debug_types, but nothing else.
5254
5255    We fill in THIS_CU->length.
5256
5257    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5258    linker) then DIE_READER_FUNC will not get called.
5259
5260    THIS_CU->cu is always freed when done.
5261    This is done in order to not leave THIS_CU->cu in a state where we have
5262    to care whether it refers to the "main" CU or the DWO CU.  */
5263
5264 static void
5265 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5266                                    struct dwarf2_section_info *abbrev_section,
5267                                    struct dwo_file *dwo_file,
5268                                    die_reader_func_ftype *die_reader_func,
5269                                    void *data)
5270 {
5271   struct objfile *objfile = dwarf2_per_objfile->objfile;
5272   struct dwarf2_section_info *section = this_cu->section;
5273   bfd *abfd = section->asection->owner;
5274   struct dwarf2_cu cu;
5275   const gdb_byte *begin_info_ptr, *info_ptr;
5276   struct die_reader_specs reader;
5277   struct cleanup *cleanups;
5278   struct die_info *comp_unit_die;
5279   int has_children;
5280
5281   if (dwarf2_die_debug)
5282     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5283                         this_cu->is_debug_types ? "type" : "comp",
5284                         this_cu->offset.sect_off);
5285
5286   gdb_assert (this_cu->cu == NULL);
5287
5288   /* This is cheap if the section is already read in.  */
5289   dwarf2_read_section (objfile, section);
5290
5291   init_one_comp_unit (&cu, this_cu);
5292
5293   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5294
5295   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5296   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5297                                             abbrev_section, info_ptr,
5298                                             this_cu->is_debug_types);
5299
5300   this_cu->length = get_cu_length (&cu.header);
5301
5302   /* Skip dummy compilation units.  */
5303   if (info_ptr >= begin_info_ptr + this_cu->length
5304       || peek_abbrev_code (abfd, info_ptr) == 0)
5305     {
5306       do_cleanups (cleanups);
5307       return;
5308     }
5309
5310   dwarf2_read_abbrevs (&cu, abbrev_section);
5311   make_cleanup (dwarf2_free_abbrev_table, &cu);
5312
5313   init_cu_die_reader (&reader, &cu, section, dwo_file);
5314   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5315
5316   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5317
5318   do_cleanups (cleanups);
5319 }
5320
5321 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5322    does not lookup the specified DWO file.
5323    This cannot be used to read DWO files.
5324
5325    THIS_CU->cu is always freed when done.
5326    This is done in order to not leave THIS_CU->cu in a state where we have
5327    to care whether it refers to the "main" CU or the DWO CU.
5328    We can revisit this if the data shows there's a performance issue.  */
5329
5330 static void
5331 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5332                                 die_reader_func_ftype *die_reader_func,
5333                                 void *data)
5334 {
5335   init_cutu_and_read_dies_no_follow (this_cu,
5336                                      get_abbrev_section_for_cu (this_cu),
5337                                      NULL,
5338                                      die_reader_func, data);
5339 }
5340 \f
5341 /* Type Unit Groups.
5342
5343    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5344    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5345    so that all types coming from the same compilation (.o file) are grouped
5346    together.  A future step could be to put the types in the same symtab as
5347    the CU the types ultimately came from.  */
5348
5349 static hashval_t
5350 hash_type_unit_group (const void *item)
5351 {
5352   const struct type_unit_group *tu_group = item;
5353
5354   return hash_stmt_list_entry (&tu_group->hash);
5355 }
5356
5357 static int
5358 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5359 {
5360   const struct type_unit_group *lhs = item_lhs;
5361   const struct type_unit_group *rhs = item_rhs;
5362
5363   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5364 }
5365
5366 /* Allocate a hash table for type unit groups.  */
5367
5368 static htab_t
5369 allocate_type_unit_groups_table (void)
5370 {
5371   return htab_create_alloc_ex (3,
5372                                hash_type_unit_group,
5373                                eq_type_unit_group,
5374                                NULL,
5375                                &dwarf2_per_objfile->objfile->objfile_obstack,
5376                                hashtab_obstack_allocate,
5377                                dummy_obstack_deallocate);
5378 }
5379
5380 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5381    partial symtabs.  We combine several TUs per psymtab to not let the size
5382    of any one psymtab grow too big.  */
5383 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5384 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5385
5386 /* Helper routine for get_type_unit_group.
5387    Create the type_unit_group object used to hold one or more TUs.  */
5388
5389 static struct type_unit_group *
5390 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5391 {
5392   struct objfile *objfile = dwarf2_per_objfile->objfile;
5393   struct dwarf2_per_cu_data *per_cu;
5394   struct type_unit_group *tu_group;
5395
5396   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5397                              struct type_unit_group);
5398   per_cu = &tu_group->per_cu;
5399   per_cu->objfile = objfile;
5400
5401   if (dwarf2_per_objfile->using_index)
5402     {
5403       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5404                                         struct dwarf2_per_cu_quick_data);
5405     }
5406   else
5407     {
5408       unsigned int line_offset = line_offset_struct.sect_off;
5409       struct partial_symtab *pst;
5410       char *name;
5411
5412       /* Give the symtab a useful name for debug purposes.  */
5413       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5414         name = xstrprintf ("<type_units_%d>",
5415                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5416       else
5417         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5418
5419       pst = create_partial_symtab (per_cu, name);
5420       pst->anonymous = 1;
5421
5422       xfree (name);
5423     }
5424
5425   tu_group->hash.dwo_unit = cu->dwo_unit;
5426   tu_group->hash.line_offset = line_offset_struct;
5427
5428   return tu_group;
5429 }
5430
5431 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5432    STMT_LIST is a DW_AT_stmt_list attribute.  */
5433
5434 static struct type_unit_group *
5435 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5436 {
5437   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5438   struct type_unit_group *tu_group;
5439   void **slot;
5440   unsigned int line_offset;
5441   struct type_unit_group type_unit_group_for_lookup;
5442
5443   if (dwarf2_per_objfile->type_unit_groups == NULL)
5444     {
5445       dwarf2_per_objfile->type_unit_groups =
5446         allocate_type_unit_groups_table ();
5447     }
5448
5449   /* Do we need to create a new group, or can we use an existing one?  */
5450
5451   if (stmt_list)
5452     {
5453       line_offset = DW_UNSND (stmt_list);
5454       ++tu_stats->nr_symtab_sharers;
5455     }
5456   else
5457     {
5458       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5459          We can do various things here like create one group per TU or
5460          spread them over multiple groups to split up the expansion work.
5461          To avoid worst case scenarios (too many groups or too large groups)
5462          we, umm, group them in bunches.  */
5463       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5464                      | (tu_stats->nr_stmt_less_type_units
5465                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5466       ++tu_stats->nr_stmt_less_type_units;
5467     }
5468
5469   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5470   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5471   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5472                          &type_unit_group_for_lookup, INSERT);
5473   if (*slot != NULL)
5474     {
5475       tu_group = *slot;
5476       gdb_assert (tu_group != NULL);
5477     }
5478   else
5479     {
5480       sect_offset line_offset_struct;
5481
5482       line_offset_struct.sect_off = line_offset;
5483       tu_group = create_type_unit_group (cu, line_offset_struct);
5484       *slot = tu_group;
5485       ++tu_stats->nr_symtabs;
5486     }
5487
5488   return tu_group;
5489 }
5490
5491 /* Struct used to sort TUs by their abbreviation table offset.  */
5492
5493 struct tu_abbrev_offset
5494 {
5495   struct signatured_type *sig_type;
5496   sect_offset abbrev_offset;
5497 };
5498
5499 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5500
5501 static int
5502 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5503 {
5504   const struct tu_abbrev_offset * const *a = ap;
5505   const struct tu_abbrev_offset * const *b = bp;
5506   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5507   unsigned int boff = (*b)->abbrev_offset.sect_off;
5508
5509   return (aoff > boff) - (aoff < boff);
5510 }
5511
5512 /* A helper function to add a type_unit_group to a table.  */
5513
5514 static int
5515 add_type_unit_group_to_table (void **slot, void *datum)
5516 {
5517   struct type_unit_group *tu_group = *slot;
5518   struct type_unit_group ***datap = datum;
5519
5520   **datap = tu_group;
5521   ++*datap;
5522
5523   return 1;
5524 }
5525
5526 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5527    each one passing FUNC,DATA.
5528
5529    The efficiency is because we sort TUs by the abbrev table they use and
5530    only read each abbrev table once.  In one program there are 200K TUs
5531    sharing 8K abbrev tables.
5532
5533    The main purpose of this function is to support building the
5534    dwarf2_per_objfile->type_unit_groups table.
5535    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5536    can collapse the search space by grouping them by stmt_list.
5537    The savings can be significant, in the same program from above the 200K TUs
5538    share 8K stmt_list tables.
5539
5540    FUNC is expected to call get_type_unit_group, which will create the
5541    struct type_unit_group if necessary and add it to
5542    dwarf2_per_objfile->type_unit_groups.  */
5543
5544 static void
5545 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5546 {
5547   struct objfile *objfile = dwarf2_per_objfile->objfile;
5548   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5549   struct cleanup *cleanups;
5550   struct abbrev_table *abbrev_table;
5551   sect_offset abbrev_offset;
5552   struct tu_abbrev_offset *sorted_by_abbrev;
5553   struct type_unit_group **iter;
5554   int i;
5555
5556   /* It's up to the caller to not call us multiple times.  */
5557   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5558
5559   if (dwarf2_per_objfile->n_type_units == 0)
5560     return;
5561
5562   /* TUs typically share abbrev tables, and there can be way more TUs than
5563      abbrev tables.  Sort by abbrev table to reduce the number of times we
5564      read each abbrev table in.
5565      Alternatives are to punt or to maintain a cache of abbrev tables.
5566      This is simpler and efficient enough for now.
5567
5568      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5569      symtab to use).  Typically TUs with the same abbrev offset have the same
5570      stmt_list value too so in practice this should work well.
5571
5572      The basic algorithm here is:
5573
5574       sort TUs by abbrev table
5575       for each TU with same abbrev table:
5576         read abbrev table if first user
5577         read TU top level DIE
5578           [IWBN if DWO skeletons had DW_AT_stmt_list]
5579         call FUNC  */
5580
5581   if (dwarf2_read_debug)
5582     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5583
5584   /* Sort in a separate table to maintain the order of all_type_units
5585      for .gdb_index: TU indices directly index all_type_units.  */
5586   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5587                               dwarf2_per_objfile->n_type_units);
5588   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5589     {
5590       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5591
5592       sorted_by_abbrev[i].sig_type = sig_type;
5593       sorted_by_abbrev[i].abbrev_offset =
5594         read_abbrev_offset (sig_type->per_cu.section,
5595                             sig_type->per_cu.offset);
5596     }
5597   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5598   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5599          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5600
5601   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5602      called any number of times, so we don't reset tu_stats here.  */
5603
5604   abbrev_offset.sect_off = ~(unsigned) 0;
5605   abbrev_table = NULL;
5606   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5607
5608   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5609     {
5610       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5611
5612       /* Switch to the next abbrev table if necessary.  */
5613       if (abbrev_table == NULL
5614           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5615         {
5616           if (abbrev_table != NULL)
5617             {
5618               abbrev_table_free (abbrev_table);
5619               /* Reset to NULL in case abbrev_table_read_table throws
5620                  an error: abbrev_table_free_cleanup will get called.  */
5621               abbrev_table = NULL;
5622             }
5623           abbrev_offset = tu->abbrev_offset;
5624           abbrev_table =
5625             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5626                                      abbrev_offset);
5627           ++tu_stats->nr_uniq_abbrev_tables;
5628         }
5629
5630       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5631                                func, data);
5632     }
5633
5634   /* type_unit_groups can be NULL if there is an error in the debug info.
5635      Just create an empty table so the rest of gdb doesn't have to watch
5636      for this error case.  */
5637   if (dwarf2_per_objfile->type_unit_groups == NULL)
5638     {
5639       dwarf2_per_objfile->type_unit_groups =
5640         allocate_type_unit_groups_table ();
5641       dwarf2_per_objfile->n_type_unit_groups = 0;
5642     }
5643
5644   /* Create a vector of pointers to primary type units to make it easy to
5645      iterate over them and CUs.  See dw2_get_primary_cu.  */
5646   dwarf2_per_objfile->n_type_unit_groups =
5647     htab_elements (dwarf2_per_objfile->type_unit_groups);
5648   dwarf2_per_objfile->all_type_unit_groups =
5649     obstack_alloc (&objfile->objfile_obstack,
5650                    dwarf2_per_objfile->n_type_unit_groups
5651                    * sizeof (struct type_unit_group *));
5652   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5653   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5654                           add_type_unit_group_to_table, &iter);
5655   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5656               == dwarf2_per_objfile->n_type_unit_groups);
5657
5658   do_cleanups (cleanups);
5659
5660   if (dwarf2_read_debug)
5661     {
5662       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5663       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5664                           dwarf2_per_objfile->n_type_units);
5665       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5666                           tu_stats->nr_uniq_abbrev_tables);
5667       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5668                           tu_stats->nr_symtabs);
5669       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5670                           tu_stats->nr_symtab_sharers);
5671       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5672                           tu_stats->nr_stmt_less_type_units);
5673     }
5674 }
5675 \f
5676 /* Partial symbol tables.  */
5677
5678 /* Create a psymtab named NAME and assign it to PER_CU.
5679
5680    The caller must fill in the following details:
5681    dirname, textlow, texthigh.  */
5682
5683 static struct partial_symtab *
5684 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5685 {
5686   struct objfile *objfile = per_cu->objfile;
5687   struct partial_symtab *pst;
5688
5689   pst = start_psymtab_common (objfile, objfile->section_offsets,
5690                               name, 0,
5691                               objfile->global_psymbols.next,
5692                               objfile->static_psymbols.next);
5693
5694   pst->psymtabs_addrmap_supported = 1;
5695
5696   /* This is the glue that links PST into GDB's symbol API.  */
5697   pst->read_symtab_private = per_cu;
5698   pst->read_symtab = dwarf2_read_symtab;
5699   per_cu->v.psymtab = pst;
5700
5701   return pst;
5702 }
5703
5704 /* die_reader_func for process_psymtab_comp_unit.  */
5705
5706 static void
5707 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5708                                   const gdb_byte *info_ptr,
5709                                   struct die_info *comp_unit_die,
5710                                   int has_children,
5711                                   void *data)
5712 {
5713   struct dwarf2_cu *cu = reader->cu;
5714   struct objfile *objfile = cu->objfile;
5715   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5716   struct attribute *attr;
5717   CORE_ADDR baseaddr;
5718   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5719   struct partial_symtab *pst;
5720   int has_pc_info;
5721   const char *filename;
5722   int *want_partial_unit_ptr = data;
5723
5724   if (comp_unit_die->tag == DW_TAG_partial_unit
5725       && (want_partial_unit_ptr == NULL
5726           || !*want_partial_unit_ptr))
5727     return;
5728
5729   gdb_assert (! per_cu->is_debug_types);
5730
5731   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5732
5733   cu->list_in_scope = &file_symbols;
5734
5735   /* Allocate a new partial symbol table structure.  */
5736   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5737   if (attr == NULL || !DW_STRING (attr))
5738     filename = "";
5739   else
5740     filename = DW_STRING (attr);
5741
5742   pst = create_partial_symtab (per_cu, filename);
5743
5744   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5745   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5746   if (attr != NULL)
5747     pst->dirname = DW_STRING (attr);
5748
5749   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5750
5751   dwarf2_find_base_address (comp_unit_die, cu);
5752
5753   /* Possibly set the default values of LOWPC and HIGHPC from
5754      `DW_AT_ranges'.  */
5755   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5756                                       &best_highpc, cu, pst);
5757   if (has_pc_info == 1 && best_lowpc < best_highpc)
5758     /* Store the contiguous range if it is not empty; it can be empty for
5759        CUs with no code.  */
5760     addrmap_set_empty (objfile->psymtabs_addrmap,
5761                        best_lowpc + baseaddr,
5762                        best_highpc + baseaddr - 1, pst);
5763
5764   /* Check if comp unit has_children.
5765      If so, read the rest of the partial symbols from this comp unit.
5766      If not, there's no more debug_info for this comp unit.  */
5767   if (has_children)
5768     {
5769       struct partial_die_info *first_die;
5770       CORE_ADDR lowpc, highpc;
5771
5772       lowpc = ((CORE_ADDR) -1);
5773       highpc = ((CORE_ADDR) 0);
5774
5775       first_die = load_partial_dies (reader, info_ptr, 1);
5776
5777       scan_partial_symbols (first_die, &lowpc, &highpc,
5778                             ! has_pc_info, cu);
5779
5780       /* If we didn't find a lowpc, set it to highpc to avoid
5781          complaints from `maint check'.  */
5782       if (lowpc == ((CORE_ADDR) -1))
5783         lowpc = highpc;
5784
5785       /* If the compilation unit didn't have an explicit address range,
5786          then use the information extracted from its child dies.  */
5787       if (! has_pc_info)
5788         {
5789           best_lowpc = lowpc;
5790           best_highpc = highpc;
5791         }
5792     }
5793   pst->textlow = best_lowpc + baseaddr;
5794   pst->texthigh = best_highpc + baseaddr;
5795
5796   pst->n_global_syms = objfile->global_psymbols.next -
5797     (objfile->global_psymbols.list + pst->globals_offset);
5798   pst->n_static_syms = objfile->static_psymbols.next -
5799     (objfile->static_psymbols.list + pst->statics_offset);
5800   sort_pst_symbols (objfile, pst);
5801
5802   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5803     {
5804       int i;
5805       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5806       struct dwarf2_per_cu_data *iter;
5807
5808       /* Fill in 'dependencies' here; we fill in 'users' in a
5809          post-pass.  */
5810       pst->number_of_dependencies = len;
5811       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5812                                          len * sizeof (struct symtab *));
5813       for (i = 0;
5814            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5815                         i, iter);
5816            ++i)
5817         pst->dependencies[i] = iter->v.psymtab;
5818
5819       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5820     }
5821
5822   /* Get the list of files included in the current compilation unit,
5823      and build a psymtab for each of them.  */
5824   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5825
5826   if (dwarf2_read_debug)
5827     {
5828       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5829
5830       fprintf_unfiltered (gdb_stdlog,
5831                           "Psymtab for %s unit @0x%x: %s - %s"
5832                           ", %d global, %d static syms\n",
5833                           per_cu->is_debug_types ? "type" : "comp",
5834                           per_cu->offset.sect_off,
5835                           paddress (gdbarch, pst->textlow),
5836                           paddress (gdbarch, pst->texthigh),
5837                           pst->n_global_syms, pst->n_static_syms);
5838     }
5839 }
5840
5841 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5842    Process compilation unit THIS_CU for a psymtab.  */
5843
5844 static void
5845 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5846                            int want_partial_unit)
5847 {
5848   /* If this compilation unit was already read in, free the
5849      cached copy in order to read it in again.  This is
5850      necessary because we skipped some symbols when we first
5851      read in the compilation unit (see load_partial_dies).
5852      This problem could be avoided, but the benefit is unclear.  */
5853   if (this_cu->cu != NULL)
5854     free_one_cached_comp_unit (this_cu);
5855
5856   gdb_assert (! this_cu->is_debug_types);
5857   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5858                            process_psymtab_comp_unit_reader,
5859                            &want_partial_unit);
5860
5861   /* Age out any secondary CUs.  */
5862   age_cached_comp_units ();
5863 }
5864
5865 /* Reader function for build_type_psymtabs.  */
5866
5867 static void
5868 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5869                             const gdb_byte *info_ptr,
5870                             struct die_info *type_unit_die,
5871                             int has_children,
5872                             void *data)
5873 {
5874   struct objfile *objfile = dwarf2_per_objfile->objfile;
5875   struct dwarf2_cu *cu = reader->cu;
5876   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5877   struct signatured_type *sig_type;
5878   struct type_unit_group *tu_group;
5879   struct attribute *attr;
5880   struct partial_die_info *first_die;
5881   CORE_ADDR lowpc, highpc;
5882   struct partial_symtab *pst;
5883
5884   gdb_assert (data == NULL);
5885   gdb_assert (per_cu->is_debug_types);
5886   sig_type = (struct signatured_type *) per_cu;
5887
5888   if (! has_children)
5889     return;
5890
5891   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5892   tu_group = get_type_unit_group (cu, attr);
5893
5894   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5895
5896   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5897   cu->list_in_scope = &file_symbols;
5898   pst = create_partial_symtab (per_cu, "");
5899   pst->anonymous = 1;
5900
5901   first_die = load_partial_dies (reader, info_ptr, 1);
5902
5903   lowpc = (CORE_ADDR) -1;
5904   highpc = (CORE_ADDR) 0;
5905   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5906
5907   pst->n_global_syms = objfile->global_psymbols.next -
5908     (objfile->global_psymbols.list + pst->globals_offset);
5909   pst->n_static_syms = objfile->static_psymbols.next -
5910     (objfile->static_psymbols.list + pst->statics_offset);
5911   sort_pst_symbols (objfile, pst);
5912 }
5913
5914 /* Traversal function for build_type_psymtabs.  */
5915
5916 static int
5917 build_type_psymtab_dependencies (void **slot, void *info)
5918 {
5919   struct objfile *objfile = dwarf2_per_objfile->objfile;
5920   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5921   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5922   struct partial_symtab *pst = per_cu->v.psymtab;
5923   int len = VEC_length (sig_type_ptr, tu_group->tus);
5924   struct signatured_type *iter;
5925   int i;
5926
5927   gdb_assert (len > 0);
5928   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5929
5930   pst->number_of_dependencies = len;
5931   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5932                                      len * sizeof (struct psymtab *));
5933   for (i = 0;
5934        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5935        ++i)
5936     {
5937       gdb_assert (iter->per_cu.is_debug_types);
5938       pst->dependencies[i] = iter->per_cu.v.psymtab;
5939       iter->type_unit_group = tu_group;
5940     }
5941
5942   VEC_free (sig_type_ptr, tu_group->tus);
5943
5944   return 1;
5945 }
5946
5947 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5948    Build partial symbol tables for the .debug_types comp-units.  */
5949
5950 static void
5951 build_type_psymtabs (struct objfile *objfile)
5952 {
5953   if (! create_all_type_units (objfile))
5954     return;
5955
5956   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5957
5958   /* Now that all TUs have been processed we can fill in the dependencies.  */
5959   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5960                           build_type_psymtab_dependencies, NULL);
5961 }
5962
5963 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5964
5965 static void
5966 psymtabs_addrmap_cleanup (void *o)
5967 {
5968   struct objfile *objfile = o;
5969
5970   objfile->psymtabs_addrmap = NULL;
5971 }
5972
5973 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5974
5975 static void
5976 set_partial_user (struct objfile *objfile)
5977 {
5978   int i;
5979
5980   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5981     {
5982       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5983       struct partial_symtab *pst = per_cu->v.psymtab;
5984       int j;
5985
5986       if (pst == NULL)
5987         continue;
5988
5989       for (j = 0; j < pst->number_of_dependencies; ++j)
5990         {
5991           /* Set the 'user' field only if it is not already set.  */
5992           if (pst->dependencies[j]->user == NULL)
5993             pst->dependencies[j]->user = pst;
5994         }
5995     }
5996 }
5997
5998 /* Build the partial symbol table by doing a quick pass through the
5999    .debug_info and .debug_abbrev sections.  */
6000
6001 static void
6002 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6003 {
6004   struct cleanup *back_to, *addrmap_cleanup;
6005   struct obstack temp_obstack;
6006   int i;
6007
6008   if (dwarf2_read_debug)
6009     {
6010       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6011                           objfile->name);
6012     }
6013
6014   dwarf2_per_objfile->reading_partial_symbols = 1;
6015
6016   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6017
6018   /* Any cached compilation units will be linked by the per-objfile
6019      read_in_chain.  Make sure to free them when we're done.  */
6020   back_to = make_cleanup (free_cached_comp_units, NULL);
6021
6022   build_type_psymtabs (objfile);
6023
6024   create_all_comp_units (objfile);
6025
6026   /* Create a temporary address map on a temporary obstack.  We later
6027      copy this to the final obstack.  */
6028   obstack_init (&temp_obstack);
6029   make_cleanup_obstack_free (&temp_obstack);
6030   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6031   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6032
6033   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6034     {
6035       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6036
6037       process_psymtab_comp_unit (per_cu, 0);
6038     }
6039
6040   set_partial_user (objfile);
6041
6042   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6043                                                     &objfile->objfile_obstack);
6044   discard_cleanups (addrmap_cleanup);
6045
6046   do_cleanups (back_to);
6047
6048   if (dwarf2_read_debug)
6049     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6050                         objfile->name);
6051 }
6052
6053 /* die_reader_func for load_partial_comp_unit.  */
6054
6055 static void
6056 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6057                                const gdb_byte *info_ptr,
6058                                struct die_info *comp_unit_die,
6059                                int has_children,
6060                                void *data)
6061 {
6062   struct dwarf2_cu *cu = reader->cu;
6063
6064   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6065
6066   /* Check if comp unit has_children.
6067      If so, read the rest of the partial symbols from this comp unit.
6068      If not, there's no more debug_info for this comp unit.  */
6069   if (has_children)
6070     load_partial_dies (reader, info_ptr, 0);
6071 }
6072
6073 /* Load the partial DIEs for a secondary CU into memory.
6074    This is also used when rereading a primary CU with load_all_dies.  */
6075
6076 static void
6077 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6078 {
6079   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6080                            load_partial_comp_unit_reader, NULL);
6081 }
6082
6083 static void
6084 read_comp_units_from_section (struct objfile *objfile,
6085                               struct dwarf2_section_info *section,
6086                               unsigned int is_dwz,
6087                               int *n_allocated,
6088                               int *n_comp_units,
6089                               struct dwarf2_per_cu_data ***all_comp_units)
6090 {
6091   const gdb_byte *info_ptr;
6092   bfd *abfd = section->asection->owner;
6093
6094   if (dwarf2_read_debug)
6095     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6096                         section->asection->name, bfd_get_filename (abfd));
6097
6098   dwarf2_read_section (objfile, section);
6099
6100   info_ptr = section->buffer;
6101
6102   while (info_ptr < section->buffer + section->size)
6103     {
6104       unsigned int length, initial_length_size;
6105       struct dwarf2_per_cu_data *this_cu;
6106       sect_offset offset;
6107
6108       offset.sect_off = info_ptr - section->buffer;
6109
6110       /* Read just enough information to find out where the next
6111          compilation unit is.  */
6112       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6113
6114       /* Save the compilation unit for later lookup.  */
6115       this_cu = obstack_alloc (&objfile->objfile_obstack,
6116                                sizeof (struct dwarf2_per_cu_data));
6117       memset (this_cu, 0, sizeof (*this_cu));
6118       this_cu->offset = offset;
6119       this_cu->length = length + initial_length_size;
6120       this_cu->is_dwz = is_dwz;
6121       this_cu->objfile = objfile;
6122       this_cu->section = section;
6123
6124       if (*n_comp_units == *n_allocated)
6125         {
6126           *n_allocated *= 2;
6127           *all_comp_units = xrealloc (*all_comp_units,
6128                                       *n_allocated
6129                                       * sizeof (struct dwarf2_per_cu_data *));
6130         }
6131       (*all_comp_units)[*n_comp_units] = this_cu;
6132       ++*n_comp_units;
6133
6134       info_ptr = info_ptr + this_cu->length;
6135     }
6136 }
6137
6138 /* Create a list of all compilation units in OBJFILE.
6139    This is only done for -readnow and building partial symtabs.  */
6140
6141 static void
6142 create_all_comp_units (struct objfile *objfile)
6143 {
6144   int n_allocated;
6145   int n_comp_units;
6146   struct dwarf2_per_cu_data **all_comp_units;
6147   struct dwz_file *dwz;
6148
6149   n_comp_units = 0;
6150   n_allocated = 10;
6151   all_comp_units = xmalloc (n_allocated
6152                             * sizeof (struct dwarf2_per_cu_data *));
6153
6154   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6155                                 &n_allocated, &n_comp_units, &all_comp_units);
6156
6157   dwz = dwarf2_get_dwz_file ();
6158   if (dwz != NULL)
6159     read_comp_units_from_section (objfile, &dwz->info, 1,
6160                                   &n_allocated, &n_comp_units,
6161                                   &all_comp_units);
6162
6163   dwarf2_per_objfile->all_comp_units
6164     = obstack_alloc (&objfile->objfile_obstack,
6165                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6166   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6167           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6168   xfree (all_comp_units);
6169   dwarf2_per_objfile->n_comp_units = n_comp_units;
6170 }
6171
6172 /* Process all loaded DIEs for compilation unit CU, starting at
6173    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6174    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6175    DW_AT_ranges).  If NEED_PC is set, then this function will set
6176    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6177    and record the covered ranges in the addrmap.  */
6178
6179 static void
6180 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6181                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6182 {
6183   struct partial_die_info *pdi;
6184
6185   /* Now, march along the PDI's, descending into ones which have
6186      interesting children but skipping the children of the other ones,
6187      until we reach the end of the compilation unit.  */
6188
6189   pdi = first_die;
6190
6191   while (pdi != NULL)
6192     {
6193       fixup_partial_die (pdi, cu);
6194
6195       /* Anonymous namespaces or modules have no name but have interesting
6196          children, so we need to look at them.  Ditto for anonymous
6197          enums.  */
6198
6199       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6200           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6201           || pdi->tag == DW_TAG_imported_unit)
6202         {
6203           switch (pdi->tag)
6204             {
6205             case DW_TAG_subprogram:
6206               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6207               break;
6208             case DW_TAG_constant:
6209             case DW_TAG_variable:
6210             case DW_TAG_typedef:
6211             case DW_TAG_union_type:
6212               if (!pdi->is_declaration)
6213                 {
6214                   add_partial_symbol (pdi, cu);
6215                 }
6216               break;
6217             case DW_TAG_class_type:
6218             case DW_TAG_interface_type:
6219             case DW_TAG_structure_type:
6220               if (!pdi->is_declaration)
6221                 {
6222                   add_partial_symbol (pdi, cu);
6223                 }
6224               break;
6225             case DW_TAG_enumeration_type:
6226               if (!pdi->is_declaration)
6227                 add_partial_enumeration (pdi, cu);
6228               break;
6229             case DW_TAG_base_type:
6230             case DW_TAG_subrange_type:
6231               /* File scope base type definitions are added to the partial
6232                  symbol table.  */
6233               add_partial_symbol (pdi, cu);
6234               break;
6235             case DW_TAG_namespace:
6236               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6237               break;
6238             case DW_TAG_module:
6239               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6240               break;
6241             case DW_TAG_imported_unit:
6242               {
6243                 struct dwarf2_per_cu_data *per_cu;
6244
6245                 /* For now we don't handle imported units in type units.  */
6246                 if (cu->per_cu->is_debug_types)
6247                   {
6248                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6249                              " supported in type units [in module %s]"),
6250                            cu->objfile->name);
6251                   }
6252
6253                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6254                                                            pdi->is_dwz,
6255                                                            cu->objfile);
6256
6257                 /* Go read the partial unit, if needed.  */
6258                 if (per_cu->v.psymtab == NULL)
6259                   process_psymtab_comp_unit (per_cu, 1);
6260
6261                 VEC_safe_push (dwarf2_per_cu_ptr,
6262                                cu->per_cu->imported_symtabs, per_cu);
6263               }
6264               break;
6265             default:
6266               break;
6267             }
6268         }
6269
6270       /* If the die has a sibling, skip to the sibling.  */
6271
6272       pdi = pdi->die_sibling;
6273     }
6274 }
6275
6276 /* Functions used to compute the fully scoped name of a partial DIE.
6277
6278    Normally, this is simple.  For C++, the parent DIE's fully scoped
6279    name is concatenated with "::" and the partial DIE's name.  For
6280    Java, the same thing occurs except that "." is used instead of "::".
6281    Enumerators are an exception; they use the scope of their parent
6282    enumeration type, i.e. the name of the enumeration type is not
6283    prepended to the enumerator.
6284
6285    There are two complexities.  One is DW_AT_specification; in this
6286    case "parent" means the parent of the target of the specification,
6287    instead of the direct parent of the DIE.  The other is compilers
6288    which do not emit DW_TAG_namespace; in this case we try to guess
6289    the fully qualified name of structure types from their members'
6290    linkage names.  This must be done using the DIE's children rather
6291    than the children of any DW_AT_specification target.  We only need
6292    to do this for structures at the top level, i.e. if the target of
6293    any DW_AT_specification (if any; otherwise the DIE itself) does not
6294    have a parent.  */
6295
6296 /* Compute the scope prefix associated with PDI's parent, in
6297    compilation unit CU.  The result will be allocated on CU's
6298    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6299    field.  NULL is returned if no prefix is necessary.  */
6300 static const char *
6301 partial_die_parent_scope (struct partial_die_info *pdi,
6302                           struct dwarf2_cu *cu)
6303 {
6304   const char *grandparent_scope;
6305   struct partial_die_info *parent, *real_pdi;
6306
6307   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6308      then this means the parent of the specification DIE.  */
6309
6310   real_pdi = pdi;
6311   while (real_pdi->has_specification)
6312     real_pdi = find_partial_die (real_pdi->spec_offset,
6313                                  real_pdi->spec_is_dwz, cu);
6314
6315   parent = real_pdi->die_parent;
6316   if (parent == NULL)
6317     return NULL;
6318
6319   if (parent->scope_set)
6320     return parent->scope;
6321
6322   fixup_partial_die (parent, cu);
6323
6324   grandparent_scope = partial_die_parent_scope (parent, cu);
6325
6326   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6327      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6328      Work around this problem here.  */
6329   if (cu->language == language_cplus
6330       && parent->tag == DW_TAG_namespace
6331       && strcmp (parent->name, "::") == 0
6332       && grandparent_scope == NULL)
6333     {
6334       parent->scope = NULL;
6335       parent->scope_set = 1;
6336       return NULL;
6337     }
6338
6339   if (pdi->tag == DW_TAG_enumerator)
6340     /* Enumerators should not get the name of the enumeration as a prefix.  */
6341     parent->scope = grandparent_scope;
6342   else if (parent->tag == DW_TAG_namespace
6343       || parent->tag == DW_TAG_module
6344       || parent->tag == DW_TAG_structure_type
6345       || parent->tag == DW_TAG_class_type
6346       || parent->tag == DW_TAG_interface_type
6347       || parent->tag == DW_TAG_union_type
6348       || parent->tag == DW_TAG_enumeration_type)
6349     {
6350       if (grandparent_scope == NULL)
6351         parent->scope = parent->name;
6352       else
6353         parent->scope = typename_concat (&cu->comp_unit_obstack,
6354                                          grandparent_scope,
6355                                          parent->name, 0, cu);
6356     }
6357   else
6358     {
6359       /* FIXME drow/2004-04-01: What should we be doing with
6360          function-local names?  For partial symbols, we should probably be
6361          ignoring them.  */
6362       complaint (&symfile_complaints,
6363                  _("unhandled containing DIE tag %d for DIE at %d"),
6364                  parent->tag, pdi->offset.sect_off);
6365       parent->scope = grandparent_scope;
6366     }
6367
6368   parent->scope_set = 1;
6369   return parent->scope;
6370 }
6371
6372 /* Return the fully scoped name associated with PDI, from compilation unit
6373    CU.  The result will be allocated with malloc.  */
6374
6375 static char *
6376 partial_die_full_name (struct partial_die_info *pdi,
6377                        struct dwarf2_cu *cu)
6378 {
6379   const char *parent_scope;
6380
6381   /* If this is a template instantiation, we can not work out the
6382      template arguments from partial DIEs.  So, unfortunately, we have
6383      to go through the full DIEs.  At least any work we do building
6384      types here will be reused if full symbols are loaded later.  */
6385   if (pdi->has_template_arguments)
6386     {
6387       fixup_partial_die (pdi, cu);
6388
6389       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6390         {
6391           struct die_info *die;
6392           struct attribute attr;
6393           struct dwarf2_cu *ref_cu = cu;
6394
6395           /* DW_FORM_ref_addr is using section offset.  */
6396           attr.name = 0;
6397           attr.form = DW_FORM_ref_addr;
6398           attr.u.unsnd = pdi->offset.sect_off;
6399           die = follow_die_ref (NULL, &attr, &ref_cu);
6400
6401           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6402         }
6403     }
6404
6405   parent_scope = partial_die_parent_scope (pdi, cu);
6406   if (parent_scope == NULL)
6407     return NULL;
6408   else
6409     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6410 }
6411
6412 static void
6413 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6414 {
6415   struct objfile *objfile = cu->objfile;
6416   CORE_ADDR addr = 0;
6417   const char *actual_name = NULL;
6418   CORE_ADDR baseaddr;
6419   char *built_actual_name;
6420
6421   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6422
6423   built_actual_name = partial_die_full_name (pdi, cu);
6424   if (built_actual_name != NULL)
6425     actual_name = built_actual_name;
6426
6427   if (actual_name == NULL)
6428     actual_name = pdi->name;
6429
6430   switch (pdi->tag)
6431     {
6432     case DW_TAG_subprogram:
6433       if (pdi->is_external || cu->language == language_ada)
6434         {
6435           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6436              of the global scope.  But in Ada, we want to be able to access
6437              nested procedures globally.  So all Ada subprograms are stored
6438              in the global scope.  */
6439           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6440              mst_text, objfile); */
6441           add_psymbol_to_list (actual_name, strlen (actual_name),
6442                                built_actual_name != NULL,
6443                                VAR_DOMAIN, LOC_BLOCK,
6444                                &objfile->global_psymbols,
6445                                0, pdi->lowpc + baseaddr,
6446                                cu->language, objfile);
6447         }
6448       else
6449         {
6450           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6451              mst_file_text, objfile); */
6452           add_psymbol_to_list (actual_name, strlen (actual_name),
6453                                built_actual_name != NULL,
6454                                VAR_DOMAIN, LOC_BLOCK,
6455                                &objfile->static_psymbols,
6456                                0, pdi->lowpc + baseaddr,
6457                                cu->language, objfile);
6458         }
6459       break;
6460     case DW_TAG_constant:
6461       {
6462         struct psymbol_allocation_list *list;
6463
6464         if (pdi->is_external)
6465           list = &objfile->global_psymbols;
6466         else
6467           list = &objfile->static_psymbols;
6468         add_psymbol_to_list (actual_name, strlen (actual_name),
6469                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6470                              list, 0, 0, cu->language, objfile);
6471       }
6472       break;
6473     case DW_TAG_variable:
6474       if (pdi->d.locdesc)
6475         addr = decode_locdesc (pdi->d.locdesc, cu);
6476
6477       if (pdi->d.locdesc
6478           && addr == 0
6479           && !dwarf2_per_objfile->has_section_at_zero)
6480         {
6481           /* A global or static variable may also have been stripped
6482              out by the linker if unused, in which case its address
6483              will be nullified; do not add such variables into partial
6484              symbol table then.  */
6485         }
6486       else if (pdi->is_external)
6487         {
6488           /* Global Variable.
6489              Don't enter into the minimal symbol tables as there is
6490              a minimal symbol table entry from the ELF symbols already.
6491              Enter into partial symbol table if it has a location
6492              descriptor or a type.
6493              If the location descriptor is missing, new_symbol will create
6494              a LOC_UNRESOLVED symbol, the address of the variable will then
6495              be determined from the minimal symbol table whenever the variable
6496              is referenced.
6497              The address for the partial symbol table entry is not
6498              used by GDB, but it comes in handy for debugging partial symbol
6499              table building.  */
6500
6501           if (pdi->d.locdesc || pdi->has_type)
6502             add_psymbol_to_list (actual_name, strlen (actual_name),
6503                                  built_actual_name != NULL,
6504                                  VAR_DOMAIN, LOC_STATIC,
6505                                  &objfile->global_psymbols,
6506                                  0, addr + baseaddr,
6507                                  cu->language, objfile);
6508         }
6509       else
6510         {
6511           /* Static Variable.  Skip symbols without location descriptors.  */
6512           if (pdi->d.locdesc == NULL)
6513             {
6514               xfree (built_actual_name);
6515               return;
6516             }
6517           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6518              mst_file_data, objfile); */
6519           add_psymbol_to_list (actual_name, strlen (actual_name),
6520                                built_actual_name != NULL,
6521                                VAR_DOMAIN, LOC_STATIC,
6522                                &objfile->static_psymbols,
6523                                0, addr + baseaddr,
6524                                cu->language, objfile);
6525         }
6526       break;
6527     case DW_TAG_typedef:
6528     case DW_TAG_base_type:
6529     case DW_TAG_subrange_type:
6530       add_psymbol_to_list (actual_name, strlen (actual_name),
6531                            built_actual_name != NULL,
6532                            VAR_DOMAIN, LOC_TYPEDEF,
6533                            &objfile->static_psymbols,
6534                            0, (CORE_ADDR) 0, cu->language, objfile);
6535       break;
6536     case DW_TAG_namespace:
6537       add_psymbol_to_list (actual_name, strlen (actual_name),
6538                            built_actual_name != NULL,
6539                            VAR_DOMAIN, LOC_TYPEDEF,
6540                            &objfile->global_psymbols,
6541                            0, (CORE_ADDR) 0, cu->language, objfile);
6542       break;
6543     case DW_TAG_class_type:
6544     case DW_TAG_interface_type:
6545     case DW_TAG_structure_type:
6546     case DW_TAG_union_type:
6547     case DW_TAG_enumeration_type:
6548       /* Skip external references.  The DWARF standard says in the section
6549          about "Structure, Union, and Class Type Entries": "An incomplete
6550          structure, union or class type is represented by a structure,
6551          union or class entry that does not have a byte size attribute
6552          and that has a DW_AT_declaration attribute."  */
6553       if (!pdi->has_byte_size && pdi->is_declaration)
6554         {
6555           xfree (built_actual_name);
6556           return;
6557         }
6558
6559       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6560          static vs. global.  */
6561       add_psymbol_to_list (actual_name, strlen (actual_name),
6562                            built_actual_name != NULL,
6563                            STRUCT_DOMAIN, LOC_TYPEDEF,
6564                            (cu->language == language_cplus
6565                             || cu->language == language_java)
6566                            ? &objfile->global_psymbols
6567                            : &objfile->static_psymbols,
6568                            0, (CORE_ADDR) 0, cu->language, objfile);
6569
6570       break;
6571     case DW_TAG_enumerator:
6572       add_psymbol_to_list (actual_name, strlen (actual_name),
6573                            built_actual_name != NULL,
6574                            VAR_DOMAIN, LOC_CONST,
6575                            (cu->language == language_cplus
6576                             || cu->language == language_java)
6577                            ? &objfile->global_psymbols
6578                            : &objfile->static_psymbols,
6579                            0, (CORE_ADDR) 0, cu->language, objfile);
6580       break;
6581     default:
6582       break;
6583     }
6584
6585   xfree (built_actual_name);
6586 }
6587
6588 /* Read a partial die corresponding to a namespace; also, add a symbol
6589    corresponding to that namespace to the symbol table.  NAMESPACE is
6590    the name of the enclosing namespace.  */
6591
6592 static void
6593 add_partial_namespace (struct partial_die_info *pdi,
6594                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6595                        int need_pc, struct dwarf2_cu *cu)
6596 {
6597   /* Add a symbol for the namespace.  */
6598
6599   add_partial_symbol (pdi, cu);
6600
6601   /* Now scan partial symbols in that namespace.  */
6602
6603   if (pdi->has_children)
6604     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6605 }
6606
6607 /* Read a partial die corresponding to a Fortran module.  */
6608
6609 static void
6610 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6611                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6612 {
6613   /* Now scan partial symbols in that module.  */
6614
6615   if (pdi->has_children)
6616     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6617 }
6618
6619 /* Read a partial die corresponding to a subprogram and create a partial
6620    symbol for that subprogram.  When the CU language allows it, this
6621    routine also defines a partial symbol for each nested subprogram
6622    that this subprogram contains.
6623
6624    DIE my also be a lexical block, in which case we simply search
6625    recursively for suprograms defined inside that lexical block.
6626    Again, this is only performed when the CU language allows this
6627    type of definitions.  */
6628
6629 static void
6630 add_partial_subprogram (struct partial_die_info *pdi,
6631                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6632                         int need_pc, struct dwarf2_cu *cu)
6633 {
6634   if (pdi->tag == DW_TAG_subprogram)
6635     {
6636       if (pdi->has_pc_info)
6637         {
6638           if (pdi->lowpc < *lowpc)
6639             *lowpc = pdi->lowpc;
6640           if (pdi->highpc > *highpc)
6641             *highpc = pdi->highpc;
6642           if (need_pc)
6643             {
6644               CORE_ADDR baseaddr;
6645               struct objfile *objfile = cu->objfile;
6646
6647               baseaddr = ANOFFSET (objfile->section_offsets,
6648                                    SECT_OFF_TEXT (objfile));
6649               addrmap_set_empty (objfile->psymtabs_addrmap,
6650                                  pdi->lowpc + baseaddr,
6651                                  pdi->highpc - 1 + baseaddr,
6652                                  cu->per_cu->v.psymtab);
6653             }
6654         }
6655
6656       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6657         {
6658           if (!pdi->is_declaration)
6659             /* Ignore subprogram DIEs that do not have a name, they are
6660                illegal.  Do not emit a complaint at this point, we will
6661                do so when we convert this psymtab into a symtab.  */
6662             if (pdi->name)
6663               add_partial_symbol (pdi, cu);
6664         }
6665     }
6666
6667   if (! pdi->has_children)
6668     return;
6669
6670   if (cu->language == language_ada)
6671     {
6672       pdi = pdi->die_child;
6673       while (pdi != NULL)
6674         {
6675           fixup_partial_die (pdi, cu);
6676           if (pdi->tag == DW_TAG_subprogram
6677               || pdi->tag == DW_TAG_lexical_block)
6678             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6679           pdi = pdi->die_sibling;
6680         }
6681     }
6682 }
6683
6684 /* Read a partial die corresponding to an enumeration type.  */
6685
6686 static void
6687 add_partial_enumeration (struct partial_die_info *enum_pdi,
6688                          struct dwarf2_cu *cu)
6689 {
6690   struct partial_die_info *pdi;
6691
6692   if (enum_pdi->name != NULL)
6693     add_partial_symbol (enum_pdi, cu);
6694
6695   pdi = enum_pdi->die_child;
6696   while (pdi)
6697     {
6698       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6699         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6700       else
6701         add_partial_symbol (pdi, cu);
6702       pdi = pdi->die_sibling;
6703     }
6704 }
6705
6706 /* Return the initial uleb128 in the die at INFO_PTR.  */
6707
6708 static unsigned int
6709 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6710 {
6711   unsigned int bytes_read;
6712
6713   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6714 }
6715
6716 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6717    Return the corresponding abbrev, or NULL if the number is zero (indicating
6718    an empty DIE).  In either case *BYTES_READ will be set to the length of
6719    the initial number.  */
6720
6721 static struct abbrev_info *
6722 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6723                  struct dwarf2_cu *cu)
6724 {
6725   bfd *abfd = cu->objfile->obfd;
6726   unsigned int abbrev_number;
6727   struct abbrev_info *abbrev;
6728
6729   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6730
6731   if (abbrev_number == 0)
6732     return NULL;
6733
6734   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6735   if (!abbrev)
6736     {
6737       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6738              abbrev_number, bfd_get_filename (abfd));
6739     }
6740
6741   return abbrev;
6742 }
6743
6744 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6745    Returns a pointer to the end of a series of DIEs, terminated by an empty
6746    DIE.  Any children of the skipped DIEs will also be skipped.  */
6747
6748 static const gdb_byte *
6749 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6750 {
6751   struct dwarf2_cu *cu = reader->cu;
6752   struct abbrev_info *abbrev;
6753   unsigned int bytes_read;
6754
6755   while (1)
6756     {
6757       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6758       if (abbrev == NULL)
6759         return info_ptr + bytes_read;
6760       else
6761         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6762     }
6763 }
6764
6765 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6766    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6767    abbrev corresponding to that skipped uleb128 should be passed in
6768    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6769    children.  */
6770
6771 static const gdb_byte *
6772 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6773               struct abbrev_info *abbrev)
6774 {
6775   unsigned int bytes_read;
6776   struct attribute attr;
6777   bfd *abfd = reader->abfd;
6778   struct dwarf2_cu *cu = reader->cu;
6779   const gdb_byte *buffer = reader->buffer;
6780   const gdb_byte *buffer_end = reader->buffer_end;
6781   const gdb_byte *start_info_ptr = info_ptr;
6782   unsigned int form, i;
6783
6784   for (i = 0; i < abbrev->num_attrs; i++)
6785     {
6786       /* The only abbrev we care about is DW_AT_sibling.  */
6787       if (abbrev->attrs[i].name == DW_AT_sibling)
6788         {
6789           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6790           if (attr.form == DW_FORM_ref_addr)
6791             complaint (&symfile_complaints,
6792                        _("ignoring absolute DW_AT_sibling"));
6793           else
6794             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6795         }
6796
6797       /* If it isn't DW_AT_sibling, skip this attribute.  */
6798       form = abbrev->attrs[i].form;
6799     skip_attribute:
6800       switch (form)
6801         {
6802         case DW_FORM_ref_addr:
6803           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6804              and later it is offset sized.  */
6805           if (cu->header.version == 2)
6806             info_ptr += cu->header.addr_size;
6807           else
6808             info_ptr += cu->header.offset_size;
6809           break;
6810         case DW_FORM_GNU_ref_alt:
6811           info_ptr += cu->header.offset_size;
6812           break;
6813         case DW_FORM_addr:
6814           info_ptr += cu->header.addr_size;
6815           break;
6816         case DW_FORM_data1:
6817         case DW_FORM_ref1:
6818         case DW_FORM_flag:
6819           info_ptr += 1;
6820           break;
6821         case DW_FORM_flag_present:
6822           break;
6823         case DW_FORM_data2:
6824         case DW_FORM_ref2:
6825           info_ptr += 2;
6826           break;
6827         case DW_FORM_data4:
6828         case DW_FORM_ref4:
6829           info_ptr += 4;
6830           break;
6831         case DW_FORM_data8:
6832         case DW_FORM_ref8:
6833         case DW_FORM_ref_sig8:
6834           info_ptr += 8;
6835           break;
6836         case DW_FORM_string:
6837           read_direct_string (abfd, info_ptr, &bytes_read);
6838           info_ptr += bytes_read;
6839           break;
6840         case DW_FORM_sec_offset:
6841         case DW_FORM_strp:
6842         case DW_FORM_GNU_strp_alt:
6843           info_ptr += cu->header.offset_size;
6844           break;
6845         case DW_FORM_exprloc:
6846         case DW_FORM_block:
6847           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6848           info_ptr += bytes_read;
6849           break;
6850         case DW_FORM_block1:
6851           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6852           break;
6853         case DW_FORM_block2:
6854           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6855           break;
6856         case DW_FORM_block4:
6857           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6858           break;
6859         case DW_FORM_sdata:
6860         case DW_FORM_udata:
6861         case DW_FORM_ref_udata:
6862         case DW_FORM_GNU_addr_index:
6863         case DW_FORM_GNU_str_index:
6864           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6865           break;
6866         case DW_FORM_indirect:
6867           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6868           info_ptr += bytes_read;
6869           /* We need to continue parsing from here, so just go back to
6870              the top.  */
6871           goto skip_attribute;
6872
6873         default:
6874           error (_("Dwarf Error: Cannot handle %s "
6875                    "in DWARF reader [in module %s]"),
6876                  dwarf_form_name (form),
6877                  bfd_get_filename (abfd));
6878         }
6879     }
6880
6881   if (abbrev->has_children)
6882     return skip_children (reader, info_ptr);
6883   else
6884     return info_ptr;
6885 }
6886
6887 /* Locate ORIG_PDI's sibling.
6888    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6889
6890 static const gdb_byte *
6891 locate_pdi_sibling (const struct die_reader_specs *reader,
6892                     struct partial_die_info *orig_pdi,
6893                     const gdb_byte *info_ptr)
6894 {
6895   /* Do we know the sibling already?  */
6896
6897   if (orig_pdi->sibling)
6898     return orig_pdi->sibling;
6899
6900   /* Are there any children to deal with?  */
6901
6902   if (!orig_pdi->has_children)
6903     return info_ptr;
6904
6905   /* Skip the children the long way.  */
6906
6907   return skip_children (reader, info_ptr);
6908 }
6909
6910 /* Expand this partial symbol table into a full symbol table.  SELF is
6911    not NULL.  */
6912
6913 static void
6914 dwarf2_read_symtab (struct partial_symtab *self,
6915                     struct objfile *objfile)
6916 {
6917   if (self->readin)
6918     {
6919       warning (_("bug: psymtab for %s is already read in."),
6920                self->filename);
6921     }
6922   else
6923     {
6924       if (info_verbose)
6925         {
6926           printf_filtered (_("Reading in symbols for %s..."),
6927                            self->filename);
6928           gdb_flush (gdb_stdout);
6929         }
6930
6931       /* Restore our global data.  */
6932       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6933
6934       /* If this psymtab is constructed from a debug-only objfile, the
6935          has_section_at_zero flag will not necessarily be correct.  We
6936          can get the correct value for this flag by looking at the data
6937          associated with the (presumably stripped) associated objfile.  */
6938       if (objfile->separate_debug_objfile_backlink)
6939         {
6940           struct dwarf2_per_objfile *dpo_backlink
6941             = objfile_data (objfile->separate_debug_objfile_backlink,
6942                             dwarf2_objfile_data_key);
6943
6944           dwarf2_per_objfile->has_section_at_zero
6945             = dpo_backlink->has_section_at_zero;
6946         }
6947
6948       dwarf2_per_objfile->reading_partial_symbols = 0;
6949
6950       psymtab_to_symtab_1 (self);
6951
6952       /* Finish up the debug error message.  */
6953       if (info_verbose)
6954         printf_filtered (_("done.\n"));
6955     }
6956
6957   process_cu_includes ();
6958 }
6959 \f
6960 /* Reading in full CUs.  */
6961
6962 /* Add PER_CU to the queue.  */
6963
6964 static void
6965 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6966                  enum language pretend_language)
6967 {
6968   struct dwarf2_queue_item *item;
6969
6970   per_cu->queued = 1;
6971   item = xmalloc (sizeof (*item));
6972   item->per_cu = per_cu;
6973   item->pretend_language = pretend_language;
6974   item->next = NULL;
6975
6976   if (dwarf2_queue == NULL)
6977     dwarf2_queue = item;
6978   else
6979     dwarf2_queue_tail->next = item;
6980
6981   dwarf2_queue_tail = item;
6982 }
6983
6984 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6985    unit and add it to our queue.
6986    The result is non-zero if PER_CU was queued, otherwise the result is zero
6987    meaning either PER_CU is already queued or it is already loaded.  */
6988
6989 static int
6990 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6991                        struct dwarf2_per_cu_data *per_cu,
6992                        enum language pretend_language)
6993 {
6994   /* We may arrive here during partial symbol reading, if we need full
6995      DIEs to process an unusual case (e.g. template arguments).  Do
6996      not queue PER_CU, just tell our caller to load its DIEs.  */
6997   if (dwarf2_per_objfile->reading_partial_symbols)
6998     {
6999       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7000         return 1;
7001       return 0;
7002     }
7003
7004   /* Mark the dependence relation so that we don't flush PER_CU
7005      too early.  */
7006   dwarf2_add_dependence (this_cu, per_cu);
7007
7008   /* If it's already on the queue, we have nothing to do.  */
7009   if (per_cu->queued)
7010     return 0;
7011
7012   /* If the compilation unit is already loaded, just mark it as
7013      used.  */
7014   if (per_cu->cu != NULL)
7015     {
7016       per_cu->cu->last_used = 0;
7017       return 0;
7018     }
7019
7020   /* Add it to the queue.  */
7021   queue_comp_unit (per_cu, pretend_language);
7022
7023   return 1;
7024 }
7025
7026 /* Process the queue.  */
7027
7028 static void
7029 process_queue (void)
7030 {
7031   struct dwarf2_queue_item *item, *next_item;
7032
7033   if (dwarf2_read_debug)
7034     {
7035       fprintf_unfiltered (gdb_stdlog,
7036                           "Expanding one or more symtabs of objfile %s ...\n",
7037                           dwarf2_per_objfile->objfile->name);
7038     }
7039
7040   /* The queue starts out with one item, but following a DIE reference
7041      may load a new CU, adding it to the end of the queue.  */
7042   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7043     {
7044       if (dwarf2_per_objfile->using_index
7045           ? !item->per_cu->v.quick->symtab
7046           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7047         {
7048           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7049           char buf[100];
7050
7051           if (per_cu->is_debug_types)
7052             {
7053               struct signatured_type *sig_type =
7054                 (struct signatured_type *) per_cu;
7055
7056               sprintf (buf, "TU %s at offset 0x%x",
7057                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7058             }
7059           else
7060             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7061
7062           if (dwarf2_read_debug)
7063             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7064
7065           if (per_cu->is_debug_types)
7066             process_full_type_unit (per_cu, item->pretend_language);
7067           else
7068             process_full_comp_unit (per_cu, item->pretend_language);
7069
7070           if (dwarf2_read_debug)
7071             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7072         }
7073
7074       item->per_cu->queued = 0;
7075       next_item = item->next;
7076       xfree (item);
7077     }
7078
7079   dwarf2_queue_tail = NULL;
7080
7081   if (dwarf2_read_debug)
7082     {
7083       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7084                           dwarf2_per_objfile->objfile->name);
7085     }
7086 }
7087
7088 /* Free all allocated queue entries.  This function only releases anything if
7089    an error was thrown; if the queue was processed then it would have been
7090    freed as we went along.  */
7091
7092 static void
7093 dwarf2_release_queue (void *dummy)
7094 {
7095   struct dwarf2_queue_item *item, *last;
7096
7097   item = dwarf2_queue;
7098   while (item)
7099     {
7100       /* Anything still marked queued is likely to be in an
7101          inconsistent state, so discard it.  */
7102       if (item->per_cu->queued)
7103         {
7104           if (item->per_cu->cu != NULL)
7105             free_one_cached_comp_unit (item->per_cu);
7106           item->per_cu->queued = 0;
7107         }
7108
7109       last = item;
7110       item = item->next;
7111       xfree (last);
7112     }
7113
7114   dwarf2_queue = dwarf2_queue_tail = NULL;
7115 }
7116
7117 /* Read in full symbols for PST, and anything it depends on.  */
7118
7119 static void
7120 psymtab_to_symtab_1 (struct partial_symtab *pst)
7121 {
7122   struct dwarf2_per_cu_data *per_cu;
7123   int i;
7124
7125   if (pst->readin)
7126     return;
7127
7128   for (i = 0; i < pst->number_of_dependencies; i++)
7129     if (!pst->dependencies[i]->readin
7130         && pst->dependencies[i]->user == NULL)
7131       {
7132         /* Inform about additional files that need to be read in.  */
7133         if (info_verbose)
7134           {
7135             /* FIXME: i18n: Need to make this a single string.  */
7136             fputs_filtered (" ", gdb_stdout);
7137             wrap_here ("");
7138             fputs_filtered ("and ", gdb_stdout);
7139             wrap_here ("");
7140             printf_filtered ("%s...", pst->dependencies[i]->filename);
7141             wrap_here ("");     /* Flush output.  */
7142             gdb_flush (gdb_stdout);
7143           }
7144         psymtab_to_symtab_1 (pst->dependencies[i]);
7145       }
7146
7147   per_cu = pst->read_symtab_private;
7148
7149   if (per_cu == NULL)
7150     {
7151       /* It's an include file, no symbols to read for it.
7152          Everything is in the parent symtab.  */
7153       pst->readin = 1;
7154       return;
7155     }
7156
7157   dw2_do_instantiate_symtab (per_cu);
7158 }
7159
7160 /* Trivial hash function for die_info: the hash value of a DIE
7161    is its offset in .debug_info for this objfile.  */
7162
7163 static hashval_t
7164 die_hash (const void *item)
7165 {
7166   const struct die_info *die = item;
7167
7168   return die->offset.sect_off;
7169 }
7170
7171 /* Trivial comparison function for die_info structures: two DIEs
7172    are equal if they have the same offset.  */
7173
7174 static int
7175 die_eq (const void *item_lhs, const void *item_rhs)
7176 {
7177   const struct die_info *die_lhs = item_lhs;
7178   const struct die_info *die_rhs = item_rhs;
7179
7180   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7181 }
7182
7183 /* die_reader_func for load_full_comp_unit.
7184    This is identical to read_signatured_type_reader,
7185    but is kept separate for now.  */
7186
7187 static void
7188 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7189                             const gdb_byte *info_ptr,
7190                             struct die_info *comp_unit_die,
7191                             int has_children,
7192                             void *data)
7193 {
7194   struct dwarf2_cu *cu = reader->cu;
7195   enum language *language_ptr = data;
7196
7197   gdb_assert (cu->die_hash == NULL);
7198   cu->die_hash =
7199     htab_create_alloc_ex (cu->header.length / 12,
7200                           die_hash,
7201                           die_eq,
7202                           NULL,
7203                           &cu->comp_unit_obstack,
7204                           hashtab_obstack_allocate,
7205                           dummy_obstack_deallocate);
7206
7207   if (has_children)
7208     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7209                                                   &info_ptr, comp_unit_die);
7210   cu->dies = comp_unit_die;
7211   /* comp_unit_die is not stored in die_hash, no need.  */
7212
7213   /* We try not to read any attributes in this function, because not
7214      all CUs needed for references have been loaded yet, and symbol
7215      table processing isn't initialized.  But we have to set the CU language,
7216      or we won't be able to build types correctly.
7217      Similarly, if we do not read the producer, we can not apply
7218      producer-specific interpretation.  */
7219   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7220 }
7221
7222 /* Load the DIEs associated with PER_CU into memory.  */
7223
7224 static void
7225 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7226                      enum language pretend_language)
7227 {
7228   gdb_assert (! this_cu->is_debug_types);
7229
7230   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7231                            load_full_comp_unit_reader, &pretend_language);
7232 }
7233
7234 /* Add a DIE to the delayed physname list.  */
7235
7236 static void
7237 add_to_method_list (struct type *type, int fnfield_index, int index,
7238                     const char *name, struct die_info *die,
7239                     struct dwarf2_cu *cu)
7240 {
7241   struct delayed_method_info mi;
7242   mi.type = type;
7243   mi.fnfield_index = fnfield_index;
7244   mi.index = index;
7245   mi.name = name;
7246   mi.die = die;
7247   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7248 }
7249
7250 /* A cleanup for freeing the delayed method list.  */
7251
7252 static void
7253 free_delayed_list (void *ptr)
7254 {
7255   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7256   if (cu->method_list != NULL)
7257     {
7258       VEC_free (delayed_method_info, cu->method_list);
7259       cu->method_list = NULL;
7260     }
7261 }
7262
7263 /* Compute the physnames of any methods on the CU's method list.
7264
7265    The computation of method physnames is delayed in order to avoid the
7266    (bad) condition that one of the method's formal parameters is of an as yet
7267    incomplete type.  */
7268
7269 static void
7270 compute_delayed_physnames (struct dwarf2_cu *cu)
7271 {
7272   int i;
7273   struct delayed_method_info *mi;
7274   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7275     {
7276       const char *physname;
7277       struct fn_fieldlist *fn_flp
7278         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7279       physname = dwarf2_physname (mi->name, mi->die, cu);
7280       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7281     }
7282 }
7283
7284 /* Go objects should be embedded in a DW_TAG_module DIE,
7285    and it's not clear if/how imported objects will appear.
7286    To keep Go support simple until that's worked out,
7287    go back through what we've read and create something usable.
7288    We could do this while processing each DIE, and feels kinda cleaner,
7289    but that way is more invasive.
7290    This is to, for example, allow the user to type "p var" or "b main"
7291    without having to specify the package name, and allow lookups
7292    of module.object to work in contexts that use the expression
7293    parser.  */
7294
7295 static void
7296 fixup_go_packaging (struct dwarf2_cu *cu)
7297 {
7298   char *package_name = NULL;
7299   struct pending *list;
7300   int i;
7301
7302   for (list = global_symbols; list != NULL; list = list->next)
7303     {
7304       for (i = 0; i < list->nsyms; ++i)
7305         {
7306           struct symbol *sym = list->symbol[i];
7307
7308           if (SYMBOL_LANGUAGE (sym) == language_go
7309               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7310             {
7311               char *this_package_name = go_symbol_package_name (sym);
7312
7313               if (this_package_name == NULL)
7314                 continue;
7315               if (package_name == NULL)
7316                 package_name = this_package_name;
7317               else
7318                 {
7319                   if (strcmp (package_name, this_package_name) != 0)
7320                     complaint (&symfile_complaints,
7321                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7322                                (SYMBOL_SYMTAB (sym)
7323                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7324                                 : cu->objfile->name),
7325                                this_package_name, package_name);
7326                   xfree (this_package_name);
7327                 }
7328             }
7329         }
7330     }
7331
7332   if (package_name != NULL)
7333     {
7334       struct objfile *objfile = cu->objfile;
7335       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7336                                                       package_name,
7337                                                       strlen (package_name));
7338       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7339                                      saved_package_name, objfile);
7340       struct symbol *sym;
7341
7342       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7343
7344       sym = allocate_symbol (objfile);
7345       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7346       SYMBOL_SET_NAMES (sym, saved_package_name,
7347                         strlen (saved_package_name), 0, objfile);
7348       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7349          e.g., "main" finds the "main" module and not C's main().  */
7350       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7351       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7352       SYMBOL_TYPE (sym) = type;
7353
7354       add_symbol_to_list (sym, &global_symbols);
7355
7356       xfree (package_name);
7357     }
7358 }
7359
7360 /* Return the symtab for PER_CU.  This works properly regardless of
7361    whether we're using the index or psymtabs.  */
7362
7363 static struct symtab *
7364 get_symtab (struct dwarf2_per_cu_data *per_cu)
7365 {
7366   return (dwarf2_per_objfile->using_index
7367           ? per_cu->v.quick->symtab
7368           : per_cu->v.psymtab->symtab);
7369 }
7370
7371 /* A helper function for computing the list of all symbol tables
7372    included by PER_CU.  */
7373
7374 static void
7375 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7376                                 htab_t all_children, htab_t all_type_symtabs,
7377                                 struct dwarf2_per_cu_data *per_cu,
7378                                 struct symtab *immediate_parent)
7379 {
7380   void **slot;
7381   int ix;
7382   struct symtab *symtab;
7383   struct dwarf2_per_cu_data *iter;
7384
7385   slot = htab_find_slot (all_children, per_cu, INSERT);
7386   if (*slot != NULL)
7387     {
7388       /* This inclusion and its children have been processed.  */
7389       return;
7390     }
7391
7392   *slot = per_cu;
7393   /* Only add a CU if it has a symbol table.  */
7394   symtab = get_symtab (per_cu);
7395   if (symtab != NULL)
7396     {
7397       /* If this is a type unit only add its symbol table if we haven't
7398          seen it yet (type unit per_cu's can share symtabs).  */
7399       if (per_cu->is_debug_types)
7400         {
7401           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7402           if (*slot == NULL)
7403             {
7404               *slot = symtab;
7405               VEC_safe_push (symtab_ptr, *result, symtab);
7406               if (symtab->user == NULL)
7407                 symtab->user = immediate_parent;
7408             }
7409         }
7410       else
7411         {
7412           VEC_safe_push (symtab_ptr, *result, symtab);
7413           if (symtab->user == NULL)
7414             symtab->user = immediate_parent;
7415         }
7416     }
7417
7418   for (ix = 0;
7419        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7420        ++ix)
7421     {
7422       recursively_compute_inclusions (result, all_children,
7423                                       all_type_symtabs, iter, symtab);
7424     }
7425 }
7426
7427 /* Compute the symtab 'includes' fields for the symtab related to
7428    PER_CU.  */
7429
7430 static void
7431 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7432 {
7433   gdb_assert (! per_cu->is_debug_types);
7434
7435   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7436     {
7437       int ix, len;
7438       struct dwarf2_per_cu_data *per_cu_iter;
7439       struct symtab *symtab_iter;
7440       VEC (symtab_ptr) *result_symtabs = NULL;
7441       htab_t all_children, all_type_symtabs;
7442       struct symtab *symtab = get_symtab (per_cu);
7443
7444       /* If we don't have a symtab, we can just skip this case.  */
7445       if (symtab == NULL)
7446         return;
7447
7448       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7449                                         NULL, xcalloc, xfree);
7450       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7451                                             NULL, xcalloc, xfree);
7452
7453       for (ix = 0;
7454            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7455                         ix, per_cu_iter);
7456            ++ix)
7457         {
7458           recursively_compute_inclusions (&result_symtabs, all_children,
7459                                           all_type_symtabs, per_cu_iter,
7460                                           symtab);
7461         }
7462
7463       /* Now we have a transitive closure of all the included symtabs.  */
7464       len = VEC_length (symtab_ptr, result_symtabs);
7465       symtab->includes
7466         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7467                          (len + 1) * sizeof (struct symtab *));
7468       for (ix = 0;
7469            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7470            ++ix)
7471         symtab->includes[ix] = symtab_iter;
7472       symtab->includes[len] = NULL;
7473
7474       VEC_free (symtab_ptr, result_symtabs);
7475       htab_delete (all_children);
7476       htab_delete (all_type_symtabs);
7477     }
7478 }
7479
7480 /* Compute the 'includes' field for the symtabs of all the CUs we just
7481    read.  */
7482
7483 static void
7484 process_cu_includes (void)
7485 {
7486   int ix;
7487   struct dwarf2_per_cu_data *iter;
7488
7489   for (ix = 0;
7490        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7491                     ix, iter);
7492        ++ix)
7493     {
7494       if (! iter->is_debug_types)
7495         compute_symtab_includes (iter);
7496     }
7497
7498   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7499 }
7500
7501 /* Generate full symbol information for PER_CU, whose DIEs have
7502    already been loaded into memory.  */
7503
7504 static void
7505 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7506                         enum language pretend_language)
7507 {
7508   struct dwarf2_cu *cu = per_cu->cu;
7509   struct objfile *objfile = per_cu->objfile;
7510   CORE_ADDR lowpc, highpc;
7511   struct symtab *symtab;
7512   struct cleanup *back_to, *delayed_list_cleanup;
7513   CORE_ADDR baseaddr;
7514   struct block *static_block;
7515
7516   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7517
7518   buildsym_init ();
7519   back_to = make_cleanup (really_free_pendings, NULL);
7520   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7521
7522   cu->list_in_scope = &file_symbols;
7523
7524   cu->language = pretend_language;
7525   cu->language_defn = language_def (cu->language);
7526
7527   /* Do line number decoding in read_file_scope () */
7528   process_die (cu->dies, cu);
7529
7530   /* For now fudge the Go package.  */
7531   if (cu->language == language_go)
7532     fixup_go_packaging (cu);
7533
7534   /* Now that we have processed all the DIEs in the CU, all the types 
7535      should be complete, and it should now be safe to compute all of the
7536      physnames.  */
7537   compute_delayed_physnames (cu);
7538   do_cleanups (delayed_list_cleanup);
7539
7540   /* Some compilers don't define a DW_AT_high_pc attribute for the
7541      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7542      it, by scanning the DIE's below the compilation unit.  */
7543   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7544
7545   static_block
7546     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7547
7548   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7549      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7550      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7551      addrmap to help ensure it has an accurate map of pc values belonging to
7552      this comp unit.  */
7553   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7554
7555   symtab = end_symtab_from_static_block (static_block, objfile,
7556                                          SECT_OFF_TEXT (objfile), 0);
7557
7558   if (symtab != NULL)
7559     {
7560       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7561
7562       /* Set symtab language to language from DW_AT_language.  If the
7563          compilation is from a C file generated by language preprocessors, do
7564          not set the language if it was already deduced by start_subfile.  */
7565       if (!(cu->language == language_c && symtab->language != language_c))
7566         symtab->language = cu->language;
7567
7568       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7569          produce DW_AT_location with location lists but it can be possibly
7570          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7571          there were bugs in prologue debug info, fixed later in GCC-4.5
7572          by "unwind info for epilogues" patch (which is not directly related).
7573
7574          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7575          needed, it would be wrong due to missing DW_AT_producer there.
7576
7577          Still one can confuse GDB by using non-standard GCC compilation
7578          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7579          */ 
7580       if (cu->has_loclist && gcc_4_minor >= 5)
7581         symtab->locations_valid = 1;
7582
7583       if (gcc_4_minor >= 5)
7584         symtab->epilogue_unwind_valid = 1;
7585
7586       symtab->call_site_htab = cu->call_site_htab;
7587     }
7588
7589   if (dwarf2_per_objfile->using_index)
7590     per_cu->v.quick->symtab = symtab;
7591   else
7592     {
7593       struct partial_symtab *pst = per_cu->v.psymtab;
7594       pst->symtab = symtab;
7595       pst->readin = 1;
7596     }
7597
7598   /* Push it for inclusion processing later.  */
7599   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7600
7601   do_cleanups (back_to);
7602 }
7603
7604 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7605    already been loaded into memory.  */
7606
7607 static void
7608 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7609                         enum language pretend_language)
7610 {
7611   struct dwarf2_cu *cu = per_cu->cu;
7612   struct objfile *objfile = per_cu->objfile;
7613   struct symtab *symtab;
7614   struct cleanup *back_to, *delayed_list_cleanup;
7615   struct signatured_type *sig_type;
7616
7617   gdb_assert (per_cu->is_debug_types);
7618   sig_type = (struct signatured_type *) per_cu;
7619
7620   buildsym_init ();
7621   back_to = make_cleanup (really_free_pendings, NULL);
7622   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7623
7624   cu->list_in_scope = &file_symbols;
7625
7626   cu->language = pretend_language;
7627   cu->language_defn = language_def (cu->language);
7628
7629   /* The symbol tables are set up in read_type_unit_scope.  */
7630   process_die (cu->dies, cu);
7631
7632   /* For now fudge the Go package.  */
7633   if (cu->language == language_go)
7634     fixup_go_packaging (cu);
7635
7636   /* Now that we have processed all the DIEs in the CU, all the types 
7637      should be complete, and it should now be safe to compute all of the
7638      physnames.  */
7639   compute_delayed_physnames (cu);
7640   do_cleanups (delayed_list_cleanup);
7641
7642   /* TUs share symbol tables.
7643      If this is the first TU to use this symtab, complete the construction
7644      of it with end_expandable_symtab.  Otherwise, complete the addition of
7645      this TU's symbols to the existing symtab.  */
7646   if (sig_type->type_unit_group->primary_symtab == NULL)
7647     {
7648       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7649       sig_type->type_unit_group->primary_symtab = symtab;
7650
7651       if (symtab != NULL)
7652         {
7653           /* Set symtab language to language from DW_AT_language.  If the
7654              compilation is from a C file generated by language preprocessors,
7655              do not set the language if it was already deduced by
7656              start_subfile.  */
7657           if (!(cu->language == language_c && symtab->language != language_c))
7658             symtab->language = cu->language;
7659         }
7660     }
7661   else
7662     {
7663       augment_type_symtab (objfile,
7664                            sig_type->type_unit_group->primary_symtab);
7665       symtab = sig_type->type_unit_group->primary_symtab;
7666     }
7667
7668   if (dwarf2_per_objfile->using_index)
7669     per_cu->v.quick->symtab = symtab;
7670   else
7671     {
7672       struct partial_symtab *pst = per_cu->v.psymtab;
7673       pst->symtab = symtab;
7674       pst->readin = 1;
7675     }
7676
7677   do_cleanups (back_to);
7678 }
7679
7680 /* Process an imported unit DIE.  */
7681
7682 static void
7683 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7684 {
7685   struct attribute *attr;
7686
7687   /* For now we don't handle imported units in type units.  */
7688   if (cu->per_cu->is_debug_types)
7689     {
7690       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7691                " supported in type units [in module %s]"),
7692              cu->objfile->name);
7693     }
7694
7695   attr = dwarf2_attr (die, DW_AT_import, cu);
7696   if (attr != NULL)
7697     {
7698       struct dwarf2_per_cu_data *per_cu;
7699       struct symtab *imported_symtab;
7700       sect_offset offset;
7701       int is_dwz;
7702
7703       offset = dwarf2_get_ref_die_offset (attr);
7704       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7705       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7706
7707       /* Queue the unit, if needed.  */
7708       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7709         load_full_comp_unit (per_cu, cu->language);
7710
7711       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7712                      per_cu);
7713     }
7714 }
7715
7716 /* Process a die and its children.  */
7717
7718 static void
7719 process_die (struct die_info *die, struct dwarf2_cu *cu)
7720 {
7721   switch (die->tag)
7722     {
7723     case DW_TAG_padding:
7724       break;
7725     case DW_TAG_compile_unit:
7726     case DW_TAG_partial_unit:
7727       read_file_scope (die, cu);
7728       break;
7729     case DW_TAG_type_unit:
7730       read_type_unit_scope (die, cu);
7731       break;
7732     case DW_TAG_subprogram:
7733     case DW_TAG_inlined_subroutine:
7734       read_func_scope (die, cu);
7735       break;
7736     case DW_TAG_lexical_block:
7737     case DW_TAG_try_block:
7738     case DW_TAG_catch_block:
7739       read_lexical_block_scope (die, cu);
7740       break;
7741     case DW_TAG_GNU_call_site:
7742       read_call_site_scope (die, cu);
7743       break;
7744     case DW_TAG_class_type:
7745     case DW_TAG_interface_type:
7746     case DW_TAG_structure_type:
7747     case DW_TAG_union_type:
7748       process_structure_scope (die, cu);
7749       break;
7750     case DW_TAG_enumeration_type:
7751       process_enumeration_scope (die, cu);
7752       break;
7753
7754     /* These dies have a type, but processing them does not create
7755        a symbol or recurse to process the children.  Therefore we can
7756        read them on-demand through read_type_die.  */
7757     case DW_TAG_subroutine_type:
7758     case DW_TAG_set_type:
7759     case DW_TAG_array_type:
7760     case DW_TAG_pointer_type:
7761     case DW_TAG_ptr_to_member_type:
7762     case DW_TAG_reference_type:
7763     case DW_TAG_string_type:
7764       break;
7765
7766     case DW_TAG_base_type:
7767     case DW_TAG_subrange_type:
7768     case DW_TAG_typedef:
7769       /* Add a typedef symbol for the type definition, if it has a
7770          DW_AT_name.  */
7771       new_symbol (die, read_type_die (die, cu), cu);
7772       break;
7773     case DW_TAG_common_block:
7774       read_common_block (die, cu);
7775       break;
7776     case DW_TAG_common_inclusion:
7777       break;
7778     case DW_TAG_namespace:
7779       cu->processing_has_namespace_info = 1;
7780       read_namespace (die, cu);
7781       break;
7782     case DW_TAG_module:
7783       cu->processing_has_namespace_info = 1;
7784       read_module (die, cu);
7785       break;
7786     case DW_TAG_imported_declaration:
7787     case DW_TAG_imported_module:
7788       cu->processing_has_namespace_info = 1;
7789       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7790                                  || cu->language != language_fortran))
7791         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7792                    dwarf_tag_name (die->tag));
7793       read_import_statement (die, cu);
7794       break;
7795
7796     case DW_TAG_imported_unit:
7797       process_imported_unit_die (die, cu);
7798       break;
7799
7800     default:
7801       new_symbol (die, NULL, cu);
7802       break;
7803     }
7804 }
7805 \f
7806 /* DWARF name computation.  */
7807
7808 /* A helper function for dwarf2_compute_name which determines whether DIE
7809    needs to have the name of the scope prepended to the name listed in the
7810    die.  */
7811
7812 static int
7813 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7814 {
7815   struct attribute *attr;
7816
7817   switch (die->tag)
7818     {
7819     case DW_TAG_namespace:
7820     case DW_TAG_typedef:
7821     case DW_TAG_class_type:
7822     case DW_TAG_interface_type:
7823     case DW_TAG_structure_type:
7824     case DW_TAG_union_type:
7825     case DW_TAG_enumeration_type:
7826     case DW_TAG_enumerator:
7827     case DW_TAG_subprogram:
7828     case DW_TAG_member:
7829       return 1;
7830
7831     case DW_TAG_variable:
7832     case DW_TAG_constant:
7833       /* We only need to prefix "globally" visible variables.  These include
7834          any variable marked with DW_AT_external or any variable that
7835          lives in a namespace.  [Variables in anonymous namespaces
7836          require prefixing, but they are not DW_AT_external.]  */
7837
7838       if (dwarf2_attr (die, DW_AT_specification, cu))
7839         {
7840           struct dwarf2_cu *spec_cu = cu;
7841
7842           return die_needs_namespace (die_specification (die, &spec_cu),
7843                                       spec_cu);
7844         }
7845
7846       attr = dwarf2_attr (die, DW_AT_external, cu);
7847       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7848           && die->parent->tag != DW_TAG_module)
7849         return 0;
7850       /* A variable in a lexical block of some kind does not need a
7851          namespace, even though in C++ such variables may be external
7852          and have a mangled name.  */
7853       if (die->parent->tag ==  DW_TAG_lexical_block
7854           || die->parent->tag ==  DW_TAG_try_block
7855           || die->parent->tag ==  DW_TAG_catch_block
7856           || die->parent->tag == DW_TAG_subprogram)
7857         return 0;
7858       return 1;
7859
7860     default:
7861       return 0;
7862     }
7863 }
7864
7865 /* Retrieve the last character from a mem_file.  */
7866
7867 static void
7868 do_ui_file_peek_last (void *object, const char *buffer, long length)
7869 {
7870   char *last_char_p = (char *) object;
7871
7872   if (length > 0)
7873     *last_char_p = buffer[length - 1];
7874 }
7875
7876 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7877    compute the physname for the object, which include a method's:
7878    - formal parameters (C++/Java),
7879    - receiver type (Go),
7880    - return type (Java).
7881
7882    The term "physname" is a bit confusing.
7883    For C++, for example, it is the demangled name.
7884    For Go, for example, it's the mangled name.
7885
7886    For Ada, return the DIE's linkage name rather than the fully qualified
7887    name.  PHYSNAME is ignored..
7888
7889    The result is allocated on the objfile_obstack and canonicalized.  */
7890
7891 static const char *
7892 dwarf2_compute_name (const char *name,
7893                      struct die_info *die, struct dwarf2_cu *cu,
7894                      int physname)
7895 {
7896   struct objfile *objfile = cu->objfile;
7897
7898   if (name == NULL)
7899     name = dwarf2_name (die, cu);
7900
7901   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7902      compute it by typename_concat inside GDB.  */
7903   if (cu->language == language_ada
7904       || (cu->language == language_fortran && physname))
7905     {
7906       /* For Ada unit, we prefer the linkage name over the name, as
7907          the former contains the exported name, which the user expects
7908          to be able to reference.  Ideally, we want the user to be able
7909          to reference this entity using either natural or linkage name,
7910          but we haven't started looking at this enhancement yet.  */
7911       struct attribute *attr;
7912
7913       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7914       if (attr == NULL)
7915         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7916       if (attr && DW_STRING (attr))
7917         return DW_STRING (attr);
7918     }
7919
7920   /* These are the only languages we know how to qualify names in.  */
7921   if (name != NULL
7922       && (cu->language == language_cplus || cu->language == language_java
7923           || cu->language == language_fortran))
7924     {
7925       if (die_needs_namespace (die, cu))
7926         {
7927           long length;
7928           const char *prefix;
7929           struct ui_file *buf;
7930
7931           prefix = determine_prefix (die, cu);
7932           buf = mem_fileopen ();
7933           if (*prefix != '\0')
7934             {
7935               char *prefixed_name = typename_concat (NULL, prefix, name,
7936                                                      physname, cu);
7937
7938               fputs_unfiltered (prefixed_name, buf);
7939               xfree (prefixed_name);
7940             }
7941           else
7942             fputs_unfiltered (name, buf);
7943
7944           /* Template parameters may be specified in the DIE's DW_AT_name, or
7945              as children with DW_TAG_template_type_param or
7946              DW_TAG_value_type_param.  If the latter, add them to the name
7947              here.  If the name already has template parameters, then
7948              skip this step; some versions of GCC emit both, and
7949              it is more efficient to use the pre-computed name.
7950
7951              Something to keep in mind about this process: it is very
7952              unlikely, or in some cases downright impossible, to produce
7953              something that will match the mangled name of a function.
7954              If the definition of the function has the same debug info,
7955              we should be able to match up with it anyway.  But fallbacks
7956              using the minimal symbol, for instance to find a method
7957              implemented in a stripped copy of libstdc++, will not work.
7958              If we do not have debug info for the definition, we will have to
7959              match them up some other way.
7960
7961              When we do name matching there is a related problem with function
7962              templates; two instantiated function templates are allowed to
7963              differ only by their return types, which we do not add here.  */
7964
7965           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7966             {
7967               struct attribute *attr;
7968               struct die_info *child;
7969               int first = 1;
7970
7971               die->building_fullname = 1;
7972
7973               for (child = die->child; child != NULL; child = child->sibling)
7974                 {
7975                   struct type *type;
7976                   LONGEST value;
7977                   const gdb_byte *bytes;
7978                   struct dwarf2_locexpr_baton *baton;
7979                   struct value *v;
7980
7981                   if (child->tag != DW_TAG_template_type_param
7982                       && child->tag != DW_TAG_template_value_param)
7983                     continue;
7984
7985                   if (first)
7986                     {
7987                       fputs_unfiltered ("<", buf);
7988                       first = 0;
7989                     }
7990                   else
7991                     fputs_unfiltered (", ", buf);
7992
7993                   attr = dwarf2_attr (child, DW_AT_type, cu);
7994                   if (attr == NULL)
7995                     {
7996                       complaint (&symfile_complaints,
7997                                  _("template parameter missing DW_AT_type"));
7998                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7999                       continue;
8000                     }
8001                   type = die_type (child, cu);
8002
8003                   if (child->tag == DW_TAG_template_type_param)
8004                     {
8005                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8006                       continue;
8007                     }
8008
8009                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8010                   if (attr == NULL)
8011                     {
8012                       complaint (&symfile_complaints,
8013                                  _("template parameter missing "
8014                                    "DW_AT_const_value"));
8015                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8016                       continue;
8017                     }
8018
8019                   dwarf2_const_value_attr (attr, type, name,
8020                                            &cu->comp_unit_obstack, cu,
8021                                            &value, &bytes, &baton);
8022
8023                   if (TYPE_NOSIGN (type))
8024                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8025                        changed, this can use value_print instead.  */
8026                     c_printchar (value, type, buf);
8027                   else
8028                     {
8029                       struct value_print_options opts;
8030
8031                       if (baton != NULL)
8032                         v = dwarf2_evaluate_loc_desc (type, NULL,
8033                                                       baton->data,
8034                                                       baton->size,
8035                                                       baton->per_cu);
8036                       else if (bytes != NULL)
8037                         {
8038                           v = allocate_value (type);
8039                           memcpy (value_contents_writeable (v), bytes,
8040                                   TYPE_LENGTH (type));
8041                         }
8042                       else
8043                         v = value_from_longest (type, value);
8044
8045                       /* Specify decimal so that we do not depend on
8046                          the radix.  */
8047                       get_formatted_print_options (&opts, 'd');
8048                       opts.raw = 1;
8049                       value_print (v, buf, &opts);
8050                       release_value (v);
8051                       value_free (v);
8052                     }
8053                 }
8054
8055               die->building_fullname = 0;
8056
8057               if (!first)
8058                 {
8059                   /* Close the argument list, with a space if necessary
8060                      (nested templates).  */
8061                   char last_char = '\0';
8062                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8063                   if (last_char == '>')
8064                     fputs_unfiltered (" >", buf);
8065                   else
8066                     fputs_unfiltered (">", buf);
8067                 }
8068             }
8069
8070           /* For Java and C++ methods, append formal parameter type
8071              information, if PHYSNAME.  */
8072
8073           if (physname && die->tag == DW_TAG_subprogram
8074               && (cu->language == language_cplus
8075                   || cu->language == language_java))
8076             {
8077               struct type *type = read_type_die (die, cu);
8078
8079               c_type_print_args (type, buf, 1, cu->language,
8080                                  &type_print_raw_options);
8081
8082               if (cu->language == language_java)
8083                 {
8084                   /* For java, we must append the return type to method
8085                      names.  */
8086                   if (die->tag == DW_TAG_subprogram)
8087                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8088                                      0, 0, &type_print_raw_options);
8089                 }
8090               else if (cu->language == language_cplus)
8091                 {
8092                   /* Assume that an artificial first parameter is
8093                      "this", but do not crash if it is not.  RealView
8094                      marks unnamed (and thus unused) parameters as
8095                      artificial; there is no way to differentiate
8096                      the two cases.  */
8097                   if (TYPE_NFIELDS (type) > 0
8098                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8099                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8100                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8101                                                                         0))))
8102                     fputs_unfiltered (" const", buf);
8103                 }
8104             }
8105
8106           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8107                                        &length);
8108           ui_file_delete (buf);
8109
8110           if (cu->language == language_cplus)
8111             {
8112               const char *cname
8113                 = dwarf2_canonicalize_name (name, cu,
8114                                             &objfile->objfile_obstack);
8115
8116               if (cname != NULL)
8117                 name = cname;
8118             }
8119         }
8120     }
8121
8122   return name;
8123 }
8124
8125 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8126    If scope qualifiers are appropriate they will be added.  The result
8127    will be allocated on the objfile_obstack, or NULL if the DIE does
8128    not have a name.  NAME may either be from a previous call to
8129    dwarf2_name or NULL.
8130
8131    The output string will be canonicalized (if C++/Java).  */
8132
8133 static const char *
8134 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8135 {
8136   return dwarf2_compute_name (name, die, cu, 0);
8137 }
8138
8139 /* Construct a physname for the given DIE in CU.  NAME may either be
8140    from a previous call to dwarf2_name or NULL.  The result will be
8141    allocated on the objfile_objstack or NULL if the DIE does not have a
8142    name.
8143
8144    The output string will be canonicalized (if C++/Java).  */
8145
8146 static const char *
8147 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8148 {
8149   struct objfile *objfile = cu->objfile;
8150   struct attribute *attr;
8151   const char *retval, *mangled = NULL, *canon = NULL;
8152   struct cleanup *back_to;
8153   int need_copy = 1;
8154
8155   /* In this case dwarf2_compute_name is just a shortcut not building anything
8156      on its own.  */
8157   if (!die_needs_namespace (die, cu))
8158     return dwarf2_compute_name (name, die, cu, 1);
8159
8160   back_to = make_cleanup (null_cleanup, NULL);
8161
8162   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8163   if (!attr)
8164     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8165
8166   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8167      has computed.  */
8168   if (attr && DW_STRING (attr))
8169     {
8170       char *demangled;
8171
8172       mangled = DW_STRING (attr);
8173
8174       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8175          type.  It is easier for GDB users to search for such functions as
8176          `name(params)' than `long name(params)'.  In such case the minimal
8177          symbol names do not match the full symbol names but for template
8178          functions there is never a need to look up their definition from their
8179          declaration so the only disadvantage remains the minimal symbol
8180          variant `long name(params)' does not have the proper inferior type.
8181          */
8182
8183       if (cu->language == language_go)
8184         {
8185           /* This is a lie, but we already lie to the caller new_symbol_full.
8186              new_symbol_full assumes we return the mangled name.
8187              This just undoes that lie until things are cleaned up.  */
8188           demangled = NULL;
8189         }
8190       else
8191         {
8192           demangled = gdb_demangle (mangled,
8193                                     (DMGL_PARAMS | DMGL_ANSI
8194                                      | (cu->language == language_java
8195                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8196                                         : DMGL_RET_DROP)));
8197         }
8198       if (demangled)
8199         {
8200           make_cleanup (xfree, demangled);
8201           canon = demangled;
8202         }
8203       else
8204         {
8205           canon = mangled;
8206           need_copy = 0;
8207         }
8208     }
8209
8210   if (canon == NULL || check_physname)
8211     {
8212       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8213
8214       if (canon != NULL && strcmp (physname, canon) != 0)
8215         {
8216           /* It may not mean a bug in GDB.  The compiler could also
8217              compute DW_AT_linkage_name incorrectly.  But in such case
8218              GDB would need to be bug-to-bug compatible.  */
8219
8220           complaint (&symfile_complaints,
8221                      _("Computed physname <%s> does not match demangled <%s> "
8222                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8223                      physname, canon, mangled, die->offset.sect_off, objfile->name);
8224
8225           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8226              is available here - over computed PHYSNAME.  It is safer
8227              against both buggy GDB and buggy compilers.  */
8228
8229           retval = canon;
8230         }
8231       else
8232         {
8233           retval = physname;
8234           need_copy = 0;
8235         }
8236     }
8237   else
8238     retval = canon;
8239
8240   if (need_copy)
8241     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8242
8243   do_cleanups (back_to);
8244   return retval;
8245 }
8246
8247 /* Read the import statement specified by the given die and record it.  */
8248
8249 static void
8250 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8251 {
8252   struct objfile *objfile = cu->objfile;
8253   struct attribute *import_attr;
8254   struct die_info *imported_die, *child_die;
8255   struct dwarf2_cu *imported_cu;
8256   const char *imported_name;
8257   const char *imported_name_prefix;
8258   const char *canonical_name;
8259   const char *import_alias;
8260   const char *imported_declaration = NULL;
8261   const char *import_prefix;
8262   VEC (const_char_ptr) *excludes = NULL;
8263   struct cleanup *cleanups;
8264
8265   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8266   if (import_attr == NULL)
8267     {
8268       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8269                  dwarf_tag_name (die->tag));
8270       return;
8271     }
8272
8273   imported_cu = cu;
8274   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8275   imported_name = dwarf2_name (imported_die, imported_cu);
8276   if (imported_name == NULL)
8277     {
8278       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8279
8280         The import in the following code:
8281         namespace A
8282           {
8283             typedef int B;
8284           }
8285
8286         int main ()
8287           {
8288             using A::B;
8289             B b;
8290             return b;
8291           }
8292
8293         ...
8294          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8295             <52>   DW_AT_decl_file   : 1
8296             <53>   DW_AT_decl_line   : 6
8297             <54>   DW_AT_import      : <0x75>
8298          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8299             <59>   DW_AT_name        : B
8300             <5b>   DW_AT_decl_file   : 1
8301             <5c>   DW_AT_decl_line   : 2
8302             <5d>   DW_AT_type        : <0x6e>
8303         ...
8304          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8305             <76>   DW_AT_byte_size   : 4
8306             <77>   DW_AT_encoding    : 5        (signed)
8307
8308         imports the wrong die ( 0x75 instead of 0x58 ).
8309         This case will be ignored until the gcc bug is fixed.  */
8310       return;
8311     }
8312
8313   /* Figure out the local name after import.  */
8314   import_alias = dwarf2_name (die, cu);
8315
8316   /* Figure out where the statement is being imported to.  */
8317   import_prefix = determine_prefix (die, cu);
8318
8319   /* Figure out what the scope of the imported die is and prepend it
8320      to the name of the imported die.  */
8321   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8322
8323   if (imported_die->tag != DW_TAG_namespace
8324       && imported_die->tag != DW_TAG_module)
8325     {
8326       imported_declaration = imported_name;
8327       canonical_name = imported_name_prefix;
8328     }
8329   else if (strlen (imported_name_prefix) > 0)
8330     canonical_name = obconcat (&objfile->objfile_obstack,
8331                                imported_name_prefix, "::", imported_name,
8332                                (char *) NULL);
8333   else
8334     canonical_name = imported_name;
8335
8336   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8337
8338   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8339     for (child_die = die->child; child_die && child_die->tag;
8340          child_die = sibling_die (child_die))
8341       {
8342         /* DWARF-4: A Fortran use statement with a “rename list” may be
8343            represented by an imported module entry with an import attribute
8344            referring to the module and owned entries corresponding to those
8345            entities that are renamed as part of being imported.  */
8346
8347         if (child_die->tag != DW_TAG_imported_declaration)
8348           {
8349             complaint (&symfile_complaints,
8350                        _("child DW_TAG_imported_declaration expected "
8351                          "- DIE at 0x%x [in module %s]"),
8352                        child_die->offset.sect_off, objfile->name);
8353             continue;
8354           }
8355
8356         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8357         if (import_attr == NULL)
8358           {
8359             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8360                        dwarf_tag_name (child_die->tag));
8361             continue;
8362           }
8363
8364         imported_cu = cu;
8365         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8366                                               &imported_cu);
8367         imported_name = dwarf2_name (imported_die, imported_cu);
8368         if (imported_name == NULL)
8369           {
8370             complaint (&symfile_complaints,
8371                        _("child DW_TAG_imported_declaration has unknown "
8372                          "imported name - DIE at 0x%x [in module %s]"),
8373                        child_die->offset.sect_off, objfile->name);
8374             continue;
8375           }
8376
8377         VEC_safe_push (const_char_ptr, excludes, imported_name);
8378
8379         process_die (child_die, cu);
8380       }
8381
8382   cp_add_using_directive (import_prefix,
8383                           canonical_name,
8384                           import_alias,
8385                           imported_declaration,
8386                           excludes,
8387                           0,
8388                           &objfile->objfile_obstack);
8389
8390   do_cleanups (cleanups);
8391 }
8392
8393 /* Cleanup function for handle_DW_AT_stmt_list.  */
8394
8395 static void
8396 free_cu_line_header (void *arg)
8397 {
8398   struct dwarf2_cu *cu = arg;
8399
8400   free_line_header (cu->line_header);
8401   cu->line_header = NULL;
8402 }
8403
8404 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8405    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8406    this, it was first present in GCC release 4.3.0.  */
8407
8408 static int
8409 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8410 {
8411   if (!cu->checked_producer)
8412     check_producer (cu);
8413
8414   return cu->producer_is_gcc_lt_4_3;
8415 }
8416
8417 static void
8418 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8419                          const char **name, const char **comp_dir)
8420 {
8421   struct attribute *attr;
8422
8423   *name = NULL;
8424   *comp_dir = NULL;
8425
8426   /* Find the filename.  Do not use dwarf2_name here, since the filename
8427      is not a source language identifier.  */
8428   attr = dwarf2_attr (die, DW_AT_name, cu);
8429   if (attr)
8430     {
8431       *name = DW_STRING (attr);
8432     }
8433
8434   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8435   if (attr)
8436     *comp_dir = DW_STRING (attr);
8437   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8438            && IS_ABSOLUTE_PATH (*name))
8439     {
8440       char *d = ldirname (*name);
8441
8442       *comp_dir = d;
8443       if (d != NULL)
8444         make_cleanup (xfree, d);
8445     }
8446   if (*comp_dir != NULL)
8447     {
8448       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8449          directory, get rid of it.  */
8450       char *cp = strchr (*comp_dir, ':');
8451
8452       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8453         *comp_dir = cp + 1;
8454     }
8455
8456   if (*name == NULL)
8457     *name = "<unknown>";
8458 }
8459
8460 /* Handle DW_AT_stmt_list for a compilation unit.
8461    DIE is the DW_TAG_compile_unit die for CU.
8462    COMP_DIR is the compilation directory.
8463    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8464
8465 static void
8466 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8467                         const char *comp_dir) /* ARI: editCase function */
8468 {
8469   struct attribute *attr;
8470
8471   gdb_assert (! cu->per_cu->is_debug_types);
8472
8473   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8474   if (attr)
8475     {
8476       unsigned int line_offset = DW_UNSND (attr);
8477       struct line_header *line_header
8478         = dwarf_decode_line_header (line_offset, cu);
8479
8480       if (line_header)
8481         {
8482           cu->line_header = line_header;
8483           make_cleanup (free_cu_line_header, cu);
8484           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8485         }
8486     }
8487 }
8488
8489 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8490
8491 static void
8492 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8493 {
8494   struct objfile *objfile = dwarf2_per_objfile->objfile;
8495   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8496   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8497   CORE_ADDR highpc = ((CORE_ADDR) 0);
8498   struct attribute *attr;
8499   const char *name = NULL;
8500   const char *comp_dir = NULL;
8501   struct die_info *child_die;
8502   bfd *abfd = objfile->obfd;
8503   CORE_ADDR baseaddr;
8504
8505   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8506
8507   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8508
8509   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8510      from finish_block.  */
8511   if (lowpc == ((CORE_ADDR) -1))
8512     lowpc = highpc;
8513   lowpc += baseaddr;
8514   highpc += baseaddr;
8515
8516   find_file_and_directory (die, cu, &name, &comp_dir);
8517
8518   prepare_one_comp_unit (cu, die, cu->language);
8519
8520   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8521      standardised yet.  As a workaround for the language detection we fall
8522      back to the DW_AT_producer string.  */
8523   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8524     cu->language = language_opencl;
8525
8526   /* Similar hack for Go.  */
8527   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8528     set_cu_language (DW_LANG_Go, cu);
8529
8530   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8531
8532   /* Decode line number information if present.  We do this before
8533      processing child DIEs, so that the line header table is available
8534      for DW_AT_decl_file.  */
8535   handle_DW_AT_stmt_list (die, cu, comp_dir);
8536
8537   /* Process all dies in compilation unit.  */
8538   if (die->child != NULL)
8539     {
8540       child_die = die->child;
8541       while (child_die && child_die->tag)
8542         {
8543           process_die (child_die, cu);
8544           child_die = sibling_die (child_die);
8545         }
8546     }
8547
8548   /* Decode macro information, if present.  Dwarf 2 macro information
8549      refers to information in the line number info statement program
8550      header, so we can only read it if we've read the header
8551      successfully.  */
8552   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8553   if (attr && cu->line_header)
8554     {
8555       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8556         complaint (&symfile_complaints,
8557                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8558
8559       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8560     }
8561   else
8562     {
8563       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8564       if (attr && cu->line_header)
8565         {
8566           unsigned int macro_offset = DW_UNSND (attr);
8567
8568           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8569         }
8570     }
8571
8572   do_cleanups (back_to);
8573 }
8574
8575 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8576    Create the set of symtabs used by this TU, or if this TU is sharing
8577    symtabs with another TU and the symtabs have already been created
8578    then restore those symtabs in the line header.
8579    We don't need the pc/line-number mapping for type units.  */
8580
8581 static void
8582 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8583 {
8584   struct objfile *objfile = dwarf2_per_objfile->objfile;
8585   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8586   struct type_unit_group *tu_group;
8587   int first_time;
8588   struct line_header *lh;
8589   struct attribute *attr;
8590   unsigned int i, line_offset;
8591   struct signatured_type *sig_type;
8592
8593   gdb_assert (per_cu->is_debug_types);
8594   sig_type = (struct signatured_type *) per_cu;
8595
8596   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8597
8598   /* If we're using .gdb_index (includes -readnow) then
8599      per_cu->type_unit_group may not have been set up yet.  */
8600   if (sig_type->type_unit_group == NULL)
8601     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8602   tu_group = sig_type->type_unit_group;
8603
8604   /* If we've already processed this stmt_list there's no real need to
8605      do it again, we could fake it and just recreate the part we need
8606      (file name,index -> symtab mapping).  If data shows this optimization
8607      is useful we can do it then.  */
8608   first_time = tu_group->primary_symtab == NULL;
8609
8610   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8611      debug info.  */
8612   lh = NULL;
8613   if (attr != NULL)
8614     {
8615       line_offset = DW_UNSND (attr);
8616       lh = dwarf_decode_line_header (line_offset, cu);
8617     }
8618   if (lh == NULL)
8619     {
8620       if (first_time)
8621         dwarf2_start_symtab (cu, "", NULL, 0);
8622       else
8623         {
8624           gdb_assert (tu_group->symtabs == NULL);
8625           restart_symtab (0);
8626         }
8627       /* Note: The primary symtab will get allocated at the end.  */
8628       return;
8629     }
8630
8631   cu->line_header = lh;
8632   make_cleanup (free_cu_line_header, cu);
8633
8634   if (first_time)
8635     {
8636       dwarf2_start_symtab (cu, "", NULL, 0);
8637
8638       tu_group->num_symtabs = lh->num_file_names;
8639       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8640
8641       for (i = 0; i < lh->num_file_names; ++i)
8642         {
8643           const char *dir = NULL;
8644           struct file_entry *fe = &lh->file_names[i];
8645
8646           if (fe->dir_index)
8647             dir = lh->include_dirs[fe->dir_index - 1];
8648           dwarf2_start_subfile (fe->name, dir, NULL);
8649
8650           /* Note: We don't have to watch for the main subfile here, type units
8651              don't have DW_AT_name.  */
8652
8653           if (current_subfile->symtab == NULL)
8654             {
8655               /* NOTE: start_subfile will recognize when it's been passed
8656                  a file it has already seen.  So we can't assume there's a
8657                  simple mapping from lh->file_names to subfiles,
8658                  lh->file_names may contain dups.  */
8659               current_subfile->symtab = allocate_symtab (current_subfile->name,
8660                                                          objfile);
8661             }
8662
8663           fe->symtab = current_subfile->symtab;
8664           tu_group->symtabs[i] = fe->symtab;
8665         }
8666     }
8667   else
8668     {
8669       restart_symtab (0);
8670
8671       for (i = 0; i < lh->num_file_names; ++i)
8672         {
8673           struct file_entry *fe = &lh->file_names[i];
8674
8675           fe->symtab = tu_group->symtabs[i];
8676         }
8677     }
8678
8679   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8680      so they don't have a "real" (so to speak) symtab anyway.
8681      There is later code that will assign the main symtab to all symbols
8682      that don't have one.  We need to handle the case of a symbol with a
8683      missing symtab (DW_AT_decl_file) anyway.  */
8684 }
8685
8686 /* Process DW_TAG_type_unit.
8687    For TUs we want to skip the first top level sibling if it's not the
8688    actual type being defined by this TU.  In this case the first top
8689    level sibling is there to provide context only.  */
8690
8691 static void
8692 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8693 {
8694   struct die_info *child_die;
8695
8696   prepare_one_comp_unit (cu, die, language_minimal);
8697
8698   /* Initialize (or reinitialize) the machinery for building symtabs.
8699      We do this before processing child DIEs, so that the line header table
8700      is available for DW_AT_decl_file.  */
8701   setup_type_unit_groups (die, cu);
8702
8703   if (die->child != NULL)
8704     {
8705       child_die = die->child;
8706       while (child_die && child_die->tag)
8707         {
8708           process_die (child_die, cu);
8709           child_die = sibling_die (child_die);
8710         }
8711     }
8712 }
8713 \f
8714 /* DWO/DWP files.
8715
8716    http://gcc.gnu.org/wiki/DebugFission
8717    http://gcc.gnu.org/wiki/DebugFissionDWP
8718
8719    To simplify handling of both DWO files ("object" files with the DWARF info)
8720    and DWP files (a file with the DWOs packaged up into one file), we treat
8721    DWP files as having a collection of virtual DWO files.  */
8722
8723 static hashval_t
8724 hash_dwo_file (const void *item)
8725 {
8726   const struct dwo_file *dwo_file = item;
8727   hashval_t hash;
8728
8729   hash = htab_hash_string (dwo_file->dwo_name);
8730   if (dwo_file->comp_dir != NULL)
8731     hash += htab_hash_string (dwo_file->comp_dir);
8732   return hash;
8733 }
8734
8735 static int
8736 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8737 {
8738   const struct dwo_file *lhs = item_lhs;
8739   const struct dwo_file *rhs = item_rhs;
8740
8741   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8742     return 0;
8743   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8744     return lhs->comp_dir == rhs->comp_dir;
8745   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8746 }
8747
8748 /* Allocate a hash table for DWO files.  */
8749
8750 static htab_t
8751 allocate_dwo_file_hash_table (void)
8752 {
8753   struct objfile *objfile = dwarf2_per_objfile->objfile;
8754
8755   return htab_create_alloc_ex (41,
8756                                hash_dwo_file,
8757                                eq_dwo_file,
8758                                NULL,
8759                                &objfile->objfile_obstack,
8760                                hashtab_obstack_allocate,
8761                                dummy_obstack_deallocate);
8762 }
8763
8764 /* Lookup DWO file DWO_NAME.  */
8765
8766 static void **
8767 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8768 {
8769   struct dwo_file find_entry;
8770   void **slot;
8771
8772   if (dwarf2_per_objfile->dwo_files == NULL)
8773     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8774
8775   memset (&find_entry, 0, sizeof (find_entry));
8776   find_entry.dwo_name = dwo_name;
8777   find_entry.comp_dir = comp_dir;
8778   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8779
8780   return slot;
8781 }
8782
8783 static hashval_t
8784 hash_dwo_unit (const void *item)
8785 {
8786   const struct dwo_unit *dwo_unit = item;
8787
8788   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8789   return dwo_unit->signature;
8790 }
8791
8792 static int
8793 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8794 {
8795   const struct dwo_unit *lhs = item_lhs;
8796   const struct dwo_unit *rhs = item_rhs;
8797
8798   /* The signature is assumed to be unique within the DWO file.
8799      So while object file CU dwo_id's always have the value zero,
8800      that's OK, assuming each object file DWO file has only one CU,
8801      and that's the rule for now.  */
8802   return lhs->signature == rhs->signature;
8803 }
8804
8805 /* Allocate a hash table for DWO CUs,TUs.
8806    There is one of these tables for each of CUs,TUs for each DWO file.  */
8807
8808 static htab_t
8809 allocate_dwo_unit_table (struct objfile *objfile)
8810 {
8811   /* Start out with a pretty small number.
8812      Generally DWO files contain only one CU and maybe some TUs.  */
8813   return htab_create_alloc_ex (3,
8814                                hash_dwo_unit,
8815                                eq_dwo_unit,
8816                                NULL,
8817                                &objfile->objfile_obstack,
8818                                hashtab_obstack_allocate,
8819                                dummy_obstack_deallocate);
8820 }
8821
8822 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8823
8824 struct create_dwo_cu_data
8825 {
8826   struct dwo_file *dwo_file;
8827   struct dwo_unit dwo_unit;
8828 };
8829
8830 /* die_reader_func for create_dwo_cu.  */
8831
8832 static void
8833 create_dwo_cu_reader (const struct die_reader_specs *reader,
8834                       const gdb_byte *info_ptr,
8835                       struct die_info *comp_unit_die,
8836                       int has_children,
8837                       void *datap)
8838 {
8839   struct dwarf2_cu *cu = reader->cu;
8840   struct objfile *objfile = dwarf2_per_objfile->objfile;
8841   sect_offset offset = cu->per_cu->offset;
8842   struct dwarf2_section_info *section = cu->per_cu->section;
8843   struct create_dwo_cu_data *data = datap;
8844   struct dwo_file *dwo_file = data->dwo_file;
8845   struct dwo_unit *dwo_unit = &data->dwo_unit;
8846   struct attribute *attr;
8847
8848   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8849   if (attr == NULL)
8850     {
8851       complaint (&symfile_complaints,
8852                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8853                    " its dwo_id [in module %s]"),
8854                  offset.sect_off, dwo_file->dwo_name);
8855       return;
8856     }
8857
8858   dwo_unit->dwo_file = dwo_file;
8859   dwo_unit->signature = DW_UNSND (attr);
8860   dwo_unit->section = section;
8861   dwo_unit->offset = offset;
8862   dwo_unit->length = cu->per_cu->length;
8863
8864   if (dwarf2_read_debug)
8865     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8866                         offset.sect_off, hex_string (dwo_unit->signature));
8867 }
8868
8869 /* Create the dwo_unit for the lone CU in DWO_FILE.
8870    Note: This function processes DWO files only, not DWP files.  */
8871
8872 static struct dwo_unit *
8873 create_dwo_cu (struct dwo_file *dwo_file)
8874 {
8875   struct objfile *objfile = dwarf2_per_objfile->objfile;
8876   struct dwarf2_section_info *section = &dwo_file->sections.info;
8877   bfd *abfd;
8878   htab_t cu_htab;
8879   const gdb_byte *info_ptr, *end_ptr;
8880   struct create_dwo_cu_data create_dwo_cu_data;
8881   struct dwo_unit *dwo_unit;
8882
8883   dwarf2_read_section (objfile, section);
8884   info_ptr = section->buffer;
8885
8886   if (info_ptr == NULL)
8887     return NULL;
8888
8889   /* We can't set abfd until now because the section may be empty or
8890      not present, in which case section->asection will be NULL.  */
8891   abfd = section->asection->owner;
8892
8893   if (dwarf2_read_debug)
8894     {
8895       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8896                           bfd_section_name (abfd, section->asection),
8897                           bfd_get_filename (abfd));
8898     }
8899
8900   create_dwo_cu_data.dwo_file = dwo_file;
8901   dwo_unit = NULL;
8902
8903   end_ptr = info_ptr + section->size;
8904   while (info_ptr < end_ptr)
8905     {
8906       struct dwarf2_per_cu_data per_cu;
8907
8908       memset (&create_dwo_cu_data.dwo_unit, 0,
8909               sizeof (create_dwo_cu_data.dwo_unit));
8910       memset (&per_cu, 0, sizeof (per_cu));
8911       per_cu.objfile = objfile;
8912       per_cu.is_debug_types = 0;
8913       per_cu.offset.sect_off = info_ptr - section->buffer;
8914       per_cu.section = section;
8915
8916       init_cutu_and_read_dies_no_follow (&per_cu,
8917                                          &dwo_file->sections.abbrev,
8918                                          dwo_file,
8919                                          create_dwo_cu_reader,
8920                                          &create_dwo_cu_data);
8921
8922       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8923         {
8924           /* If we've already found one, complain.  We only support one
8925              because having more than one requires hacking the dwo_name of
8926              each to match, which is highly unlikely to happen.  */
8927           if (dwo_unit != NULL)
8928             {
8929               complaint (&symfile_complaints,
8930                          _("Multiple CUs in DWO file %s [in module %s]"),
8931                          dwo_file->dwo_name, objfile->name);
8932               break;
8933             }
8934
8935           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8936           *dwo_unit = create_dwo_cu_data.dwo_unit;
8937         }
8938
8939       info_ptr += per_cu.length;
8940     }
8941
8942   return dwo_unit;
8943 }
8944
8945 /* DWP file .debug_{cu,tu}_index section format:
8946    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8947
8948    DWP Version 1:
8949
8950    Both index sections have the same format, and serve to map a 64-bit
8951    signature to a set of section numbers.  Each section begins with a header,
8952    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8953    indexes, and a pool of 32-bit section numbers.  The index sections will be
8954    aligned at 8-byte boundaries in the file.
8955
8956    The index section header consists of:
8957
8958     V, 32 bit version number
8959     -, 32 bits unused
8960     N, 32 bit number of compilation units or type units in the index
8961     M, 32 bit number of slots in the hash table
8962
8963    Numbers are recorded using the byte order of the application binary.
8964
8965    We assume that N and M will not exceed 2^32 - 1.
8966
8967    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8968
8969    The hash table begins at offset 16 in the section, and consists of an array
8970    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8971    order of the application binary).  Unused slots in the hash table are 0.
8972    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8973
8974    The parallel table begins immediately after the hash table
8975    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8976    array of 32-bit indexes (using the byte order of the application binary),
8977    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8978    table contains a 32-bit index into the pool of section numbers.  For unused
8979    hash table slots, the corresponding entry in the parallel table will be 0.
8980
8981    Given a 64-bit compilation unit signature or a type signature S, an entry
8982    in the hash table is located as follows:
8983
8984    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8985       the low-order k bits all set to 1.
8986
8987    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8988
8989    3) If the hash table entry at index H matches the signature, use that
8990       entry.  If the hash table entry at index H is unused (all zeroes),
8991       terminate the search: the signature is not present in the table.
8992
8993    4) Let H = (H + H') modulo M. Repeat at Step 3.
8994
8995    Because M > N and H' and M are relatively prime, the search is guaranteed
8996    to stop at an unused slot or find the match.
8997
8998    The pool of section numbers begins immediately following the hash table
8999    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9000    section numbers consists of an array of 32-bit words (using the byte order
9001    of the application binary).  Each item in the array is indexed starting
9002    from 0.  The hash table entry provides the index of the first section
9003    number in the set.  Additional section numbers in the set follow, and the
9004    set is terminated by a 0 entry (section number 0 is not used in ELF).
9005
9006    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9007    section must be the first entry in the set, and the .debug_abbrev.dwo must
9008    be the second entry. Other members of the set may follow in any order.  */
9009
9010 /* Create a hash table to map DWO IDs to their CU/TU entry in
9011    .debug_{info,types}.dwo in DWP_FILE.
9012    Returns NULL if there isn't one.
9013    Note: This function processes DWP files only, not DWO files.  */
9014
9015 static struct dwp_hash_table *
9016 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9017 {
9018   struct objfile *objfile = dwarf2_per_objfile->objfile;
9019   bfd *dbfd = dwp_file->dbfd;
9020   const gdb_byte *index_ptr, *index_end;
9021   struct dwarf2_section_info *index;
9022   uint32_t version, nr_units, nr_slots;
9023   struct dwp_hash_table *htab;
9024
9025   if (is_debug_types)
9026     index = &dwp_file->sections.tu_index;
9027   else
9028     index = &dwp_file->sections.cu_index;
9029
9030   if (dwarf2_section_empty_p (index))
9031     return NULL;
9032   dwarf2_read_section (objfile, index);
9033
9034   index_ptr = index->buffer;
9035   index_end = index_ptr + index->size;
9036
9037   version = read_4_bytes (dbfd, index_ptr);
9038   index_ptr += 8; /* Skip the unused word.  */
9039   nr_units = read_4_bytes (dbfd, index_ptr);
9040   index_ptr += 4;
9041   nr_slots = read_4_bytes (dbfd, index_ptr);
9042   index_ptr += 4;
9043
9044   if (version != 1)
9045     {
9046       error (_("Dwarf Error: unsupported DWP file version (%s)"
9047                " [in module %s]"),
9048              pulongest (version), dwp_file->name);
9049     }
9050   if (nr_slots != (nr_slots & -nr_slots))
9051     {
9052       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9053                " is not power of 2 [in module %s]"),
9054              pulongest (nr_slots), dwp_file->name);
9055     }
9056
9057   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9058   htab->nr_units = nr_units;
9059   htab->nr_slots = nr_slots;
9060   htab->hash_table = index_ptr;
9061   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9062   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9063
9064   return htab;
9065 }
9066
9067 /* Update SECTIONS with the data from SECTP.
9068
9069    This function is like the other "locate" section routines that are
9070    passed to bfd_map_over_sections, but in this context the sections to
9071    read comes from the DWP hash table, not the full ELF section table.
9072
9073    The result is non-zero for success, or zero if an error was found.  */
9074
9075 static int
9076 locate_virtual_dwo_sections (asection *sectp,
9077                              struct virtual_dwo_sections *sections)
9078 {
9079   const struct dwop_section_names *names = &dwop_section_names;
9080
9081   if (section_is_p (sectp->name, &names->abbrev_dwo))
9082     {
9083       /* There can be only one.  */
9084       if (sections->abbrev.asection != NULL)
9085         return 0;
9086       sections->abbrev.asection = sectp;
9087       sections->abbrev.size = bfd_get_section_size (sectp);
9088     }
9089   else if (section_is_p (sectp->name, &names->info_dwo)
9090            || section_is_p (sectp->name, &names->types_dwo))
9091     {
9092       /* There can be only one.  */
9093       if (sections->info_or_types.asection != NULL)
9094         return 0;
9095       sections->info_or_types.asection = sectp;
9096       sections->info_or_types.size = bfd_get_section_size (sectp);
9097     }
9098   else if (section_is_p (sectp->name, &names->line_dwo))
9099     {
9100       /* There can be only one.  */
9101       if (sections->line.asection != NULL)
9102         return 0;
9103       sections->line.asection = sectp;
9104       sections->line.size = bfd_get_section_size (sectp);
9105     }
9106   else if (section_is_p (sectp->name, &names->loc_dwo))
9107     {
9108       /* There can be only one.  */
9109       if (sections->loc.asection != NULL)
9110         return 0;
9111       sections->loc.asection = sectp;
9112       sections->loc.size = bfd_get_section_size (sectp);
9113     }
9114   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9115     {
9116       /* There can be only one.  */
9117       if (sections->macinfo.asection != NULL)
9118         return 0;
9119       sections->macinfo.asection = sectp;
9120       sections->macinfo.size = bfd_get_section_size (sectp);
9121     }
9122   else if (section_is_p (sectp->name, &names->macro_dwo))
9123     {
9124       /* There can be only one.  */
9125       if (sections->macro.asection != NULL)
9126         return 0;
9127       sections->macro.asection = sectp;
9128       sections->macro.size = bfd_get_section_size (sectp);
9129     }
9130   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9131     {
9132       /* There can be only one.  */
9133       if (sections->str_offsets.asection != NULL)
9134         return 0;
9135       sections->str_offsets.asection = sectp;
9136       sections->str_offsets.size = bfd_get_section_size (sectp);
9137     }
9138   else
9139     {
9140       /* No other kind of section is valid.  */
9141       return 0;
9142     }
9143
9144   return 1;
9145 }
9146
9147 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9148    HTAB is the hash table from the DWP file.
9149    SECTION_INDEX is the index of the DWO in HTAB.
9150    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9151
9152 static struct dwo_unit *
9153 create_dwo_in_dwp (struct dwp_file *dwp_file,
9154                    const struct dwp_hash_table *htab,
9155                    uint32_t section_index,
9156                    const char *comp_dir,
9157                    ULONGEST signature, int is_debug_types)
9158 {
9159   struct objfile *objfile = dwarf2_per_objfile->objfile;
9160   bfd *dbfd = dwp_file->dbfd;
9161   const char *kind = is_debug_types ? "TU" : "CU";
9162   struct dwo_file *dwo_file;
9163   struct dwo_unit *dwo_unit;
9164   struct virtual_dwo_sections sections;
9165   void **dwo_file_slot;
9166   char *virtual_dwo_name;
9167   struct dwarf2_section_info *cutu;
9168   struct cleanup *cleanups;
9169   int i;
9170
9171   if (dwarf2_read_debug)
9172     {
9173       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9174                           kind,
9175                           pulongest (section_index), hex_string (signature),
9176                           dwp_file->name);
9177     }
9178
9179   /* Fetch the sections of this DWO.
9180      Put a limit on the number of sections we look for so that bad data
9181      doesn't cause us to loop forever.  */
9182
9183 #define MAX_NR_DWO_SECTIONS \
9184   (1 /* .debug_info or .debug_types */ \
9185    + 1 /* .debug_abbrev */ \
9186    + 1 /* .debug_line */ \
9187    + 1 /* .debug_loc */ \
9188    + 1 /* .debug_str_offsets */ \
9189    + 1 /* .debug_macro */ \
9190    + 1 /* .debug_macinfo */ \
9191    + 1 /* trailing zero */)
9192
9193   memset (&sections, 0, sizeof (sections));
9194   cleanups = make_cleanup (null_cleanup, 0);
9195
9196   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9197     {
9198       asection *sectp;
9199       uint32_t section_nr =
9200         read_4_bytes (dbfd,
9201                       htab->section_pool
9202                       + (section_index + i) * sizeof (uint32_t));
9203
9204       if (section_nr == 0)
9205         break;
9206       if (section_nr >= dwp_file->num_sections)
9207         {
9208           error (_("Dwarf Error: bad DWP hash table, section number too large"
9209                    " [in module %s]"),
9210                  dwp_file->name);
9211         }
9212
9213       sectp = dwp_file->elf_sections[section_nr];
9214       if (! locate_virtual_dwo_sections (sectp, &sections))
9215         {
9216           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9217                    " [in module %s]"),
9218                  dwp_file->name);
9219         }
9220     }
9221
9222   if (i < 2
9223       || sections.info_or_types.asection == NULL
9224       || sections.abbrev.asection == NULL)
9225     {
9226       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9227                " [in module %s]"),
9228              dwp_file->name);
9229     }
9230   if (i == MAX_NR_DWO_SECTIONS)
9231     {
9232       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9233                " [in module %s]"),
9234              dwp_file->name);
9235     }
9236
9237   /* It's easier for the rest of the code if we fake a struct dwo_file and
9238      have dwo_unit "live" in that.  At least for now.
9239
9240      The DWP file can be made up of a random collection of CUs and TUs.
9241      However, for each CU + set of TUs that came from the same original DWO
9242      file, we want to combine them back into a virtual DWO file to save space
9243      (fewer struct dwo_file objects to allocated).  Remember that for really
9244      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9245
9246   virtual_dwo_name =
9247     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9248                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9249                 sections.line.asection ? sections.line.asection->id : 0,
9250                 sections.loc.asection ? sections.loc.asection->id : 0,
9251                 (sections.str_offsets.asection
9252                 ? sections.str_offsets.asection->id
9253                 : 0));
9254   make_cleanup (xfree, virtual_dwo_name);
9255   /* Can we use an existing virtual DWO file?  */
9256   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9257   /* Create one if necessary.  */
9258   if (*dwo_file_slot == NULL)
9259     {
9260       if (dwarf2_read_debug)
9261         {
9262           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9263                               virtual_dwo_name);
9264         }
9265       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9266       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9267                                           virtual_dwo_name,
9268                                           strlen (virtual_dwo_name));
9269       dwo_file->comp_dir = comp_dir;
9270       dwo_file->sections.abbrev = sections.abbrev;
9271       dwo_file->sections.line = sections.line;
9272       dwo_file->sections.loc = sections.loc;
9273       dwo_file->sections.macinfo = sections.macinfo;
9274       dwo_file->sections.macro = sections.macro;
9275       dwo_file->sections.str_offsets = sections.str_offsets;
9276       /* The "str" section is global to the entire DWP file.  */
9277       dwo_file->sections.str = dwp_file->sections.str;
9278       /* The info or types section is assigned later to dwo_unit,
9279          there's no need to record it in dwo_file.
9280          Also, we can't simply record type sections in dwo_file because
9281          we record a pointer into the vector in dwo_unit.  As we collect more
9282          types we'll grow the vector and eventually have to reallocate space
9283          for it, invalidating all the pointers into the current copy.  */
9284       *dwo_file_slot = dwo_file;
9285     }
9286   else
9287     {
9288       if (dwarf2_read_debug)
9289         {
9290           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9291                               virtual_dwo_name);
9292         }
9293       dwo_file = *dwo_file_slot;
9294     }
9295   do_cleanups (cleanups);
9296
9297   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9298   dwo_unit->dwo_file = dwo_file;
9299   dwo_unit->signature = signature;
9300   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9301                                      sizeof (struct dwarf2_section_info));
9302   *dwo_unit->section = sections.info_or_types;
9303   /* offset, length, type_offset_in_tu are set later.  */
9304
9305   return dwo_unit;
9306 }
9307
9308 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9309
9310 static struct dwo_unit *
9311 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9312                    const struct dwp_hash_table *htab,
9313                    const char *comp_dir,
9314                    ULONGEST signature, int is_debug_types)
9315 {
9316   bfd *dbfd = dwp_file->dbfd;
9317   uint32_t mask = htab->nr_slots - 1;
9318   uint32_t hash = signature & mask;
9319   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9320   unsigned int i;
9321   void **slot;
9322   struct dwo_unit find_dwo_cu, *dwo_cu;
9323
9324   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9325   find_dwo_cu.signature = signature;
9326   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9327
9328   if (*slot != NULL)
9329     return *slot;
9330
9331   /* Use a for loop so that we don't loop forever on bad debug info.  */
9332   for (i = 0; i < htab->nr_slots; ++i)
9333     {
9334       ULONGEST signature_in_table;
9335
9336       signature_in_table =
9337         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9338       if (signature_in_table == signature)
9339         {
9340           uint32_t section_index =
9341             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9342
9343           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9344                                      comp_dir, signature, is_debug_types);
9345           return *slot;
9346         }
9347       if (signature_in_table == 0)
9348         return NULL;
9349       hash = (hash + hash2) & mask;
9350     }
9351
9352   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9353            " [in module %s]"),
9354          dwp_file->name);
9355 }
9356
9357 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9358    Open the file specified by FILE_NAME and hand it off to BFD for
9359    preliminary analysis.  Return a newly initialized bfd *, which
9360    includes a canonicalized copy of FILE_NAME.
9361    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9362    SEARCH_CWD is true if the current directory is to be searched.
9363    It will be searched before debug-file-directory.
9364    If unable to find/open the file, return NULL.
9365    NOTE: This function is derived from symfile_bfd_open.  */
9366
9367 static bfd *
9368 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9369 {
9370   bfd *sym_bfd;
9371   int desc, flags;
9372   char *absolute_name;
9373   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9374      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9375      to debug_file_directory.  */
9376   char *search_path;
9377   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9378
9379   if (search_cwd)
9380     {
9381       if (*debug_file_directory != '\0')
9382         search_path = concat (".", dirname_separator_string,
9383                               debug_file_directory, NULL);
9384       else
9385         search_path = xstrdup (".");
9386     }
9387   else
9388     search_path = xstrdup (debug_file_directory);
9389
9390   flags = 0;
9391   if (is_dwp)
9392     flags |= OPF_SEARCH_IN_PATH;
9393   desc = openp (search_path, flags, file_name,
9394                 O_RDONLY | O_BINARY, &absolute_name);
9395   xfree (search_path);
9396   if (desc < 0)
9397     return NULL;
9398
9399   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9400   xfree (absolute_name);
9401   if (sym_bfd == NULL)
9402     return NULL;
9403   bfd_set_cacheable (sym_bfd, 1);
9404
9405   if (!bfd_check_format (sym_bfd, bfd_object))
9406     {
9407       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9408       return NULL;
9409     }
9410
9411   return sym_bfd;
9412 }
9413
9414 /* Try to open DWO file FILE_NAME.
9415    COMP_DIR is the DW_AT_comp_dir attribute.
9416    The result is the bfd handle of the file.
9417    If there is a problem finding or opening the file, return NULL.
9418    Upon success, the canonicalized path of the file is stored in the bfd,
9419    same as symfile_bfd_open.  */
9420
9421 static bfd *
9422 open_dwo_file (const char *file_name, const char *comp_dir)
9423 {
9424   bfd *abfd;
9425
9426   if (IS_ABSOLUTE_PATH (file_name))
9427     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9428
9429   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9430
9431   if (comp_dir != NULL)
9432     {
9433       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9434
9435       /* NOTE: If comp_dir is a relative path, this will also try the
9436          search path, which seems useful.  */
9437       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9438       xfree (path_to_try);
9439       if (abfd != NULL)
9440         return abfd;
9441     }
9442
9443   /* That didn't work, try debug-file-directory, which, despite its name,
9444      is a list of paths.  */
9445
9446   if (*debug_file_directory == '\0')
9447     return NULL;
9448
9449   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9450 }
9451
9452 /* This function is mapped across the sections and remembers the offset and
9453    size of each of the DWO debugging sections we are interested in.  */
9454
9455 static void
9456 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9457 {
9458   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9459   const struct dwop_section_names *names = &dwop_section_names;
9460
9461   if (section_is_p (sectp->name, &names->abbrev_dwo))
9462     {
9463       dwo_sections->abbrev.asection = sectp;
9464       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9465     }
9466   else if (section_is_p (sectp->name, &names->info_dwo))
9467     {
9468       dwo_sections->info.asection = sectp;
9469       dwo_sections->info.size = bfd_get_section_size (sectp);
9470     }
9471   else if (section_is_p (sectp->name, &names->line_dwo))
9472     {
9473       dwo_sections->line.asection = sectp;
9474       dwo_sections->line.size = bfd_get_section_size (sectp);
9475     }
9476   else if (section_is_p (sectp->name, &names->loc_dwo))
9477     {
9478       dwo_sections->loc.asection = sectp;
9479       dwo_sections->loc.size = bfd_get_section_size (sectp);
9480     }
9481   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9482     {
9483       dwo_sections->macinfo.asection = sectp;
9484       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9485     }
9486   else if (section_is_p (sectp->name, &names->macro_dwo))
9487     {
9488       dwo_sections->macro.asection = sectp;
9489       dwo_sections->macro.size = bfd_get_section_size (sectp);
9490     }
9491   else if (section_is_p (sectp->name, &names->str_dwo))
9492     {
9493       dwo_sections->str.asection = sectp;
9494       dwo_sections->str.size = bfd_get_section_size (sectp);
9495     }
9496   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9497     {
9498       dwo_sections->str_offsets.asection = sectp;
9499       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9500     }
9501   else if (section_is_p (sectp->name, &names->types_dwo))
9502     {
9503       struct dwarf2_section_info type_section;
9504
9505       memset (&type_section, 0, sizeof (type_section));
9506       type_section.asection = sectp;
9507       type_section.size = bfd_get_section_size (sectp);
9508       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9509                      &type_section);
9510     }
9511 }
9512
9513 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9514    by PER_CU.  This is for the non-DWP case.
9515    The result is NULL if DWO_NAME can't be found.  */
9516
9517 static struct dwo_file *
9518 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9519                         const char *dwo_name, const char *comp_dir)
9520 {
9521   struct objfile *objfile = dwarf2_per_objfile->objfile;
9522   struct dwo_file *dwo_file;
9523   bfd *dbfd;
9524   struct cleanup *cleanups;
9525
9526   dbfd = open_dwo_file (dwo_name, comp_dir);
9527   if (dbfd == NULL)
9528     {
9529       if (dwarf2_read_debug)
9530         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9531       return NULL;
9532     }
9533   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9534   dwo_file->dwo_name = dwo_name;
9535   dwo_file->comp_dir = comp_dir;
9536   dwo_file->dbfd = dbfd;
9537
9538   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9539
9540   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9541
9542   dwo_file->cu = create_dwo_cu (dwo_file);
9543
9544   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9545                                                  dwo_file->sections.types);
9546
9547   discard_cleanups (cleanups);
9548
9549   if (dwarf2_read_debug)
9550     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9551
9552   return dwo_file;
9553 }
9554
9555 /* This function is mapped across the sections and remembers the offset and
9556    size of each of the DWP debugging sections we are interested in.  */
9557
9558 static void
9559 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9560 {
9561   struct dwp_file *dwp_file = dwp_file_ptr;
9562   const struct dwop_section_names *names = &dwop_section_names;
9563   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9564
9565   /* Record the ELF section number for later lookup: this is what the
9566      .debug_cu_index,.debug_tu_index tables use.  */
9567   gdb_assert (elf_section_nr < dwp_file->num_sections);
9568   dwp_file->elf_sections[elf_section_nr] = sectp;
9569
9570   /* Look for specific sections that we need.  */
9571   if (section_is_p (sectp->name, &names->str_dwo))
9572     {
9573       dwp_file->sections.str.asection = sectp;
9574       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9575     }
9576   else if (section_is_p (sectp->name, &names->cu_index))
9577     {
9578       dwp_file->sections.cu_index.asection = sectp;
9579       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9580     }
9581   else if (section_is_p (sectp->name, &names->tu_index))
9582     {
9583       dwp_file->sections.tu_index.asection = sectp;
9584       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9585     }
9586 }
9587
9588 /* Hash function for dwp_file loaded CUs/TUs.  */
9589
9590 static hashval_t
9591 hash_dwp_loaded_cutus (const void *item)
9592 {
9593   const struct dwo_unit *dwo_unit = item;
9594
9595   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9596   return dwo_unit->signature;
9597 }
9598
9599 /* Equality function for dwp_file loaded CUs/TUs.  */
9600
9601 static int
9602 eq_dwp_loaded_cutus (const void *a, const void *b)
9603 {
9604   const struct dwo_unit *dua = a;
9605   const struct dwo_unit *dub = b;
9606
9607   return dua->signature == dub->signature;
9608 }
9609
9610 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9611
9612 static htab_t
9613 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9614 {
9615   return htab_create_alloc_ex (3,
9616                                hash_dwp_loaded_cutus,
9617                                eq_dwp_loaded_cutus,
9618                                NULL,
9619                                &objfile->objfile_obstack,
9620                                hashtab_obstack_allocate,
9621                                dummy_obstack_deallocate);
9622 }
9623
9624 /* Try to open DWP file FILE_NAME.
9625    The result is the bfd handle of the file.
9626    If there is a problem finding or opening the file, return NULL.
9627    Upon success, the canonicalized path of the file is stored in the bfd,
9628    same as symfile_bfd_open.  */
9629
9630 static bfd *
9631 open_dwp_file (const char *file_name)
9632 {
9633   bfd *abfd;
9634
9635   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9636   if (abfd != NULL)
9637     return abfd;
9638
9639   /* Work around upstream bug 15652.
9640      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9641      [Whether that's a "bug" is debatable, but it is getting in our way.]
9642      We have no real idea where the dwp file is, because gdb's realpath-ing
9643      of the executable's path may have discarded the needed info.
9644      [IWBN if the dwp file name was recorded in the executable, akin to
9645      .gnu_debuglink, but that doesn't exist yet.]
9646      Strip the directory from FILE_NAME and search again.  */
9647   if (*debug_file_directory != '\0')
9648     {
9649       /* Don't implicitly search the current directory here.
9650          If the user wants to search "." to handle this case,
9651          it must be added to debug-file-directory.  */
9652       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9653                                  0 /*search_cwd*/);
9654     }
9655
9656   return NULL;
9657 }
9658
9659 /* Initialize the use of the DWP file for the current objfile.
9660    By convention the name of the DWP file is ${objfile}.dwp.
9661    The result is NULL if it can't be found.  */
9662
9663 static struct dwp_file *
9664 open_and_init_dwp_file (void)
9665 {
9666   struct objfile *objfile = dwarf2_per_objfile->objfile;
9667   struct dwp_file *dwp_file;
9668   char *dwp_name;
9669   bfd *dbfd;
9670   struct cleanup *cleanups;
9671
9672   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9673   cleanups = make_cleanup (xfree, dwp_name);
9674
9675   dbfd = open_dwp_file (dwp_name);
9676   if (dbfd == NULL)
9677     {
9678       if (dwarf2_read_debug)
9679         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9680       do_cleanups (cleanups);
9681       return NULL;
9682     }
9683   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9684   dwp_file->name = bfd_get_filename (dbfd);
9685   dwp_file->dbfd = dbfd;
9686   do_cleanups (cleanups);
9687
9688   /* +1: section 0 is unused */
9689   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9690   dwp_file->elf_sections =
9691     OBSTACK_CALLOC (&objfile->objfile_obstack,
9692                     dwp_file->num_sections, asection *);
9693
9694   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9695
9696   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9697
9698   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9699
9700   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9701
9702   if (dwarf2_read_debug)
9703     {
9704       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9705       fprintf_unfiltered (gdb_stdlog,
9706                           "    %s CUs, %s TUs\n",
9707                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9708                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9709     }
9710
9711   return dwp_file;
9712 }
9713
9714 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9715
9716 static struct dwp_file *
9717 get_dwp_file (void)
9718 {
9719   if (! dwarf2_per_objfile->dwp_checked)
9720     {
9721       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9722       dwarf2_per_objfile->dwp_checked = 1;
9723     }
9724   return dwarf2_per_objfile->dwp_file;
9725 }
9726
9727 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9728    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9729    or in the DWP file for the objfile, referenced by THIS_UNIT.
9730    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9731    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9732
9733    This is called, for example, when wanting to read a variable with a
9734    complex location.  Therefore we don't want to do file i/o for every call.
9735    Therefore we don't want to look for a DWO file on every call.
9736    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9737    then we check if we've already seen DWO_NAME, and only THEN do we check
9738    for a DWO file.
9739
9740    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9741    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9742
9743 static struct dwo_unit *
9744 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9745                  const char *dwo_name, const char *comp_dir,
9746                  ULONGEST signature, int is_debug_types)
9747 {
9748   struct objfile *objfile = dwarf2_per_objfile->objfile;
9749   const char *kind = is_debug_types ? "TU" : "CU";
9750   void **dwo_file_slot;
9751   struct dwo_file *dwo_file;
9752   struct dwp_file *dwp_file;
9753
9754   /* First see if there's a DWP file.
9755      If we have a DWP file but didn't find the DWO inside it, don't
9756      look for the original DWO file.  It makes gdb behave differently
9757      depending on whether one is debugging in the build tree.  */
9758
9759   dwp_file = get_dwp_file ();
9760   if (dwp_file != NULL)
9761     {
9762       const struct dwp_hash_table *dwp_htab =
9763         is_debug_types ? dwp_file->tus : dwp_file->cus;
9764
9765       if (dwp_htab != NULL)
9766         {
9767           struct dwo_unit *dwo_cutu =
9768             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9769                                signature, is_debug_types);
9770
9771           if (dwo_cutu != NULL)
9772             {
9773               if (dwarf2_read_debug)
9774                 {
9775                   fprintf_unfiltered (gdb_stdlog,
9776                                       "Virtual DWO %s %s found: @%s\n",
9777                                       kind, hex_string (signature),
9778                                       host_address_to_string (dwo_cutu));
9779                 }
9780               return dwo_cutu;
9781             }
9782         }
9783     }
9784   else
9785     {
9786       /* No DWP file, look for the DWO file.  */
9787
9788       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9789       if (*dwo_file_slot == NULL)
9790         {
9791           /* Read in the file and build a table of the CUs/TUs it contains.  */
9792           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9793         }
9794       /* NOTE: This will be NULL if unable to open the file.  */
9795       dwo_file = *dwo_file_slot;
9796
9797       if (dwo_file != NULL)
9798         {
9799           struct dwo_unit *dwo_cutu = NULL;
9800
9801           if (is_debug_types && dwo_file->tus)
9802             {
9803               struct dwo_unit find_dwo_cutu;
9804
9805               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9806               find_dwo_cutu.signature = signature;
9807               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9808             }
9809           else if (!is_debug_types && dwo_file->cu)
9810             {
9811               if (signature == dwo_file->cu->signature)
9812                 dwo_cutu = dwo_file->cu;
9813             }
9814
9815           if (dwo_cutu != NULL)
9816             {
9817               if (dwarf2_read_debug)
9818                 {
9819                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9820                                       kind, dwo_name, hex_string (signature),
9821                                       host_address_to_string (dwo_cutu));
9822                 }
9823               return dwo_cutu;
9824             }
9825         }
9826     }
9827
9828   /* We didn't find it.  This could mean a dwo_id mismatch, or
9829      someone deleted the DWO/DWP file, or the search path isn't set up
9830      correctly to find the file.  */
9831
9832   if (dwarf2_read_debug)
9833     {
9834       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9835                           kind, dwo_name, hex_string (signature));
9836     }
9837
9838   /* This is a warning and not a complaint because it can be caused by
9839      pilot error (e.g., user accidentally deleting the DWO).  */
9840   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9841              " [in module %s]"),
9842            kind, dwo_name, hex_string (signature),
9843            this_unit->is_debug_types ? "TU" : "CU",
9844            this_unit->offset.sect_off, objfile->name);
9845   return NULL;
9846 }
9847
9848 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9849    See lookup_dwo_cutu_unit for details.  */
9850
9851 static struct dwo_unit *
9852 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9853                       const char *dwo_name, const char *comp_dir,
9854                       ULONGEST signature)
9855 {
9856   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9857 }
9858
9859 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9860    See lookup_dwo_cutu_unit for details.  */
9861
9862 static struct dwo_unit *
9863 lookup_dwo_type_unit (struct signatured_type *this_tu,
9864                       const char *dwo_name, const char *comp_dir)
9865 {
9866   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9867 }
9868
9869 /* Free all resources associated with DWO_FILE.
9870    Close the DWO file and munmap the sections.
9871    All memory should be on the objfile obstack.  */
9872
9873 static void
9874 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9875 {
9876   int ix;
9877   struct dwarf2_section_info *section;
9878
9879   /* Note: dbfd is NULL for virtual DWO files.  */
9880   gdb_bfd_unref (dwo_file->dbfd);
9881
9882   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9883 }
9884
9885 /* Wrapper for free_dwo_file for use in cleanups.  */
9886
9887 static void
9888 free_dwo_file_cleanup (void *arg)
9889 {
9890   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9891   struct objfile *objfile = dwarf2_per_objfile->objfile;
9892
9893   free_dwo_file (dwo_file, objfile);
9894 }
9895
9896 /* Traversal function for free_dwo_files.  */
9897
9898 static int
9899 free_dwo_file_from_slot (void **slot, void *info)
9900 {
9901   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9902   struct objfile *objfile = (struct objfile *) info;
9903
9904   free_dwo_file (dwo_file, objfile);
9905
9906   return 1;
9907 }
9908
9909 /* Free all resources associated with DWO_FILES.  */
9910
9911 static void
9912 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9913 {
9914   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9915 }
9916 \f
9917 /* Read in various DIEs.  */
9918
9919 /* qsort helper for inherit_abstract_dies.  */
9920
9921 static int
9922 unsigned_int_compar (const void *ap, const void *bp)
9923 {
9924   unsigned int a = *(unsigned int *) ap;
9925   unsigned int b = *(unsigned int *) bp;
9926
9927   return (a > b) - (b > a);
9928 }
9929
9930 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9931    Inherit only the children of the DW_AT_abstract_origin DIE not being
9932    already referenced by DW_AT_abstract_origin from the children of the
9933    current DIE.  */
9934
9935 static void
9936 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9937 {
9938   struct die_info *child_die;
9939   unsigned die_children_count;
9940   /* CU offsets which were referenced by children of the current DIE.  */
9941   sect_offset *offsets;
9942   sect_offset *offsets_end, *offsetp;
9943   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9944   struct die_info *origin_die;
9945   /* Iterator of the ORIGIN_DIE children.  */
9946   struct die_info *origin_child_die;
9947   struct cleanup *cleanups;
9948   struct attribute *attr;
9949   struct dwarf2_cu *origin_cu;
9950   struct pending **origin_previous_list_in_scope;
9951
9952   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9953   if (!attr)
9954     return;
9955
9956   /* Note that following die references may follow to a die in a
9957      different cu.  */
9958
9959   origin_cu = cu;
9960   origin_die = follow_die_ref (die, attr, &origin_cu);
9961
9962   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9963      symbols in.  */
9964   origin_previous_list_in_scope = origin_cu->list_in_scope;
9965   origin_cu->list_in_scope = cu->list_in_scope;
9966
9967   if (die->tag != origin_die->tag
9968       && !(die->tag == DW_TAG_inlined_subroutine
9969            && origin_die->tag == DW_TAG_subprogram))
9970     complaint (&symfile_complaints,
9971                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9972                die->offset.sect_off, origin_die->offset.sect_off);
9973
9974   child_die = die->child;
9975   die_children_count = 0;
9976   while (child_die && child_die->tag)
9977     {
9978       child_die = sibling_die (child_die);
9979       die_children_count++;
9980     }
9981   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9982   cleanups = make_cleanup (xfree, offsets);
9983
9984   offsets_end = offsets;
9985   child_die = die->child;
9986   while (child_die && child_die->tag)
9987     {
9988       /* For each CHILD_DIE, find the corresponding child of
9989          ORIGIN_DIE.  If there is more than one layer of
9990          DW_AT_abstract_origin, follow them all; there shouldn't be,
9991          but GCC versions at least through 4.4 generate this (GCC PR
9992          40573).  */
9993       struct die_info *child_origin_die = child_die;
9994       struct dwarf2_cu *child_origin_cu = cu;
9995
9996       while (1)
9997         {
9998           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9999                               child_origin_cu);
10000           if (attr == NULL)
10001             break;
10002           child_origin_die = follow_die_ref (child_origin_die, attr,
10003                                              &child_origin_cu);
10004         }
10005
10006       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10007          counterpart may exist.  */
10008       if (child_origin_die != child_die)
10009         {
10010           if (child_die->tag != child_origin_die->tag
10011               && !(child_die->tag == DW_TAG_inlined_subroutine
10012                    && child_origin_die->tag == DW_TAG_subprogram))
10013             complaint (&symfile_complaints,
10014                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10015                          "different tags"), child_die->offset.sect_off,
10016                        child_origin_die->offset.sect_off);
10017           if (child_origin_die->parent != origin_die)
10018             complaint (&symfile_complaints,
10019                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10020                          "different parents"), child_die->offset.sect_off,
10021                        child_origin_die->offset.sect_off);
10022           else
10023             *offsets_end++ = child_origin_die->offset;
10024         }
10025       child_die = sibling_die (child_die);
10026     }
10027   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10028          unsigned_int_compar);
10029   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10030     if (offsetp[-1].sect_off == offsetp->sect_off)
10031       complaint (&symfile_complaints,
10032                  _("Multiple children of DIE 0x%x refer "
10033                    "to DIE 0x%x as their abstract origin"),
10034                  die->offset.sect_off, offsetp->sect_off);
10035
10036   offsetp = offsets;
10037   origin_child_die = origin_die->child;
10038   while (origin_child_die && origin_child_die->tag)
10039     {
10040       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10041       while (offsetp < offsets_end
10042              && offsetp->sect_off < origin_child_die->offset.sect_off)
10043         offsetp++;
10044       if (offsetp >= offsets_end
10045           || offsetp->sect_off > origin_child_die->offset.sect_off)
10046         {
10047           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10048           process_die (origin_child_die, origin_cu);
10049         }
10050       origin_child_die = sibling_die (origin_child_die);
10051     }
10052   origin_cu->list_in_scope = origin_previous_list_in_scope;
10053
10054   do_cleanups (cleanups);
10055 }
10056
10057 static void
10058 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10059 {
10060   struct objfile *objfile = cu->objfile;
10061   struct context_stack *new;
10062   CORE_ADDR lowpc;
10063   CORE_ADDR highpc;
10064   struct die_info *child_die;
10065   struct attribute *attr, *call_line, *call_file;
10066   const char *name;
10067   CORE_ADDR baseaddr;
10068   struct block *block;
10069   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10070   VEC (symbolp) *template_args = NULL;
10071   struct template_symbol *templ_func = NULL;
10072
10073   if (inlined_func)
10074     {
10075       /* If we do not have call site information, we can't show the
10076          caller of this inlined function.  That's too confusing, so
10077          only use the scope for local variables.  */
10078       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10079       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10080       if (call_line == NULL || call_file == NULL)
10081         {
10082           read_lexical_block_scope (die, cu);
10083           return;
10084         }
10085     }
10086
10087   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10088
10089   name = dwarf2_name (die, cu);
10090
10091   /* Ignore functions with missing or empty names.  These are actually
10092      illegal according to the DWARF standard.  */
10093   if (name == NULL)
10094     {
10095       complaint (&symfile_complaints,
10096                  _("missing name for subprogram DIE at %d"),
10097                  die->offset.sect_off);
10098       return;
10099     }
10100
10101   /* Ignore functions with missing or invalid low and high pc attributes.  */
10102   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10103     {
10104       attr = dwarf2_attr (die, DW_AT_external, cu);
10105       if (!attr || !DW_UNSND (attr))
10106         complaint (&symfile_complaints,
10107                    _("cannot get low and high bounds "
10108                      "for subprogram DIE at %d"),
10109                    die->offset.sect_off);
10110       return;
10111     }
10112
10113   lowpc += baseaddr;
10114   highpc += baseaddr;
10115
10116   /* If we have any template arguments, then we must allocate a
10117      different sort of symbol.  */
10118   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10119     {
10120       if (child_die->tag == DW_TAG_template_type_param
10121           || child_die->tag == DW_TAG_template_value_param)
10122         {
10123           templ_func = allocate_template_symbol (objfile);
10124           templ_func->base.is_cplus_template_function = 1;
10125           break;
10126         }
10127     }
10128
10129   new = push_context (0, lowpc);
10130   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10131                                (struct symbol *) templ_func);
10132
10133   /* If there is a location expression for DW_AT_frame_base, record
10134      it.  */
10135   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10136   if (attr)
10137     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10138
10139   cu->list_in_scope = &local_symbols;
10140
10141   if (die->child != NULL)
10142     {
10143       child_die = die->child;
10144       while (child_die && child_die->tag)
10145         {
10146           if (child_die->tag == DW_TAG_template_type_param
10147               || child_die->tag == DW_TAG_template_value_param)
10148             {
10149               struct symbol *arg = new_symbol (child_die, NULL, cu);
10150
10151               if (arg != NULL)
10152                 VEC_safe_push (symbolp, template_args, arg);
10153             }
10154           else
10155             process_die (child_die, cu);
10156           child_die = sibling_die (child_die);
10157         }
10158     }
10159
10160   inherit_abstract_dies (die, cu);
10161
10162   /* If we have a DW_AT_specification, we might need to import using
10163      directives from the context of the specification DIE.  See the
10164      comment in determine_prefix.  */
10165   if (cu->language == language_cplus
10166       && dwarf2_attr (die, DW_AT_specification, cu))
10167     {
10168       struct dwarf2_cu *spec_cu = cu;
10169       struct die_info *spec_die = die_specification (die, &spec_cu);
10170
10171       while (spec_die)
10172         {
10173           child_die = spec_die->child;
10174           while (child_die && child_die->tag)
10175             {
10176               if (child_die->tag == DW_TAG_imported_module)
10177                 process_die (child_die, spec_cu);
10178               child_die = sibling_die (child_die);
10179             }
10180
10181           /* In some cases, GCC generates specification DIEs that
10182              themselves contain DW_AT_specification attributes.  */
10183           spec_die = die_specification (spec_die, &spec_cu);
10184         }
10185     }
10186
10187   new = pop_context ();
10188   /* Make a block for the local symbols within.  */
10189   block = finish_block (new->name, &local_symbols, new->old_blocks,
10190                         lowpc, highpc, objfile);
10191
10192   /* For C++, set the block's scope.  */
10193   if ((cu->language == language_cplus || cu->language == language_fortran)
10194       && cu->processing_has_namespace_info)
10195     block_set_scope (block, determine_prefix (die, cu),
10196                      &objfile->objfile_obstack);
10197
10198   /* If we have address ranges, record them.  */
10199   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10200
10201   /* Attach template arguments to function.  */
10202   if (! VEC_empty (symbolp, template_args))
10203     {
10204       gdb_assert (templ_func != NULL);
10205
10206       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10207       templ_func->template_arguments
10208         = obstack_alloc (&objfile->objfile_obstack,
10209                          (templ_func->n_template_arguments
10210                           * sizeof (struct symbol *)));
10211       memcpy (templ_func->template_arguments,
10212               VEC_address (symbolp, template_args),
10213               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10214       VEC_free (symbolp, template_args);
10215     }
10216
10217   /* In C++, we can have functions nested inside functions (e.g., when
10218      a function declares a class that has methods).  This means that
10219      when we finish processing a function scope, we may need to go
10220      back to building a containing block's symbol lists.  */
10221   local_symbols = new->locals;
10222   using_directives = new->using_directives;
10223
10224   /* If we've finished processing a top-level function, subsequent
10225      symbols go in the file symbol list.  */
10226   if (outermost_context_p ())
10227     cu->list_in_scope = &file_symbols;
10228 }
10229
10230 /* Process all the DIES contained within a lexical block scope.  Start
10231    a new scope, process the dies, and then close the scope.  */
10232
10233 static void
10234 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10235 {
10236   struct objfile *objfile = cu->objfile;
10237   struct context_stack *new;
10238   CORE_ADDR lowpc, highpc;
10239   struct die_info *child_die;
10240   CORE_ADDR baseaddr;
10241
10242   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10243
10244   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10245   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10246      as multiple lexical blocks?  Handling children in a sane way would
10247      be nasty.  Might be easier to properly extend generic blocks to
10248      describe ranges.  */
10249   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10250     return;
10251   lowpc += baseaddr;
10252   highpc += baseaddr;
10253
10254   push_context (0, lowpc);
10255   if (die->child != NULL)
10256     {
10257       child_die = die->child;
10258       while (child_die && child_die->tag)
10259         {
10260           process_die (child_die, cu);
10261           child_die = sibling_die (child_die);
10262         }
10263     }
10264   new = pop_context ();
10265
10266   if (local_symbols != NULL || using_directives != NULL)
10267     {
10268       struct block *block
10269         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10270                         highpc, objfile);
10271
10272       /* Note that recording ranges after traversing children, as we
10273          do here, means that recording a parent's ranges entails
10274          walking across all its children's ranges as they appear in
10275          the address map, which is quadratic behavior.
10276
10277          It would be nicer to record the parent's ranges before
10278          traversing its children, simply overriding whatever you find
10279          there.  But since we don't even decide whether to create a
10280          block until after we've traversed its children, that's hard
10281          to do.  */
10282       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10283     }
10284   local_symbols = new->locals;
10285   using_directives = new->using_directives;
10286 }
10287
10288 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10289
10290 static void
10291 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10292 {
10293   struct objfile *objfile = cu->objfile;
10294   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10295   CORE_ADDR pc, baseaddr;
10296   struct attribute *attr;
10297   struct call_site *call_site, call_site_local;
10298   void **slot;
10299   int nparams;
10300   struct die_info *child_die;
10301
10302   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10303
10304   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10305   if (!attr)
10306     {
10307       complaint (&symfile_complaints,
10308                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10309                    "DIE 0x%x [in module %s]"),
10310                  die->offset.sect_off, objfile->name);
10311       return;
10312     }
10313   pc = DW_ADDR (attr) + baseaddr;
10314
10315   if (cu->call_site_htab == NULL)
10316     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10317                                                NULL, &objfile->objfile_obstack,
10318                                                hashtab_obstack_allocate, NULL);
10319   call_site_local.pc = pc;
10320   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10321   if (*slot != NULL)
10322     {
10323       complaint (&symfile_complaints,
10324                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10325                    "DIE 0x%x [in module %s]"),
10326                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
10327       return;
10328     }
10329
10330   /* Count parameters at the caller.  */
10331
10332   nparams = 0;
10333   for (child_die = die->child; child_die && child_die->tag;
10334        child_die = sibling_die (child_die))
10335     {
10336       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10337         {
10338           complaint (&symfile_complaints,
10339                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10340                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10341                      child_die->tag, child_die->offset.sect_off, objfile->name);
10342           continue;
10343         }
10344
10345       nparams++;
10346     }
10347
10348   call_site = obstack_alloc (&objfile->objfile_obstack,
10349                              (sizeof (*call_site)
10350                               + (sizeof (*call_site->parameter)
10351                                  * (nparams - 1))));
10352   *slot = call_site;
10353   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10354   call_site->pc = pc;
10355
10356   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10357     {
10358       struct die_info *func_die;
10359
10360       /* Skip also over DW_TAG_inlined_subroutine.  */
10361       for (func_die = die->parent;
10362            func_die && func_die->tag != DW_TAG_subprogram
10363            && func_die->tag != DW_TAG_subroutine_type;
10364            func_die = func_die->parent);
10365
10366       /* DW_AT_GNU_all_call_sites is a superset
10367          of DW_AT_GNU_all_tail_call_sites.  */
10368       if (func_die
10369           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10370           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10371         {
10372           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10373              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10374              both the initial caller containing the real return address PC and
10375              the final callee containing the current PC of a chain of tail
10376              calls do not need to have the tail call list complete.  But any
10377              function candidate for a virtual tail call frame searched via
10378              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10379              determined unambiguously.  */
10380         }
10381       else
10382         {
10383           struct type *func_type = NULL;
10384
10385           if (func_die)
10386             func_type = get_die_type (func_die, cu);
10387           if (func_type != NULL)
10388             {
10389               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10390
10391               /* Enlist this call site to the function.  */
10392               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10393               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10394             }
10395           else
10396             complaint (&symfile_complaints,
10397                        _("Cannot find function owning DW_TAG_GNU_call_site "
10398                          "DIE 0x%x [in module %s]"),
10399                        die->offset.sect_off, objfile->name);
10400         }
10401     }
10402
10403   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10404   if (attr == NULL)
10405     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10406   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10407   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10408     /* Keep NULL DWARF_BLOCK.  */;
10409   else if (attr_form_is_block (attr))
10410     {
10411       struct dwarf2_locexpr_baton *dlbaton;
10412
10413       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10414       dlbaton->data = DW_BLOCK (attr)->data;
10415       dlbaton->size = DW_BLOCK (attr)->size;
10416       dlbaton->per_cu = cu->per_cu;
10417
10418       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10419     }
10420   else if (attr_form_is_ref (attr))
10421     {
10422       struct dwarf2_cu *target_cu = cu;
10423       struct die_info *target_die;
10424
10425       target_die = follow_die_ref (die, attr, &target_cu);
10426       gdb_assert (target_cu->objfile == objfile);
10427       if (die_is_declaration (target_die, target_cu))
10428         {
10429           const char *target_physname = NULL;
10430           struct attribute *target_attr;
10431
10432           /* Prefer the mangled name; otherwise compute the demangled one.  */
10433           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10434           if (target_attr == NULL)
10435             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10436                                        target_cu);
10437           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10438             target_physname = DW_STRING (target_attr);
10439           else
10440             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10441           if (target_physname == NULL)
10442             complaint (&symfile_complaints,
10443                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10444                          "physname, for referencing DIE 0x%x [in module %s]"),
10445                        die->offset.sect_off, objfile->name);
10446           else
10447             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10448         }
10449       else
10450         {
10451           CORE_ADDR lowpc;
10452
10453           /* DW_AT_entry_pc should be preferred.  */
10454           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10455             complaint (&symfile_complaints,
10456                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10457                          "low pc, for referencing DIE 0x%x [in module %s]"),
10458                        die->offset.sect_off, objfile->name);
10459           else
10460             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10461         }
10462     }
10463   else
10464     complaint (&symfile_complaints,
10465                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10466                  "block nor reference, for DIE 0x%x [in module %s]"),
10467                die->offset.sect_off, objfile->name);
10468
10469   call_site->per_cu = cu->per_cu;
10470
10471   for (child_die = die->child;
10472        child_die && child_die->tag;
10473        child_die = sibling_die (child_die))
10474     {
10475       struct call_site_parameter *parameter;
10476       struct attribute *loc, *origin;
10477
10478       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10479         {
10480           /* Already printed the complaint above.  */
10481           continue;
10482         }
10483
10484       gdb_assert (call_site->parameter_count < nparams);
10485       parameter = &call_site->parameter[call_site->parameter_count];
10486
10487       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10488          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10489          register is contained in DW_AT_GNU_call_site_value.  */
10490
10491       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10492       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10493       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
10494         {
10495           sect_offset offset;
10496
10497           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10498           offset = dwarf2_get_ref_die_offset (origin);
10499           if (!offset_in_cu_p (&cu->header, offset))
10500             {
10501               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10502                  binding can be done only inside one CU.  Such referenced DIE
10503                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10504               complaint (&symfile_complaints,
10505                          _("DW_AT_abstract_origin offset is not in CU for "
10506                            "DW_TAG_GNU_call_site child DIE 0x%x "
10507                            "[in module %s]"),
10508                          child_die->offset.sect_off, objfile->name);
10509               continue;
10510             }
10511           parameter->u.param_offset.cu_off = (offset.sect_off
10512                                               - cu->header.offset.sect_off);
10513         }
10514       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10515         {
10516           complaint (&symfile_complaints,
10517                      _("No DW_FORM_block* DW_AT_location for "
10518                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10519                      child_die->offset.sect_off, objfile->name);
10520           continue;
10521         }
10522       else
10523         {
10524           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10525             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10526           if (parameter->u.dwarf_reg != -1)
10527             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10528           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10529                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10530                                              &parameter->u.fb_offset))
10531             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10532           else
10533             {
10534               complaint (&symfile_complaints,
10535                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10536                            "for DW_FORM_block* DW_AT_location is supported for "
10537                            "DW_TAG_GNU_call_site child DIE 0x%x "
10538                            "[in module %s]"),
10539                          child_die->offset.sect_off, objfile->name);
10540               continue;
10541             }
10542         }
10543
10544       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10545       if (!attr_form_is_block (attr))
10546         {
10547           complaint (&symfile_complaints,
10548                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10549                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10550                      child_die->offset.sect_off, objfile->name);
10551           continue;
10552         }
10553       parameter->value = DW_BLOCK (attr)->data;
10554       parameter->value_size = DW_BLOCK (attr)->size;
10555
10556       /* Parameters are not pre-cleared by memset above.  */
10557       parameter->data_value = NULL;
10558       parameter->data_value_size = 0;
10559       call_site->parameter_count++;
10560
10561       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10562       if (attr)
10563         {
10564           if (!attr_form_is_block (attr))
10565             complaint (&symfile_complaints,
10566                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10567                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10568                        child_die->offset.sect_off, objfile->name);
10569           else
10570             {
10571               parameter->data_value = DW_BLOCK (attr)->data;
10572               parameter->data_value_size = DW_BLOCK (attr)->size;
10573             }
10574         }
10575     }
10576 }
10577
10578 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10579    Return 1 if the attributes are present and valid, otherwise, return 0.
10580    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10581
10582 static int
10583 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10584                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10585                     struct partial_symtab *ranges_pst)
10586 {
10587   struct objfile *objfile = cu->objfile;
10588   struct comp_unit_head *cu_header = &cu->header;
10589   bfd *obfd = objfile->obfd;
10590   unsigned int addr_size = cu_header->addr_size;
10591   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10592   /* Base address selection entry.  */
10593   CORE_ADDR base;
10594   int found_base;
10595   unsigned int dummy;
10596   const gdb_byte *buffer;
10597   CORE_ADDR marker;
10598   int low_set;
10599   CORE_ADDR low = 0;
10600   CORE_ADDR high = 0;
10601   CORE_ADDR baseaddr;
10602
10603   found_base = cu->base_known;
10604   base = cu->base_address;
10605
10606   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10607   if (offset >= dwarf2_per_objfile->ranges.size)
10608     {
10609       complaint (&symfile_complaints,
10610                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10611                  offset);
10612       return 0;
10613     }
10614   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10615
10616   /* Read in the largest possible address.  */
10617   marker = read_address (obfd, buffer, cu, &dummy);
10618   if ((marker & mask) == mask)
10619     {
10620       /* If we found the largest possible address, then
10621          read the base address.  */
10622       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10623       buffer += 2 * addr_size;
10624       offset += 2 * addr_size;
10625       found_base = 1;
10626     }
10627
10628   low_set = 0;
10629
10630   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10631
10632   while (1)
10633     {
10634       CORE_ADDR range_beginning, range_end;
10635
10636       range_beginning = read_address (obfd, buffer, cu, &dummy);
10637       buffer += addr_size;
10638       range_end = read_address (obfd, buffer, cu, &dummy);
10639       buffer += addr_size;
10640       offset += 2 * addr_size;
10641
10642       /* An end of list marker is a pair of zero addresses.  */
10643       if (range_beginning == 0 && range_end == 0)
10644         /* Found the end of list entry.  */
10645         break;
10646
10647       /* Each base address selection entry is a pair of 2 values.
10648          The first is the largest possible address, the second is
10649          the base address.  Check for a base address here.  */
10650       if ((range_beginning & mask) == mask)
10651         {
10652           /* If we found the largest possible address, then
10653              read the base address.  */
10654           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10655           found_base = 1;
10656           continue;
10657         }
10658
10659       if (!found_base)
10660         {
10661           /* We have no valid base address for the ranges
10662              data.  */
10663           complaint (&symfile_complaints,
10664                      _("Invalid .debug_ranges data (no base address)"));
10665           return 0;
10666         }
10667
10668       if (range_beginning > range_end)
10669         {
10670           /* Inverted range entries are invalid.  */
10671           complaint (&symfile_complaints,
10672                      _("Invalid .debug_ranges data (inverted range)"));
10673           return 0;
10674         }
10675
10676       /* Empty range entries have no effect.  */
10677       if (range_beginning == range_end)
10678         continue;
10679
10680       range_beginning += base;
10681       range_end += base;
10682
10683       /* A not-uncommon case of bad debug info.
10684          Don't pollute the addrmap with bad data.  */
10685       if (range_beginning + baseaddr == 0
10686           && !dwarf2_per_objfile->has_section_at_zero)
10687         {
10688           complaint (&symfile_complaints,
10689                      _(".debug_ranges entry has start address of zero"
10690                        " [in module %s]"), objfile->name);
10691           continue;
10692         }
10693
10694       if (ranges_pst != NULL)
10695         addrmap_set_empty (objfile->psymtabs_addrmap,
10696                            range_beginning + baseaddr,
10697                            range_end - 1 + baseaddr,
10698                            ranges_pst);
10699
10700       /* FIXME: This is recording everything as a low-high
10701          segment of consecutive addresses.  We should have a
10702          data structure for discontiguous block ranges
10703          instead.  */
10704       if (! low_set)
10705         {
10706           low = range_beginning;
10707           high = range_end;
10708           low_set = 1;
10709         }
10710       else
10711         {
10712           if (range_beginning < low)
10713             low = range_beginning;
10714           if (range_end > high)
10715             high = range_end;
10716         }
10717     }
10718
10719   if (! low_set)
10720     /* If the first entry is an end-of-list marker, the range
10721        describes an empty scope, i.e. no instructions.  */
10722     return 0;
10723
10724   if (low_return)
10725     *low_return = low;
10726   if (high_return)
10727     *high_return = high;
10728   return 1;
10729 }
10730
10731 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10732    are present and valid, otherwise, return 0.  Return -1 if the range is
10733    discontinuous, i.e. derived from DW_AT_ranges information.  */
10734
10735 static int
10736 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10737                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10738                       struct partial_symtab *pst)
10739 {
10740   struct attribute *attr;
10741   struct attribute *attr_high;
10742   CORE_ADDR low = 0;
10743   CORE_ADDR high = 0;
10744   int ret = 0;
10745
10746   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10747   if (attr_high)
10748     {
10749       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10750       if (attr)
10751         {
10752           low = DW_ADDR (attr);
10753           if (attr_high->form == DW_FORM_addr
10754               || attr_high->form == DW_FORM_GNU_addr_index)
10755             high = DW_ADDR (attr_high);
10756           else
10757             high = low + DW_UNSND (attr_high);
10758         }
10759       else
10760         /* Found high w/o low attribute.  */
10761         return 0;
10762
10763       /* Found consecutive range of addresses.  */
10764       ret = 1;
10765     }
10766   else
10767     {
10768       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10769       if (attr != NULL)
10770         {
10771           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10772              We take advantage of the fact that DW_AT_ranges does not appear
10773              in DW_TAG_compile_unit of DWO files.  */
10774           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10775           unsigned int ranges_offset = (DW_UNSND (attr)
10776                                         + (need_ranges_base
10777                                            ? cu->ranges_base
10778                                            : 0));
10779
10780           /* Value of the DW_AT_ranges attribute is the offset in the
10781              .debug_ranges section.  */
10782           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10783             return 0;
10784           /* Found discontinuous range of addresses.  */
10785           ret = -1;
10786         }
10787     }
10788
10789   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10790   if (high <= low)
10791     return 0;
10792
10793   /* When using the GNU linker, .gnu.linkonce. sections are used to
10794      eliminate duplicate copies of functions and vtables and such.
10795      The linker will arbitrarily choose one and discard the others.
10796      The AT_*_pc values for such functions refer to local labels in
10797      these sections.  If the section from that file was discarded, the
10798      labels are not in the output, so the relocs get a value of 0.
10799      If this is a discarded function, mark the pc bounds as invalid,
10800      so that GDB will ignore it.  */
10801   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10802     return 0;
10803
10804   *lowpc = low;
10805   if (highpc)
10806     *highpc = high;
10807   return ret;
10808 }
10809
10810 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10811    its low and high PC addresses.  Do nothing if these addresses could not
10812    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10813    and HIGHPC to the high address if greater than HIGHPC.  */
10814
10815 static void
10816 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10817                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10818                                  struct dwarf2_cu *cu)
10819 {
10820   CORE_ADDR low, high;
10821   struct die_info *child = die->child;
10822
10823   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10824     {
10825       *lowpc = min (*lowpc, low);
10826       *highpc = max (*highpc, high);
10827     }
10828
10829   /* If the language does not allow nested subprograms (either inside
10830      subprograms or lexical blocks), we're done.  */
10831   if (cu->language != language_ada)
10832     return;
10833
10834   /* Check all the children of the given DIE.  If it contains nested
10835      subprograms, then check their pc bounds.  Likewise, we need to
10836      check lexical blocks as well, as they may also contain subprogram
10837      definitions.  */
10838   while (child && child->tag)
10839     {
10840       if (child->tag == DW_TAG_subprogram
10841           || child->tag == DW_TAG_lexical_block)
10842         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10843       child = sibling_die (child);
10844     }
10845 }
10846
10847 /* Get the low and high pc's represented by the scope DIE, and store
10848    them in *LOWPC and *HIGHPC.  If the correct values can't be
10849    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10850
10851 static void
10852 get_scope_pc_bounds (struct die_info *die,
10853                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10854                      struct dwarf2_cu *cu)
10855 {
10856   CORE_ADDR best_low = (CORE_ADDR) -1;
10857   CORE_ADDR best_high = (CORE_ADDR) 0;
10858   CORE_ADDR current_low, current_high;
10859
10860   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10861     {
10862       best_low = current_low;
10863       best_high = current_high;
10864     }
10865   else
10866     {
10867       struct die_info *child = die->child;
10868
10869       while (child && child->tag)
10870         {
10871           switch (child->tag) {
10872           case DW_TAG_subprogram:
10873             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10874             break;
10875           case DW_TAG_namespace:
10876           case DW_TAG_module:
10877             /* FIXME: carlton/2004-01-16: Should we do this for
10878                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10879                that current GCC's always emit the DIEs corresponding
10880                to definitions of methods of classes as children of a
10881                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10882                the DIEs giving the declarations, which could be
10883                anywhere).  But I don't see any reason why the
10884                standards says that they have to be there.  */
10885             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10886
10887             if (current_low != ((CORE_ADDR) -1))
10888               {
10889                 best_low = min (best_low, current_low);
10890                 best_high = max (best_high, current_high);
10891               }
10892             break;
10893           default:
10894             /* Ignore.  */
10895             break;
10896           }
10897
10898           child = sibling_die (child);
10899         }
10900     }
10901
10902   *lowpc = best_low;
10903   *highpc = best_high;
10904 }
10905
10906 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10907    in DIE.  */
10908
10909 static void
10910 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10911                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10912 {
10913   struct objfile *objfile = cu->objfile;
10914   struct attribute *attr;
10915   struct attribute *attr_high;
10916
10917   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10918   if (attr_high)
10919     {
10920       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10921       if (attr)
10922         {
10923           CORE_ADDR low = DW_ADDR (attr);
10924           CORE_ADDR high;
10925           if (attr_high->form == DW_FORM_addr
10926               || attr_high->form == DW_FORM_GNU_addr_index)
10927             high = DW_ADDR (attr_high);
10928           else
10929             high = low + DW_UNSND (attr_high);
10930
10931           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10932         }
10933     }
10934
10935   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10936   if (attr)
10937     {
10938       bfd *obfd = objfile->obfd;
10939       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10940          We take advantage of the fact that DW_AT_ranges does not appear
10941          in DW_TAG_compile_unit of DWO files.  */
10942       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10943
10944       /* The value of the DW_AT_ranges attribute is the offset of the
10945          address range list in the .debug_ranges section.  */
10946       unsigned long offset = (DW_UNSND (attr)
10947                               + (need_ranges_base ? cu->ranges_base : 0));
10948       const gdb_byte *buffer;
10949
10950       /* For some target architectures, but not others, the
10951          read_address function sign-extends the addresses it returns.
10952          To recognize base address selection entries, we need a
10953          mask.  */
10954       unsigned int addr_size = cu->header.addr_size;
10955       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10956
10957       /* The base address, to which the next pair is relative.  Note
10958          that this 'base' is a DWARF concept: most entries in a range
10959          list are relative, to reduce the number of relocs against the
10960          debugging information.  This is separate from this function's
10961          'baseaddr' argument, which GDB uses to relocate debugging
10962          information from a shared library based on the address at
10963          which the library was loaded.  */
10964       CORE_ADDR base = cu->base_address;
10965       int base_known = cu->base_known;
10966
10967       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10968       if (offset >= dwarf2_per_objfile->ranges.size)
10969         {
10970           complaint (&symfile_complaints,
10971                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10972                      offset);
10973           return;
10974         }
10975       buffer = dwarf2_per_objfile->ranges.buffer + offset;
10976
10977       for (;;)
10978         {
10979           unsigned int bytes_read;
10980           CORE_ADDR start, end;
10981
10982           start = read_address (obfd, buffer, cu, &bytes_read);
10983           buffer += bytes_read;
10984           end = read_address (obfd, buffer, cu, &bytes_read);
10985           buffer += bytes_read;
10986
10987           /* Did we find the end of the range list?  */
10988           if (start == 0 && end == 0)
10989             break;
10990
10991           /* Did we find a base address selection entry?  */
10992           else if ((start & base_select_mask) == base_select_mask)
10993             {
10994               base = end;
10995               base_known = 1;
10996             }
10997
10998           /* We found an ordinary address range.  */
10999           else
11000             {
11001               if (!base_known)
11002                 {
11003                   complaint (&symfile_complaints,
11004                              _("Invalid .debug_ranges data "
11005                                "(no base address)"));
11006                   return;
11007                 }
11008
11009               if (start > end)
11010                 {
11011                   /* Inverted range entries are invalid.  */
11012                   complaint (&symfile_complaints,
11013                              _("Invalid .debug_ranges data "
11014                                "(inverted range)"));
11015                   return;
11016                 }
11017
11018               /* Empty range entries have no effect.  */
11019               if (start == end)
11020                 continue;
11021
11022               start += base + baseaddr;
11023               end += base + baseaddr;
11024
11025               /* A not-uncommon case of bad debug info.
11026                  Don't pollute the addrmap with bad data.  */
11027               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11028                 {
11029                   complaint (&symfile_complaints,
11030                              _(".debug_ranges entry has start address of zero"
11031                                " [in module %s]"), objfile->name);
11032                   continue;
11033                 }
11034
11035               record_block_range (block, start, end - 1);
11036             }
11037         }
11038     }
11039 }
11040
11041 /* Check whether the producer field indicates either of GCC < 4.6, or the
11042    Intel C/C++ compiler, and cache the result in CU.  */
11043
11044 static void
11045 check_producer (struct dwarf2_cu *cu)
11046 {
11047   const char *cs;
11048   int major, minor, release;
11049
11050   if (cu->producer == NULL)
11051     {
11052       /* For unknown compilers expect their behavior is DWARF version
11053          compliant.
11054
11055          GCC started to support .debug_types sections by -gdwarf-4 since
11056          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11057          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11058          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11059          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11060     }
11061   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11062     {
11063       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11064
11065       cs = &cu->producer[strlen ("GNU ")];
11066       while (*cs && !isdigit (*cs))
11067         cs++;
11068       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11069         {
11070           /* Not recognized as GCC.  */
11071         }
11072       else
11073         {
11074           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11075           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11076         }
11077     }
11078   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11079     cu->producer_is_icc = 1;
11080   else
11081     {
11082       /* For other non-GCC compilers, expect their behavior is DWARF version
11083          compliant.  */
11084     }
11085
11086   cu->checked_producer = 1;
11087 }
11088
11089 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11090    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11091    during 4.6.0 experimental.  */
11092
11093 static int
11094 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11095 {
11096   if (!cu->checked_producer)
11097     check_producer (cu);
11098
11099   return cu->producer_is_gxx_lt_4_6;
11100 }
11101
11102 /* Return the default accessibility type if it is not overriden by
11103    DW_AT_accessibility.  */
11104
11105 static enum dwarf_access_attribute
11106 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11107 {
11108   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11109     {
11110       /* The default DWARF 2 accessibility for members is public, the default
11111          accessibility for inheritance is private.  */
11112
11113       if (die->tag != DW_TAG_inheritance)
11114         return DW_ACCESS_public;
11115       else
11116         return DW_ACCESS_private;
11117     }
11118   else
11119     {
11120       /* DWARF 3+ defines the default accessibility a different way.  The same
11121          rules apply now for DW_TAG_inheritance as for the members and it only
11122          depends on the container kind.  */
11123
11124       if (die->parent->tag == DW_TAG_class_type)
11125         return DW_ACCESS_private;
11126       else
11127         return DW_ACCESS_public;
11128     }
11129 }
11130
11131 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11132    offset.  If the attribute was not found return 0, otherwise return
11133    1.  If it was found but could not properly be handled, set *OFFSET
11134    to 0.  */
11135
11136 static int
11137 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11138                              LONGEST *offset)
11139 {
11140   struct attribute *attr;
11141
11142   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11143   if (attr != NULL)
11144     {
11145       *offset = 0;
11146
11147       /* Note that we do not check for a section offset first here.
11148          This is because DW_AT_data_member_location is new in DWARF 4,
11149          so if we see it, we can assume that a constant form is really
11150          a constant and not a section offset.  */
11151       if (attr_form_is_constant (attr))
11152         *offset = dwarf2_get_attr_constant_value (attr, 0);
11153       else if (attr_form_is_section_offset (attr))
11154         dwarf2_complex_location_expr_complaint ();
11155       else if (attr_form_is_block (attr))
11156         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11157       else
11158         dwarf2_complex_location_expr_complaint ();
11159
11160       return 1;
11161     }
11162
11163   return 0;
11164 }
11165
11166 /* Add an aggregate field to the field list.  */
11167
11168 static void
11169 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11170                   struct dwarf2_cu *cu)
11171 {
11172   struct objfile *objfile = cu->objfile;
11173   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11174   struct nextfield *new_field;
11175   struct attribute *attr;
11176   struct field *fp;
11177   const char *fieldname = "";
11178
11179   /* Allocate a new field list entry and link it in.  */
11180   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11181   make_cleanup (xfree, new_field);
11182   memset (new_field, 0, sizeof (struct nextfield));
11183
11184   if (die->tag == DW_TAG_inheritance)
11185     {
11186       new_field->next = fip->baseclasses;
11187       fip->baseclasses = new_field;
11188     }
11189   else
11190     {
11191       new_field->next = fip->fields;
11192       fip->fields = new_field;
11193     }
11194   fip->nfields++;
11195
11196   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11197   if (attr)
11198     new_field->accessibility = DW_UNSND (attr);
11199   else
11200     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11201   if (new_field->accessibility != DW_ACCESS_public)
11202     fip->non_public_fields = 1;
11203
11204   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11205   if (attr)
11206     new_field->virtuality = DW_UNSND (attr);
11207   else
11208     new_field->virtuality = DW_VIRTUALITY_none;
11209
11210   fp = &new_field->field;
11211
11212   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11213     {
11214       LONGEST offset;
11215
11216       /* Data member other than a C++ static data member.  */
11217
11218       /* Get type of field.  */
11219       fp->type = die_type (die, cu);
11220
11221       SET_FIELD_BITPOS (*fp, 0);
11222
11223       /* Get bit size of field (zero if none).  */
11224       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11225       if (attr)
11226         {
11227           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11228         }
11229       else
11230         {
11231           FIELD_BITSIZE (*fp) = 0;
11232         }
11233
11234       /* Get bit offset of field.  */
11235       if (handle_data_member_location (die, cu, &offset))
11236         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11237       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11238       if (attr)
11239         {
11240           if (gdbarch_bits_big_endian (gdbarch))
11241             {
11242               /* For big endian bits, the DW_AT_bit_offset gives the
11243                  additional bit offset from the MSB of the containing
11244                  anonymous object to the MSB of the field.  We don't
11245                  have to do anything special since we don't need to
11246                  know the size of the anonymous object.  */
11247               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11248             }
11249           else
11250             {
11251               /* For little endian bits, compute the bit offset to the
11252                  MSB of the anonymous object, subtract off the number of
11253                  bits from the MSB of the field to the MSB of the
11254                  object, and then subtract off the number of bits of
11255                  the field itself.  The result is the bit offset of
11256                  the LSB of the field.  */
11257               int anonymous_size;
11258               int bit_offset = DW_UNSND (attr);
11259
11260               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11261               if (attr)
11262                 {
11263                   /* The size of the anonymous object containing
11264                      the bit field is explicit, so use the
11265                      indicated size (in bytes).  */
11266                   anonymous_size = DW_UNSND (attr);
11267                 }
11268               else
11269                 {
11270                   /* The size of the anonymous object containing
11271                      the bit field must be inferred from the type
11272                      attribute of the data member containing the
11273                      bit field.  */
11274                   anonymous_size = TYPE_LENGTH (fp->type);
11275                 }
11276               SET_FIELD_BITPOS (*fp,
11277                                 (FIELD_BITPOS (*fp)
11278                                  + anonymous_size * bits_per_byte
11279                                  - bit_offset - FIELD_BITSIZE (*fp)));
11280             }
11281         }
11282
11283       /* Get name of field.  */
11284       fieldname = dwarf2_name (die, cu);
11285       if (fieldname == NULL)
11286         fieldname = "";
11287
11288       /* The name is already allocated along with this objfile, so we don't
11289          need to duplicate it for the type.  */
11290       fp->name = fieldname;
11291
11292       /* Change accessibility for artificial fields (e.g. virtual table
11293          pointer or virtual base class pointer) to private.  */
11294       if (dwarf2_attr (die, DW_AT_artificial, cu))
11295         {
11296           FIELD_ARTIFICIAL (*fp) = 1;
11297           new_field->accessibility = DW_ACCESS_private;
11298           fip->non_public_fields = 1;
11299         }
11300     }
11301   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11302     {
11303       /* C++ static member.  */
11304
11305       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11306          is a declaration, but all versions of G++ as of this writing
11307          (so through at least 3.2.1) incorrectly generate
11308          DW_TAG_variable tags.  */
11309
11310       const char *physname;
11311
11312       /* Get name of field.  */
11313       fieldname = dwarf2_name (die, cu);
11314       if (fieldname == NULL)
11315         return;
11316
11317       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11318       if (attr
11319           /* Only create a symbol if this is an external value.
11320              new_symbol checks this and puts the value in the global symbol
11321              table, which we want.  If it is not external, new_symbol
11322              will try to put the value in cu->list_in_scope which is wrong.  */
11323           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11324         {
11325           /* A static const member, not much different than an enum as far as
11326              we're concerned, except that we can support more types.  */
11327           new_symbol (die, NULL, cu);
11328         }
11329
11330       /* Get physical name.  */
11331       physname = dwarf2_physname (fieldname, die, cu);
11332
11333       /* The name is already allocated along with this objfile, so we don't
11334          need to duplicate it for the type.  */
11335       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11336       FIELD_TYPE (*fp) = die_type (die, cu);
11337       FIELD_NAME (*fp) = fieldname;
11338     }
11339   else if (die->tag == DW_TAG_inheritance)
11340     {
11341       LONGEST offset;
11342
11343       /* C++ base class field.  */
11344       if (handle_data_member_location (die, cu, &offset))
11345         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11346       FIELD_BITSIZE (*fp) = 0;
11347       FIELD_TYPE (*fp) = die_type (die, cu);
11348       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11349       fip->nbaseclasses++;
11350     }
11351 }
11352
11353 /* Add a typedef defined in the scope of the FIP's class.  */
11354
11355 static void
11356 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11357                     struct dwarf2_cu *cu)
11358 {
11359   struct objfile *objfile = cu->objfile;
11360   struct typedef_field_list *new_field;
11361   struct attribute *attr;
11362   struct typedef_field *fp;
11363   char *fieldname = "";
11364
11365   /* Allocate a new field list entry and link it in.  */
11366   new_field = xzalloc (sizeof (*new_field));
11367   make_cleanup (xfree, new_field);
11368
11369   gdb_assert (die->tag == DW_TAG_typedef);
11370
11371   fp = &new_field->field;
11372
11373   /* Get name of field.  */
11374   fp->name = dwarf2_name (die, cu);
11375   if (fp->name == NULL)
11376     return;
11377
11378   fp->type = read_type_die (die, cu);
11379
11380   new_field->next = fip->typedef_field_list;
11381   fip->typedef_field_list = new_field;
11382   fip->typedef_field_list_count++;
11383 }
11384
11385 /* Create the vector of fields, and attach it to the type.  */
11386
11387 static void
11388 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11389                               struct dwarf2_cu *cu)
11390 {
11391   int nfields = fip->nfields;
11392
11393   /* Record the field count, allocate space for the array of fields,
11394      and create blank accessibility bitfields if necessary.  */
11395   TYPE_NFIELDS (type) = nfields;
11396   TYPE_FIELDS (type) = (struct field *)
11397     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11398   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11399
11400   if (fip->non_public_fields && cu->language != language_ada)
11401     {
11402       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11403
11404       TYPE_FIELD_PRIVATE_BITS (type) =
11405         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11406       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11407
11408       TYPE_FIELD_PROTECTED_BITS (type) =
11409         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11410       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11411
11412       TYPE_FIELD_IGNORE_BITS (type) =
11413         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11414       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11415     }
11416
11417   /* If the type has baseclasses, allocate and clear a bit vector for
11418      TYPE_FIELD_VIRTUAL_BITS.  */
11419   if (fip->nbaseclasses && cu->language != language_ada)
11420     {
11421       int num_bytes = B_BYTES (fip->nbaseclasses);
11422       unsigned char *pointer;
11423
11424       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11425       pointer = TYPE_ALLOC (type, num_bytes);
11426       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11427       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11428       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11429     }
11430
11431   /* Copy the saved-up fields into the field vector.  Start from the head of
11432      the list, adding to the tail of the field array, so that they end up in
11433      the same order in the array in which they were added to the list.  */
11434   while (nfields-- > 0)
11435     {
11436       struct nextfield *fieldp;
11437
11438       if (fip->fields)
11439         {
11440           fieldp = fip->fields;
11441           fip->fields = fieldp->next;
11442         }
11443       else
11444         {
11445           fieldp = fip->baseclasses;
11446           fip->baseclasses = fieldp->next;
11447         }
11448
11449       TYPE_FIELD (type, nfields) = fieldp->field;
11450       switch (fieldp->accessibility)
11451         {
11452         case DW_ACCESS_private:
11453           if (cu->language != language_ada)
11454             SET_TYPE_FIELD_PRIVATE (type, nfields);
11455           break;
11456
11457         case DW_ACCESS_protected:
11458           if (cu->language != language_ada)
11459             SET_TYPE_FIELD_PROTECTED (type, nfields);
11460           break;
11461
11462         case DW_ACCESS_public:
11463           break;
11464
11465         default:
11466           /* Unknown accessibility.  Complain and treat it as public.  */
11467           {
11468             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11469                        fieldp->accessibility);
11470           }
11471           break;
11472         }
11473       if (nfields < fip->nbaseclasses)
11474         {
11475           switch (fieldp->virtuality)
11476             {
11477             case DW_VIRTUALITY_virtual:
11478             case DW_VIRTUALITY_pure_virtual:
11479               if (cu->language == language_ada)
11480                 error (_("unexpected virtuality in component of Ada type"));
11481               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11482               break;
11483             }
11484         }
11485     }
11486 }
11487
11488 /* Return true if this member function is a constructor, false
11489    otherwise.  */
11490
11491 static int
11492 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11493 {
11494   const char *fieldname;
11495   const char *typename;
11496   int len;
11497
11498   if (die->parent == NULL)
11499     return 0;
11500
11501   if (die->parent->tag != DW_TAG_structure_type
11502       && die->parent->tag != DW_TAG_union_type
11503       && die->parent->tag != DW_TAG_class_type)
11504     return 0;
11505
11506   fieldname = dwarf2_name (die, cu);
11507   typename = dwarf2_name (die->parent, cu);
11508   if (fieldname == NULL || typename == NULL)
11509     return 0;
11510
11511   len = strlen (fieldname);
11512   return (strncmp (fieldname, typename, len) == 0
11513           && (typename[len] == '\0' || typename[len] == '<'));
11514 }
11515
11516 /* Add a member function to the proper fieldlist.  */
11517
11518 static void
11519 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11520                       struct type *type, struct dwarf2_cu *cu)
11521 {
11522   struct objfile *objfile = cu->objfile;
11523   struct attribute *attr;
11524   struct fnfieldlist *flp;
11525   int i;
11526   struct fn_field *fnp;
11527   const char *fieldname;
11528   struct nextfnfield *new_fnfield;
11529   struct type *this_type;
11530   enum dwarf_access_attribute accessibility;
11531
11532   if (cu->language == language_ada)
11533     error (_("unexpected member function in Ada type"));
11534
11535   /* Get name of member function.  */
11536   fieldname = dwarf2_name (die, cu);
11537   if (fieldname == NULL)
11538     return;
11539
11540   /* Look up member function name in fieldlist.  */
11541   for (i = 0; i < fip->nfnfields; i++)
11542     {
11543       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11544         break;
11545     }
11546
11547   /* Create new list element if necessary.  */
11548   if (i < fip->nfnfields)
11549     flp = &fip->fnfieldlists[i];
11550   else
11551     {
11552       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11553         {
11554           fip->fnfieldlists = (struct fnfieldlist *)
11555             xrealloc (fip->fnfieldlists,
11556                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11557                       * sizeof (struct fnfieldlist));
11558           if (fip->nfnfields == 0)
11559             make_cleanup (free_current_contents, &fip->fnfieldlists);
11560         }
11561       flp = &fip->fnfieldlists[fip->nfnfields];
11562       flp->name = fieldname;
11563       flp->length = 0;
11564       flp->head = NULL;
11565       i = fip->nfnfields++;
11566     }
11567
11568   /* Create a new member function field and chain it to the field list
11569      entry.  */
11570   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11571   make_cleanup (xfree, new_fnfield);
11572   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11573   new_fnfield->next = flp->head;
11574   flp->head = new_fnfield;
11575   flp->length++;
11576
11577   /* Fill in the member function field info.  */
11578   fnp = &new_fnfield->fnfield;
11579
11580   /* Delay processing of the physname until later.  */
11581   if (cu->language == language_cplus || cu->language == language_java)
11582     {
11583       add_to_method_list (type, i, flp->length - 1, fieldname,
11584                           die, cu);
11585     }
11586   else
11587     {
11588       const char *physname = dwarf2_physname (fieldname, die, cu);
11589       fnp->physname = physname ? physname : "";
11590     }
11591
11592   fnp->type = alloc_type (objfile);
11593   this_type = read_type_die (die, cu);
11594   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11595     {
11596       int nparams = TYPE_NFIELDS (this_type);
11597
11598       /* TYPE is the domain of this method, and THIS_TYPE is the type
11599            of the method itself (TYPE_CODE_METHOD).  */
11600       smash_to_method_type (fnp->type, type,
11601                             TYPE_TARGET_TYPE (this_type),
11602                             TYPE_FIELDS (this_type),
11603                             TYPE_NFIELDS (this_type),
11604                             TYPE_VARARGS (this_type));
11605
11606       /* Handle static member functions.
11607          Dwarf2 has no clean way to discern C++ static and non-static
11608          member functions.  G++ helps GDB by marking the first
11609          parameter for non-static member functions (which is the this
11610          pointer) as artificial.  We obtain this information from
11611          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11612       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11613         fnp->voffset = VOFFSET_STATIC;
11614     }
11615   else
11616     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11617                dwarf2_full_name (fieldname, die, cu));
11618
11619   /* Get fcontext from DW_AT_containing_type if present.  */
11620   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11621     fnp->fcontext = die_containing_type (die, cu);
11622
11623   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11624      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11625
11626   /* Get accessibility.  */
11627   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11628   if (attr)
11629     accessibility = DW_UNSND (attr);
11630   else
11631     accessibility = dwarf2_default_access_attribute (die, cu);
11632   switch (accessibility)
11633     {
11634     case DW_ACCESS_private:
11635       fnp->is_private = 1;
11636       break;
11637     case DW_ACCESS_protected:
11638       fnp->is_protected = 1;
11639       break;
11640     }
11641
11642   /* Check for artificial methods.  */
11643   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11644   if (attr && DW_UNSND (attr) != 0)
11645     fnp->is_artificial = 1;
11646
11647   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11648
11649   /* Get index in virtual function table if it is a virtual member
11650      function.  For older versions of GCC, this is an offset in the
11651      appropriate virtual table, as specified by DW_AT_containing_type.
11652      For everyone else, it is an expression to be evaluated relative
11653      to the object address.  */
11654
11655   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11656   if (attr)
11657     {
11658       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11659         {
11660           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11661             {
11662               /* Old-style GCC.  */
11663               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11664             }
11665           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11666                    || (DW_BLOCK (attr)->size > 1
11667                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11668                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11669             {
11670               struct dwarf_block blk;
11671               int offset;
11672
11673               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11674                         ? 1 : 2);
11675               blk.size = DW_BLOCK (attr)->size - offset;
11676               blk.data = DW_BLOCK (attr)->data + offset;
11677               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11678               if ((fnp->voffset % cu->header.addr_size) != 0)
11679                 dwarf2_complex_location_expr_complaint ();
11680               else
11681                 fnp->voffset /= cu->header.addr_size;
11682               fnp->voffset += 2;
11683             }
11684           else
11685             dwarf2_complex_location_expr_complaint ();
11686
11687           if (!fnp->fcontext)
11688             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11689         }
11690       else if (attr_form_is_section_offset (attr))
11691         {
11692           dwarf2_complex_location_expr_complaint ();
11693         }
11694       else
11695         {
11696           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11697                                                  fieldname);
11698         }
11699     }
11700   else
11701     {
11702       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11703       if (attr && DW_UNSND (attr))
11704         {
11705           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11706           complaint (&symfile_complaints,
11707                      _("Member function \"%s\" (offset %d) is virtual "
11708                        "but the vtable offset is not specified"),
11709                      fieldname, die->offset.sect_off);
11710           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11711           TYPE_CPLUS_DYNAMIC (type) = 1;
11712         }
11713     }
11714 }
11715
11716 /* Create the vector of member function fields, and attach it to the type.  */
11717
11718 static void
11719 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11720                                  struct dwarf2_cu *cu)
11721 {
11722   struct fnfieldlist *flp;
11723   int i;
11724
11725   if (cu->language == language_ada)
11726     error (_("unexpected member functions in Ada type"));
11727
11728   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11729   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11730     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11731
11732   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11733     {
11734       struct nextfnfield *nfp = flp->head;
11735       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11736       int k;
11737
11738       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11739       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11740       fn_flp->fn_fields = (struct fn_field *)
11741         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11742       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11743         fn_flp->fn_fields[k] = nfp->fnfield;
11744     }
11745
11746   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11747 }
11748
11749 /* Returns non-zero if NAME is the name of a vtable member in CU's
11750    language, zero otherwise.  */
11751 static int
11752 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11753 {
11754   static const char vptr[] = "_vptr";
11755   static const char vtable[] = "vtable";
11756
11757   /* Look for the C++ and Java forms of the vtable.  */
11758   if ((cu->language == language_java
11759        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11760        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11761        && is_cplus_marker (name[sizeof (vptr) - 1])))
11762     return 1;
11763
11764   return 0;
11765 }
11766
11767 /* GCC outputs unnamed structures that are really pointers to member
11768    functions, with the ABI-specified layout.  If TYPE describes
11769    such a structure, smash it into a member function type.
11770
11771    GCC shouldn't do this; it should just output pointer to member DIEs.
11772    This is GCC PR debug/28767.  */
11773
11774 static void
11775 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11776 {
11777   struct type *pfn_type, *domain_type, *new_type;
11778
11779   /* Check for a structure with no name and two children.  */
11780   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11781     return;
11782
11783   /* Check for __pfn and __delta members.  */
11784   if (TYPE_FIELD_NAME (type, 0) == NULL
11785       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11786       || TYPE_FIELD_NAME (type, 1) == NULL
11787       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11788     return;
11789
11790   /* Find the type of the method.  */
11791   pfn_type = TYPE_FIELD_TYPE (type, 0);
11792   if (pfn_type == NULL
11793       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11794       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11795     return;
11796
11797   /* Look for the "this" argument.  */
11798   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11799   if (TYPE_NFIELDS (pfn_type) == 0
11800       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11801       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11802     return;
11803
11804   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11805   new_type = alloc_type (objfile);
11806   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11807                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11808                         TYPE_VARARGS (pfn_type));
11809   smash_to_methodptr_type (type, new_type);
11810 }
11811
11812 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11813    (icc).  */
11814
11815 static int
11816 producer_is_icc (struct dwarf2_cu *cu)
11817 {
11818   if (!cu->checked_producer)
11819     check_producer (cu);
11820
11821   return cu->producer_is_icc;
11822 }
11823
11824 /* Called when we find the DIE that starts a structure or union scope
11825    (definition) to create a type for the structure or union.  Fill in
11826    the type's name and general properties; the members will not be
11827    processed until process_structure_scope.
11828
11829    NOTE: we need to call these functions regardless of whether or not the
11830    DIE has a DW_AT_name attribute, since it might be an anonymous
11831    structure or union.  This gets the type entered into our set of
11832    user defined types.
11833
11834    However, if the structure is incomplete (an opaque struct/union)
11835    then suppress creating a symbol table entry for it since gdb only
11836    wants to find the one with the complete definition.  Note that if
11837    it is complete, we just call new_symbol, which does it's own
11838    checking about whether the struct/union is anonymous or not (and
11839    suppresses creating a symbol table entry itself).  */
11840
11841 static struct type *
11842 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11843 {
11844   struct objfile *objfile = cu->objfile;
11845   struct type *type;
11846   struct attribute *attr;
11847   const char *name;
11848
11849   /* If the definition of this type lives in .debug_types, read that type.
11850      Don't follow DW_AT_specification though, that will take us back up
11851      the chain and we want to go down.  */
11852   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11853   if (attr)
11854     {
11855       type = get_DW_AT_signature_type (die, attr, cu);
11856
11857       /* The type's CU may not be the same as CU.
11858          Ensure TYPE is recorded with CU in die_type_hash.  */
11859       return set_die_type (die, type, cu);
11860     }
11861
11862   type = alloc_type (objfile);
11863   INIT_CPLUS_SPECIFIC (type);
11864
11865   name = dwarf2_name (die, cu);
11866   if (name != NULL)
11867     {
11868       if (cu->language == language_cplus
11869           || cu->language == language_java)
11870         {
11871           const char *full_name = dwarf2_full_name (name, die, cu);
11872
11873           /* dwarf2_full_name might have already finished building the DIE's
11874              type.  If so, there is no need to continue.  */
11875           if (get_die_type (die, cu) != NULL)
11876             return get_die_type (die, cu);
11877
11878           TYPE_TAG_NAME (type) = full_name;
11879           if (die->tag == DW_TAG_structure_type
11880               || die->tag == DW_TAG_class_type)
11881             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11882         }
11883       else
11884         {
11885           /* The name is already allocated along with this objfile, so
11886              we don't need to duplicate it for the type.  */
11887           TYPE_TAG_NAME (type) = name;
11888           if (die->tag == DW_TAG_class_type)
11889             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11890         }
11891     }
11892
11893   if (die->tag == DW_TAG_structure_type)
11894     {
11895       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11896     }
11897   else if (die->tag == DW_TAG_union_type)
11898     {
11899       TYPE_CODE (type) = TYPE_CODE_UNION;
11900     }
11901   else
11902     {
11903       TYPE_CODE (type) = TYPE_CODE_CLASS;
11904     }
11905
11906   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11907     TYPE_DECLARED_CLASS (type) = 1;
11908
11909   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11910   if (attr)
11911     {
11912       TYPE_LENGTH (type) = DW_UNSND (attr);
11913     }
11914   else
11915     {
11916       TYPE_LENGTH (type) = 0;
11917     }
11918
11919   if (producer_is_icc (cu))
11920     {
11921       /* ICC does not output the required DW_AT_declaration
11922          on incomplete types, but gives them a size of zero.  */
11923     }
11924   else
11925     TYPE_STUB_SUPPORTED (type) = 1;
11926
11927   if (die_is_declaration (die, cu))
11928     TYPE_STUB (type) = 1;
11929   else if (attr == NULL && die->child == NULL
11930            && producer_is_realview (cu->producer))
11931     /* RealView does not output the required DW_AT_declaration
11932        on incomplete types.  */
11933     TYPE_STUB (type) = 1;
11934
11935   /* We need to add the type field to the die immediately so we don't
11936      infinitely recurse when dealing with pointers to the structure
11937      type within the structure itself.  */
11938   set_die_type (die, type, cu);
11939
11940   /* set_die_type should be already done.  */
11941   set_descriptive_type (type, die, cu);
11942
11943   return type;
11944 }
11945
11946 /* Finish creating a structure or union type, including filling in
11947    its members and creating a symbol for it.  */
11948
11949 static void
11950 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11951 {
11952   struct objfile *objfile = cu->objfile;
11953   struct die_info *child_die = die->child;
11954   struct type *type;
11955
11956   type = get_die_type (die, cu);
11957   if (type == NULL)
11958     type = read_structure_type (die, cu);
11959
11960   if (die->child != NULL && ! die_is_declaration (die, cu))
11961     {
11962       struct field_info fi;
11963       struct die_info *child_die;
11964       VEC (symbolp) *template_args = NULL;
11965       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11966
11967       memset (&fi, 0, sizeof (struct field_info));
11968
11969       child_die = die->child;
11970
11971       while (child_die && child_die->tag)
11972         {
11973           if (child_die->tag == DW_TAG_member
11974               || child_die->tag == DW_TAG_variable)
11975             {
11976               /* NOTE: carlton/2002-11-05: A C++ static data member
11977                  should be a DW_TAG_member that is a declaration, but
11978                  all versions of G++ as of this writing (so through at
11979                  least 3.2.1) incorrectly generate DW_TAG_variable
11980                  tags for them instead.  */
11981               dwarf2_add_field (&fi, child_die, cu);
11982             }
11983           else if (child_die->tag == DW_TAG_subprogram)
11984             {
11985               /* C++ member function.  */
11986               dwarf2_add_member_fn (&fi, child_die, type, cu);
11987             }
11988           else if (child_die->tag == DW_TAG_inheritance)
11989             {
11990               /* C++ base class field.  */
11991               dwarf2_add_field (&fi, child_die, cu);
11992             }
11993           else if (child_die->tag == DW_TAG_typedef)
11994             dwarf2_add_typedef (&fi, child_die, cu);
11995           else if (child_die->tag == DW_TAG_template_type_param
11996                    || child_die->tag == DW_TAG_template_value_param)
11997             {
11998               struct symbol *arg = new_symbol (child_die, NULL, cu);
11999
12000               if (arg != NULL)
12001                 VEC_safe_push (symbolp, template_args, arg);
12002             }
12003
12004           child_die = sibling_die (child_die);
12005         }
12006
12007       /* Attach template arguments to type.  */
12008       if (! VEC_empty (symbolp, template_args))
12009         {
12010           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12011           TYPE_N_TEMPLATE_ARGUMENTS (type)
12012             = VEC_length (symbolp, template_args);
12013           TYPE_TEMPLATE_ARGUMENTS (type)
12014             = obstack_alloc (&objfile->objfile_obstack,
12015                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12016                               * sizeof (struct symbol *)));
12017           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12018                   VEC_address (symbolp, template_args),
12019                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12020                    * sizeof (struct symbol *)));
12021           VEC_free (symbolp, template_args);
12022         }
12023
12024       /* Attach fields and member functions to the type.  */
12025       if (fi.nfields)
12026         dwarf2_attach_fields_to_type (&fi, type, cu);
12027       if (fi.nfnfields)
12028         {
12029           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12030
12031           /* Get the type which refers to the base class (possibly this
12032              class itself) which contains the vtable pointer for the current
12033              class from the DW_AT_containing_type attribute.  This use of
12034              DW_AT_containing_type is a GNU extension.  */
12035
12036           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12037             {
12038               struct type *t = die_containing_type (die, cu);
12039
12040               TYPE_VPTR_BASETYPE (type) = t;
12041               if (type == t)
12042                 {
12043                   int i;
12044
12045                   /* Our own class provides vtbl ptr.  */
12046                   for (i = TYPE_NFIELDS (t) - 1;
12047                        i >= TYPE_N_BASECLASSES (t);
12048                        --i)
12049                     {
12050                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12051
12052                       if (is_vtable_name (fieldname, cu))
12053                         {
12054                           TYPE_VPTR_FIELDNO (type) = i;
12055                           break;
12056                         }
12057                     }
12058
12059                   /* Complain if virtual function table field not found.  */
12060                   if (i < TYPE_N_BASECLASSES (t))
12061                     complaint (&symfile_complaints,
12062                                _("virtual function table pointer "
12063                                  "not found when defining class '%s'"),
12064                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12065                                "");
12066                 }
12067               else
12068                 {
12069                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12070                 }
12071             }
12072           else if (cu->producer
12073                    && strncmp (cu->producer,
12074                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12075             {
12076               /* The IBM XLC compiler does not provide direct indication
12077                  of the containing type, but the vtable pointer is
12078                  always named __vfp.  */
12079
12080               int i;
12081
12082               for (i = TYPE_NFIELDS (type) - 1;
12083                    i >= TYPE_N_BASECLASSES (type);
12084                    --i)
12085                 {
12086                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12087                     {
12088                       TYPE_VPTR_FIELDNO (type) = i;
12089                       TYPE_VPTR_BASETYPE (type) = type;
12090                       break;
12091                     }
12092                 }
12093             }
12094         }
12095
12096       /* Copy fi.typedef_field_list linked list elements content into the
12097          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12098       if (fi.typedef_field_list)
12099         {
12100           int i = fi.typedef_field_list_count;
12101
12102           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12103           TYPE_TYPEDEF_FIELD_ARRAY (type)
12104             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12105           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12106
12107           /* Reverse the list order to keep the debug info elements order.  */
12108           while (--i >= 0)
12109             {
12110               struct typedef_field *dest, *src;
12111
12112               dest = &TYPE_TYPEDEF_FIELD (type, i);
12113               src = &fi.typedef_field_list->field;
12114               fi.typedef_field_list = fi.typedef_field_list->next;
12115               *dest = *src;
12116             }
12117         }
12118
12119       do_cleanups (back_to);
12120
12121       if (HAVE_CPLUS_STRUCT (type))
12122         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12123     }
12124
12125   quirk_gcc_member_function_pointer (type, objfile);
12126
12127   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12128      snapshots) has been known to create a die giving a declaration
12129      for a class that has, as a child, a die giving a definition for a
12130      nested class.  So we have to process our children even if the
12131      current die is a declaration.  Normally, of course, a declaration
12132      won't have any children at all.  */
12133
12134   while (child_die != NULL && child_die->tag)
12135     {
12136       if (child_die->tag == DW_TAG_member
12137           || child_die->tag == DW_TAG_variable
12138           || child_die->tag == DW_TAG_inheritance
12139           || child_die->tag == DW_TAG_template_value_param
12140           || child_die->tag == DW_TAG_template_type_param)
12141         {
12142           /* Do nothing.  */
12143         }
12144       else
12145         process_die (child_die, cu);
12146
12147       child_die = sibling_die (child_die);
12148     }
12149
12150   /* Do not consider external references.  According to the DWARF standard,
12151      these DIEs are identified by the fact that they have no byte_size
12152      attribute, and a declaration attribute.  */
12153   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12154       || !die_is_declaration (die, cu))
12155     new_symbol (die, type, cu);
12156 }
12157
12158 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12159    complete the type's fields yet, or create any symbols.  */
12160
12161 static struct type *
12162 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12163 {
12164   struct objfile *objfile = cu->objfile;
12165   struct type *type;
12166   struct attribute *attr;
12167   const char *name;
12168
12169   /* If the definition of this type lives in .debug_types, read that type.
12170      Don't follow DW_AT_specification though, that will take us back up
12171      the chain and we want to go down.  */
12172   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12173   if (attr)
12174     {
12175       type = get_DW_AT_signature_type (die, attr, cu);
12176
12177       /* The type's CU may not be the same as CU.
12178          Ensure TYPE is recorded with CU in die_type_hash.  */
12179       return set_die_type (die, type, cu);
12180     }
12181
12182   type = alloc_type (objfile);
12183
12184   TYPE_CODE (type) = TYPE_CODE_ENUM;
12185   name = dwarf2_full_name (NULL, die, cu);
12186   if (name != NULL)
12187     TYPE_TAG_NAME (type) = name;
12188
12189   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12190   if (attr)
12191     {
12192       TYPE_LENGTH (type) = DW_UNSND (attr);
12193     }
12194   else
12195     {
12196       TYPE_LENGTH (type) = 0;
12197     }
12198
12199   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12200      declared as private in the package spec, and then defined only
12201      inside the package body.  Such types are known as Taft Amendment
12202      Types.  When another package uses such a type, an incomplete DIE
12203      may be generated by the compiler.  */
12204   if (die_is_declaration (die, cu))
12205     TYPE_STUB (type) = 1;
12206
12207   return set_die_type (die, type, cu);
12208 }
12209
12210 /* Given a pointer to a die which begins an enumeration, process all
12211    the dies that define the members of the enumeration, and create the
12212    symbol for the enumeration type.
12213
12214    NOTE: We reverse the order of the element list.  */
12215
12216 static void
12217 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12218 {
12219   struct type *this_type;
12220
12221   this_type = get_die_type (die, cu);
12222   if (this_type == NULL)
12223     this_type = read_enumeration_type (die, cu);
12224
12225   if (die->child != NULL)
12226     {
12227       struct die_info *child_die;
12228       struct symbol *sym;
12229       struct field *fields = NULL;
12230       int num_fields = 0;
12231       int unsigned_enum = 1;
12232       const char *name;
12233       int flag_enum = 1;
12234       ULONGEST mask = 0;
12235
12236       child_die = die->child;
12237       while (child_die && child_die->tag)
12238         {
12239           if (child_die->tag != DW_TAG_enumerator)
12240             {
12241               process_die (child_die, cu);
12242             }
12243           else
12244             {
12245               name = dwarf2_name (child_die, cu);
12246               if (name)
12247                 {
12248                   sym = new_symbol (child_die, this_type, cu);
12249                   if (SYMBOL_VALUE (sym) < 0)
12250                     {
12251                       unsigned_enum = 0;
12252                       flag_enum = 0;
12253                     }
12254                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12255                     flag_enum = 0;
12256                   else
12257                     mask |= SYMBOL_VALUE (sym);
12258
12259                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12260                     {
12261                       fields = (struct field *)
12262                         xrealloc (fields,
12263                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12264                                   * sizeof (struct field));
12265                     }
12266
12267                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12268                   FIELD_TYPE (fields[num_fields]) = NULL;
12269                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12270                   FIELD_BITSIZE (fields[num_fields]) = 0;
12271
12272                   num_fields++;
12273                 }
12274             }
12275
12276           child_die = sibling_die (child_die);
12277         }
12278
12279       if (num_fields)
12280         {
12281           TYPE_NFIELDS (this_type) = num_fields;
12282           TYPE_FIELDS (this_type) = (struct field *)
12283             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12284           memcpy (TYPE_FIELDS (this_type), fields,
12285                   sizeof (struct field) * num_fields);
12286           xfree (fields);
12287         }
12288       if (unsigned_enum)
12289         TYPE_UNSIGNED (this_type) = 1;
12290       if (flag_enum)
12291         TYPE_FLAG_ENUM (this_type) = 1;
12292     }
12293
12294   /* If we are reading an enum from a .debug_types unit, and the enum
12295      is a declaration, and the enum is not the signatured type in the
12296      unit, then we do not want to add a symbol for it.  Adding a
12297      symbol would in some cases obscure the true definition of the
12298      enum, giving users an incomplete type when the definition is
12299      actually available.  Note that we do not want to do this for all
12300      enums which are just declarations, because C++0x allows forward
12301      enum declarations.  */
12302   if (cu->per_cu->is_debug_types
12303       && die_is_declaration (die, cu))
12304     {
12305       struct signatured_type *sig_type;
12306
12307       sig_type = (struct signatured_type *) cu->per_cu;
12308       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12309       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12310         return;
12311     }
12312
12313   new_symbol (die, this_type, cu);
12314 }
12315
12316 /* Extract all information from a DW_TAG_array_type DIE and put it in
12317    the DIE's type field.  For now, this only handles one dimensional
12318    arrays.  */
12319
12320 static struct type *
12321 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12322 {
12323   struct objfile *objfile = cu->objfile;
12324   struct die_info *child_die;
12325   struct type *type;
12326   struct type *element_type, *range_type, *index_type;
12327   struct type **range_types = NULL;
12328   struct attribute *attr;
12329   int ndim = 0;
12330   struct cleanup *back_to;
12331   const char *name;
12332
12333   element_type = die_type (die, cu);
12334
12335   /* The die_type call above may have already set the type for this DIE.  */
12336   type = get_die_type (die, cu);
12337   if (type)
12338     return type;
12339
12340   /* Irix 6.2 native cc creates array types without children for
12341      arrays with unspecified length.  */
12342   if (die->child == NULL)
12343     {
12344       index_type = objfile_type (objfile)->builtin_int;
12345       range_type = create_range_type (NULL, index_type, 0, -1);
12346       type = create_array_type (NULL, element_type, range_type);
12347       return set_die_type (die, type, cu);
12348     }
12349
12350   back_to = make_cleanup (null_cleanup, NULL);
12351   child_die = die->child;
12352   while (child_die && child_die->tag)
12353     {
12354       if (child_die->tag == DW_TAG_subrange_type)
12355         {
12356           struct type *child_type = read_type_die (child_die, cu);
12357
12358           if (child_type != NULL)
12359             {
12360               /* The range type was succesfully read.  Save it for the
12361                  array type creation.  */
12362               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12363                 {
12364                   range_types = (struct type **)
12365                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12366                               * sizeof (struct type *));
12367                   if (ndim == 0)
12368                     make_cleanup (free_current_contents, &range_types);
12369                 }
12370               range_types[ndim++] = child_type;
12371             }
12372         }
12373       child_die = sibling_die (child_die);
12374     }
12375
12376   /* Dwarf2 dimensions are output from left to right, create the
12377      necessary array types in backwards order.  */
12378
12379   type = element_type;
12380
12381   if (read_array_order (die, cu) == DW_ORD_col_major)
12382     {
12383       int i = 0;
12384
12385       while (i < ndim)
12386         type = create_array_type (NULL, type, range_types[i++]);
12387     }
12388   else
12389     {
12390       while (ndim-- > 0)
12391         type = create_array_type (NULL, type, range_types[ndim]);
12392     }
12393
12394   /* Understand Dwarf2 support for vector types (like they occur on
12395      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12396      array type.  This is not part of the Dwarf2/3 standard yet, but a
12397      custom vendor extension.  The main difference between a regular
12398      array and the vector variant is that vectors are passed by value
12399      to functions.  */
12400   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12401   if (attr)
12402     make_vector_type (type);
12403
12404   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12405      implementation may choose to implement triple vectors using this
12406      attribute.  */
12407   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12408   if (attr)
12409     {
12410       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12411         TYPE_LENGTH (type) = DW_UNSND (attr);
12412       else
12413         complaint (&symfile_complaints,
12414                    _("DW_AT_byte_size for array type smaller "
12415                      "than the total size of elements"));
12416     }
12417
12418   name = dwarf2_name (die, cu);
12419   if (name)
12420     TYPE_NAME (type) = name;
12421
12422   /* Install the type in the die.  */
12423   set_die_type (die, type, cu);
12424
12425   /* set_die_type should be already done.  */
12426   set_descriptive_type (type, die, cu);
12427
12428   do_cleanups (back_to);
12429
12430   return type;
12431 }
12432
12433 static enum dwarf_array_dim_ordering
12434 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12435 {
12436   struct attribute *attr;
12437
12438   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12439
12440   if (attr) return DW_SND (attr);
12441
12442   /* GNU F77 is a special case, as at 08/2004 array type info is the
12443      opposite order to the dwarf2 specification, but data is still
12444      laid out as per normal fortran.
12445
12446      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12447      version checking.  */
12448
12449   if (cu->language == language_fortran
12450       && cu->producer && strstr (cu->producer, "GNU F77"))
12451     {
12452       return DW_ORD_row_major;
12453     }
12454
12455   switch (cu->language_defn->la_array_ordering)
12456     {
12457     case array_column_major:
12458       return DW_ORD_col_major;
12459     case array_row_major:
12460     default:
12461       return DW_ORD_row_major;
12462     };
12463 }
12464
12465 /* Extract all information from a DW_TAG_set_type DIE and put it in
12466    the DIE's type field.  */
12467
12468 static struct type *
12469 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12470 {
12471   struct type *domain_type, *set_type;
12472   struct attribute *attr;
12473
12474   domain_type = die_type (die, cu);
12475
12476   /* The die_type call above may have already set the type for this DIE.  */
12477   set_type = get_die_type (die, cu);
12478   if (set_type)
12479     return set_type;
12480
12481   set_type = create_set_type (NULL, domain_type);
12482
12483   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12484   if (attr)
12485     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12486
12487   return set_die_type (die, set_type, cu);
12488 }
12489
12490 /* A helper for read_common_block that creates a locexpr baton.
12491    SYM is the symbol which we are marking as computed.
12492    COMMON_DIE is the DIE for the common block.
12493    COMMON_LOC is the location expression attribute for the common
12494    block itself.
12495    MEMBER_LOC is the location expression attribute for the particular
12496    member of the common block that we are processing.
12497    CU is the CU from which the above come.  */
12498
12499 static void
12500 mark_common_block_symbol_computed (struct symbol *sym,
12501                                    struct die_info *common_die,
12502                                    struct attribute *common_loc,
12503                                    struct attribute *member_loc,
12504                                    struct dwarf2_cu *cu)
12505 {
12506   struct objfile *objfile = dwarf2_per_objfile->objfile;
12507   struct dwarf2_locexpr_baton *baton;
12508   gdb_byte *ptr;
12509   unsigned int cu_off;
12510   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12511   LONGEST offset = 0;
12512
12513   gdb_assert (common_loc && member_loc);
12514   gdb_assert (attr_form_is_block (common_loc));
12515   gdb_assert (attr_form_is_block (member_loc)
12516               || attr_form_is_constant (member_loc));
12517
12518   baton = obstack_alloc (&objfile->objfile_obstack,
12519                          sizeof (struct dwarf2_locexpr_baton));
12520   baton->per_cu = cu->per_cu;
12521   gdb_assert (baton->per_cu);
12522
12523   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12524
12525   if (attr_form_is_constant (member_loc))
12526     {
12527       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12528       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12529     }
12530   else
12531     baton->size += DW_BLOCK (member_loc)->size;
12532
12533   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12534   baton->data = ptr;
12535
12536   *ptr++ = DW_OP_call4;
12537   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12538   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12539   ptr += 4;
12540
12541   if (attr_form_is_constant (member_loc))
12542     {
12543       *ptr++ = DW_OP_addr;
12544       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12545       ptr += cu->header.addr_size;
12546     }
12547   else
12548     {
12549       /* We have to copy the data here, because DW_OP_call4 will only
12550          use a DW_AT_location attribute.  */
12551       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12552       ptr += DW_BLOCK (member_loc)->size;
12553     }
12554
12555   *ptr++ = DW_OP_plus;
12556   gdb_assert (ptr - baton->data == baton->size);
12557
12558   SYMBOL_LOCATION_BATON (sym) = baton;
12559   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12560 }
12561
12562 /* Create appropriate locally-scoped variables for all the
12563    DW_TAG_common_block entries.  Also create a struct common_block
12564    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12565    is used to sepate the common blocks name namespace from regular
12566    variable names.  */
12567
12568 static void
12569 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12570 {
12571   struct attribute *attr;
12572
12573   attr = dwarf2_attr (die, DW_AT_location, cu);
12574   if (attr)
12575     {
12576       /* Support the .debug_loc offsets.  */
12577       if (attr_form_is_block (attr))
12578         {
12579           /* Ok.  */
12580         }
12581       else if (attr_form_is_section_offset (attr))
12582         {
12583           dwarf2_complex_location_expr_complaint ();
12584           attr = NULL;
12585         }
12586       else
12587         {
12588           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12589                                                  "common block member");
12590           attr = NULL;
12591         }
12592     }
12593
12594   if (die->child != NULL)
12595     {
12596       struct objfile *objfile = cu->objfile;
12597       struct die_info *child_die;
12598       size_t n_entries = 0, size;
12599       struct common_block *common_block;
12600       struct symbol *sym;
12601
12602       for (child_die = die->child;
12603            child_die && child_die->tag;
12604            child_die = sibling_die (child_die))
12605         ++n_entries;
12606
12607       size = (sizeof (struct common_block)
12608               + (n_entries - 1) * sizeof (struct symbol *));
12609       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12610       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12611       common_block->n_entries = 0;
12612
12613       for (child_die = die->child;
12614            child_die && child_die->tag;
12615            child_die = sibling_die (child_die))
12616         {
12617           /* Create the symbol in the DW_TAG_common_block block in the current
12618              symbol scope.  */
12619           sym = new_symbol (child_die, NULL, cu);
12620           if (sym != NULL)
12621             {
12622               struct attribute *member_loc;
12623
12624               common_block->contents[common_block->n_entries++] = sym;
12625
12626               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12627                                         cu);
12628               if (member_loc)
12629                 {
12630                   /* GDB has handled this for a long time, but it is
12631                      not specified by DWARF.  It seems to have been
12632                      emitted by gfortran at least as recently as:
12633                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12634                   complaint (&symfile_complaints,
12635                              _("Variable in common block has "
12636                                "DW_AT_data_member_location "
12637                                "- DIE at 0x%x [in module %s]"),
12638                              child_die->offset.sect_off, cu->objfile->name);
12639
12640                   if (attr_form_is_section_offset (member_loc))
12641                     dwarf2_complex_location_expr_complaint ();
12642                   else if (attr_form_is_constant (member_loc)
12643                            || attr_form_is_block (member_loc))
12644                     {
12645                       if (attr)
12646                         mark_common_block_symbol_computed (sym, die, attr,
12647                                                            member_loc, cu);
12648                     }
12649                   else
12650                     dwarf2_complex_location_expr_complaint ();
12651                 }
12652             }
12653         }
12654
12655       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12656       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12657     }
12658 }
12659
12660 /* Create a type for a C++ namespace.  */
12661
12662 static struct type *
12663 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12664 {
12665   struct objfile *objfile = cu->objfile;
12666   const char *previous_prefix, *name;
12667   int is_anonymous;
12668   struct type *type;
12669
12670   /* For extensions, reuse the type of the original namespace.  */
12671   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12672     {
12673       struct die_info *ext_die;
12674       struct dwarf2_cu *ext_cu = cu;
12675
12676       ext_die = dwarf2_extension (die, &ext_cu);
12677       type = read_type_die (ext_die, ext_cu);
12678
12679       /* EXT_CU may not be the same as CU.
12680          Ensure TYPE is recorded with CU in die_type_hash.  */
12681       return set_die_type (die, type, cu);
12682     }
12683
12684   name = namespace_name (die, &is_anonymous, cu);
12685
12686   /* Now build the name of the current namespace.  */
12687
12688   previous_prefix = determine_prefix (die, cu);
12689   if (previous_prefix[0] != '\0')
12690     name = typename_concat (&objfile->objfile_obstack,
12691                             previous_prefix, name, 0, cu);
12692
12693   /* Create the type.  */
12694   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12695                     objfile);
12696   TYPE_NAME (type) = name;
12697   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12698
12699   return set_die_type (die, type, cu);
12700 }
12701
12702 /* Read a C++ namespace.  */
12703
12704 static void
12705 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12706 {
12707   struct objfile *objfile = cu->objfile;
12708   int is_anonymous;
12709
12710   /* Add a symbol associated to this if we haven't seen the namespace
12711      before.  Also, add a using directive if it's an anonymous
12712      namespace.  */
12713
12714   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12715     {
12716       struct type *type;
12717
12718       type = read_type_die (die, cu);
12719       new_symbol (die, type, cu);
12720
12721       namespace_name (die, &is_anonymous, cu);
12722       if (is_anonymous)
12723         {
12724           const char *previous_prefix = determine_prefix (die, cu);
12725
12726           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12727                                   NULL, NULL, 0, &objfile->objfile_obstack);
12728         }
12729     }
12730
12731   if (die->child != NULL)
12732     {
12733       struct die_info *child_die = die->child;
12734
12735       while (child_die && child_die->tag)
12736         {
12737           process_die (child_die, cu);
12738           child_die = sibling_die (child_die);
12739         }
12740     }
12741 }
12742
12743 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12744    imported module.  Still we need that type as local Fortran "use ... only"
12745    declaration imports depend on the created type in determine_prefix.  */
12746
12747 static struct type *
12748 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12749 {
12750   struct objfile *objfile = cu->objfile;
12751   const char *module_name;
12752   struct type *type;
12753
12754   module_name = dwarf2_name (die, cu);
12755   if (!module_name)
12756     complaint (&symfile_complaints,
12757                _("DW_TAG_module has no name, offset 0x%x"),
12758                die->offset.sect_off);
12759   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12760
12761   /* determine_prefix uses TYPE_TAG_NAME.  */
12762   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12763
12764   return set_die_type (die, type, cu);
12765 }
12766
12767 /* Read a Fortran module.  */
12768
12769 static void
12770 read_module (struct die_info *die, struct dwarf2_cu *cu)
12771 {
12772   struct die_info *child_die = die->child;
12773
12774   while (child_die && child_die->tag)
12775     {
12776       process_die (child_die, cu);
12777       child_die = sibling_die (child_die);
12778     }
12779 }
12780
12781 /* Return the name of the namespace represented by DIE.  Set
12782    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12783    namespace.  */
12784
12785 static const char *
12786 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12787 {
12788   struct die_info *current_die;
12789   const char *name = NULL;
12790
12791   /* Loop through the extensions until we find a name.  */
12792
12793   for (current_die = die;
12794        current_die != NULL;
12795        current_die = dwarf2_extension (die, &cu))
12796     {
12797       name = dwarf2_name (current_die, cu);
12798       if (name != NULL)
12799         break;
12800     }
12801
12802   /* Is it an anonymous namespace?  */
12803
12804   *is_anonymous = (name == NULL);
12805   if (*is_anonymous)
12806     name = CP_ANONYMOUS_NAMESPACE_STR;
12807
12808   return name;
12809 }
12810
12811 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12812    the user defined type vector.  */
12813
12814 static struct type *
12815 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12816 {
12817   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12818   struct comp_unit_head *cu_header = &cu->header;
12819   struct type *type;
12820   struct attribute *attr_byte_size;
12821   struct attribute *attr_address_class;
12822   int byte_size, addr_class;
12823   struct type *target_type;
12824
12825   target_type = die_type (die, cu);
12826
12827   /* The die_type call above may have already set the type for this DIE.  */
12828   type = get_die_type (die, cu);
12829   if (type)
12830     return type;
12831
12832   type = lookup_pointer_type (target_type);
12833
12834   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12835   if (attr_byte_size)
12836     byte_size = DW_UNSND (attr_byte_size);
12837   else
12838     byte_size = cu_header->addr_size;
12839
12840   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12841   if (attr_address_class)
12842     addr_class = DW_UNSND (attr_address_class);
12843   else
12844     addr_class = DW_ADDR_none;
12845
12846   /* If the pointer size or address class is different than the
12847      default, create a type variant marked as such and set the
12848      length accordingly.  */
12849   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12850     {
12851       if (gdbarch_address_class_type_flags_p (gdbarch))
12852         {
12853           int type_flags;
12854
12855           type_flags = gdbarch_address_class_type_flags
12856                          (gdbarch, byte_size, addr_class);
12857           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12858                       == 0);
12859           type = make_type_with_address_space (type, type_flags);
12860         }
12861       else if (TYPE_LENGTH (type) != byte_size)
12862         {
12863           complaint (&symfile_complaints,
12864                      _("invalid pointer size %d"), byte_size);
12865         }
12866       else
12867         {
12868           /* Should we also complain about unhandled address classes?  */
12869         }
12870     }
12871
12872   TYPE_LENGTH (type) = byte_size;
12873   return set_die_type (die, type, cu);
12874 }
12875
12876 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12877    the user defined type vector.  */
12878
12879 static struct type *
12880 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12881 {
12882   struct type *type;
12883   struct type *to_type;
12884   struct type *domain;
12885
12886   to_type = die_type (die, cu);
12887   domain = die_containing_type (die, cu);
12888
12889   /* The calls above may have already set the type for this DIE.  */
12890   type = get_die_type (die, cu);
12891   if (type)
12892     return type;
12893
12894   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12895     type = lookup_methodptr_type (to_type);
12896   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12897     {
12898       struct type *new_type = alloc_type (cu->objfile);
12899
12900       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12901                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12902                             TYPE_VARARGS (to_type));
12903       type = lookup_methodptr_type (new_type);
12904     }
12905   else
12906     type = lookup_memberptr_type (to_type, domain);
12907
12908   return set_die_type (die, type, cu);
12909 }
12910
12911 /* Extract all information from a DW_TAG_reference_type DIE and add to
12912    the user defined type vector.  */
12913
12914 static struct type *
12915 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12916 {
12917   struct comp_unit_head *cu_header = &cu->header;
12918   struct type *type, *target_type;
12919   struct attribute *attr;
12920
12921   target_type = die_type (die, cu);
12922
12923   /* The die_type call above may have already set the type for this DIE.  */
12924   type = get_die_type (die, cu);
12925   if (type)
12926     return type;
12927
12928   type = lookup_reference_type (target_type);
12929   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12930   if (attr)
12931     {
12932       TYPE_LENGTH (type) = DW_UNSND (attr);
12933     }
12934   else
12935     {
12936       TYPE_LENGTH (type) = cu_header->addr_size;
12937     }
12938   return set_die_type (die, type, cu);
12939 }
12940
12941 static struct type *
12942 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12943 {
12944   struct type *base_type, *cv_type;
12945
12946   base_type = die_type (die, cu);
12947
12948   /* The die_type call above may have already set the type for this DIE.  */
12949   cv_type = get_die_type (die, cu);
12950   if (cv_type)
12951     return cv_type;
12952
12953   /* In case the const qualifier is applied to an array type, the element type
12954      is so qualified, not the array type (section 6.7.3 of C99).  */
12955   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12956     {
12957       struct type *el_type, *inner_array;
12958
12959       base_type = copy_type (base_type);
12960       inner_array = base_type;
12961
12962       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12963         {
12964           TYPE_TARGET_TYPE (inner_array) =
12965             copy_type (TYPE_TARGET_TYPE (inner_array));
12966           inner_array = TYPE_TARGET_TYPE (inner_array);
12967         }
12968
12969       el_type = TYPE_TARGET_TYPE (inner_array);
12970       TYPE_TARGET_TYPE (inner_array) =
12971         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12972
12973       return set_die_type (die, base_type, cu);
12974     }
12975
12976   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12977   return set_die_type (die, cv_type, cu);
12978 }
12979
12980 static struct type *
12981 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12982 {
12983   struct type *base_type, *cv_type;
12984
12985   base_type = die_type (die, cu);
12986
12987   /* The die_type call above may have already set the type for this DIE.  */
12988   cv_type = get_die_type (die, cu);
12989   if (cv_type)
12990     return cv_type;
12991
12992   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12993   return set_die_type (die, cv_type, cu);
12994 }
12995
12996 /* Handle DW_TAG_restrict_type.  */
12997
12998 static struct type *
12999 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13000 {
13001   struct type *base_type, *cv_type;
13002
13003   base_type = die_type (die, cu);
13004
13005   /* The die_type call above may have already set the type for this DIE.  */
13006   cv_type = get_die_type (die, cu);
13007   if (cv_type)
13008     return cv_type;
13009
13010   cv_type = make_restrict_type (base_type);
13011   return set_die_type (die, cv_type, cu);
13012 }
13013
13014 /* Extract all information from a DW_TAG_string_type DIE and add to
13015    the user defined type vector.  It isn't really a user defined type,
13016    but it behaves like one, with other DIE's using an AT_user_def_type
13017    attribute to reference it.  */
13018
13019 static struct type *
13020 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13021 {
13022   struct objfile *objfile = cu->objfile;
13023   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13024   struct type *type, *range_type, *index_type, *char_type;
13025   struct attribute *attr;
13026   unsigned int length;
13027
13028   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13029   if (attr)
13030     {
13031       length = DW_UNSND (attr);
13032     }
13033   else
13034     {
13035       /* Check for the DW_AT_byte_size attribute.  */
13036       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13037       if (attr)
13038         {
13039           length = DW_UNSND (attr);
13040         }
13041       else
13042         {
13043           length = 1;
13044         }
13045     }
13046
13047   index_type = objfile_type (objfile)->builtin_int;
13048   range_type = create_range_type (NULL, index_type, 1, length);
13049   char_type = language_string_char_type (cu->language_defn, gdbarch);
13050   type = create_string_type (NULL, char_type, range_type);
13051
13052   return set_die_type (die, type, cu);
13053 }
13054
13055 /* Assuming that DIE corresponds to a function, returns nonzero
13056    if the function is prototyped.  */
13057
13058 static int
13059 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13060 {
13061   struct attribute *attr;
13062
13063   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13064   if (attr && (DW_UNSND (attr) != 0))
13065     return 1;
13066
13067   /* The DWARF standard implies that the DW_AT_prototyped attribute
13068      is only meaninful for C, but the concept also extends to other
13069      languages that allow unprototyped functions (Eg: Objective C).
13070      For all other languages, assume that functions are always
13071      prototyped.  */
13072   if (cu->language != language_c
13073       && cu->language != language_objc
13074       && cu->language != language_opencl)
13075     return 1;
13076
13077   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13078      prototyped and unprototyped functions; default to prototyped,
13079      since that is more common in modern code (and RealView warns
13080      about unprototyped functions).  */
13081   if (producer_is_realview (cu->producer))
13082     return 1;
13083
13084   return 0;
13085 }
13086
13087 /* Handle DIES due to C code like:
13088
13089    struct foo
13090    {
13091    int (*funcp)(int a, long l);
13092    int b;
13093    };
13094
13095    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13096
13097 static struct type *
13098 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13099 {
13100   struct objfile *objfile = cu->objfile;
13101   struct type *type;            /* Type that this function returns.  */
13102   struct type *ftype;           /* Function that returns above type.  */
13103   struct attribute *attr;
13104
13105   type = die_type (die, cu);
13106
13107   /* The die_type call above may have already set the type for this DIE.  */
13108   ftype = get_die_type (die, cu);
13109   if (ftype)
13110     return ftype;
13111
13112   ftype = lookup_function_type (type);
13113
13114   if (prototyped_function_p (die, cu))
13115     TYPE_PROTOTYPED (ftype) = 1;
13116
13117   /* Store the calling convention in the type if it's available in
13118      the subroutine die.  Otherwise set the calling convention to
13119      the default value DW_CC_normal.  */
13120   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13121   if (attr)
13122     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13123   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13124     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13125   else
13126     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13127
13128   /* We need to add the subroutine type to the die immediately so
13129      we don't infinitely recurse when dealing with parameters
13130      declared as the same subroutine type.  */
13131   set_die_type (die, ftype, cu);
13132
13133   if (die->child != NULL)
13134     {
13135       struct type *void_type = objfile_type (objfile)->builtin_void;
13136       struct die_info *child_die;
13137       int nparams, iparams;
13138
13139       /* Count the number of parameters.
13140          FIXME: GDB currently ignores vararg functions, but knows about
13141          vararg member functions.  */
13142       nparams = 0;
13143       child_die = die->child;
13144       while (child_die && child_die->tag)
13145         {
13146           if (child_die->tag == DW_TAG_formal_parameter)
13147             nparams++;
13148           else if (child_die->tag == DW_TAG_unspecified_parameters)
13149             TYPE_VARARGS (ftype) = 1;
13150           child_die = sibling_die (child_die);
13151         }
13152
13153       /* Allocate storage for parameters and fill them in.  */
13154       TYPE_NFIELDS (ftype) = nparams;
13155       TYPE_FIELDS (ftype) = (struct field *)
13156         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13157
13158       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13159          even if we error out during the parameters reading below.  */
13160       for (iparams = 0; iparams < nparams; iparams++)
13161         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13162
13163       iparams = 0;
13164       child_die = die->child;
13165       while (child_die && child_die->tag)
13166         {
13167           if (child_die->tag == DW_TAG_formal_parameter)
13168             {
13169               struct type *arg_type;
13170
13171               /* DWARF version 2 has no clean way to discern C++
13172                  static and non-static member functions.  G++ helps
13173                  GDB by marking the first parameter for non-static
13174                  member functions (which is the this pointer) as
13175                  artificial.  We pass this information to
13176                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13177
13178                  DWARF version 3 added DW_AT_object_pointer, which GCC
13179                  4.5 does not yet generate.  */
13180               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13181               if (attr)
13182                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13183               else
13184                 {
13185                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13186
13187                   /* GCC/43521: In java, the formal parameter
13188                      "this" is sometimes not marked with DW_AT_artificial.  */
13189                   if (cu->language == language_java)
13190                     {
13191                       const char *name = dwarf2_name (child_die, cu);
13192
13193                       if (name && !strcmp (name, "this"))
13194                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13195                     }
13196                 }
13197               arg_type = die_type (child_die, cu);
13198
13199               /* RealView does not mark THIS as const, which the testsuite
13200                  expects.  GCC marks THIS as const in method definitions,
13201                  but not in the class specifications (GCC PR 43053).  */
13202               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13203                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13204                 {
13205                   int is_this = 0;
13206                   struct dwarf2_cu *arg_cu = cu;
13207                   const char *name = dwarf2_name (child_die, cu);
13208
13209                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13210                   if (attr)
13211                     {
13212                       /* If the compiler emits this, use it.  */
13213                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13214                         is_this = 1;
13215                     }
13216                   else if (name && strcmp (name, "this") == 0)
13217                     /* Function definitions will have the argument names.  */
13218                     is_this = 1;
13219                   else if (name == NULL && iparams == 0)
13220                     /* Declarations may not have the names, so like
13221                        elsewhere in GDB, assume an artificial first
13222                        argument is "this".  */
13223                     is_this = 1;
13224
13225                   if (is_this)
13226                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13227                                              arg_type, 0);
13228                 }
13229
13230               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13231               iparams++;
13232             }
13233           child_die = sibling_die (child_die);
13234         }
13235     }
13236
13237   return ftype;
13238 }
13239
13240 static struct type *
13241 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13242 {
13243   struct objfile *objfile = cu->objfile;
13244   const char *name = NULL;
13245   struct type *this_type, *target_type;
13246
13247   name = dwarf2_full_name (NULL, die, cu);
13248   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13249                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13250   TYPE_NAME (this_type) = name;
13251   set_die_type (die, this_type, cu);
13252   target_type = die_type (die, cu);
13253   if (target_type != this_type)
13254     TYPE_TARGET_TYPE (this_type) = target_type;
13255   else
13256     {
13257       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13258          spec and cause infinite loops in GDB.  */
13259       complaint (&symfile_complaints,
13260                  _("Self-referential DW_TAG_typedef "
13261                    "- DIE at 0x%x [in module %s]"),
13262                  die->offset.sect_off, objfile->name);
13263       TYPE_TARGET_TYPE (this_type) = NULL;
13264     }
13265   return this_type;
13266 }
13267
13268 /* Find a representation of a given base type and install
13269    it in the TYPE field of the die.  */
13270
13271 static struct type *
13272 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13273 {
13274   struct objfile *objfile = cu->objfile;
13275   struct type *type;
13276   struct attribute *attr;
13277   int encoding = 0, size = 0;
13278   const char *name;
13279   enum type_code code = TYPE_CODE_INT;
13280   int type_flags = 0;
13281   struct type *target_type = NULL;
13282
13283   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13284   if (attr)
13285     {
13286       encoding = DW_UNSND (attr);
13287     }
13288   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13289   if (attr)
13290     {
13291       size = DW_UNSND (attr);
13292     }
13293   name = dwarf2_name (die, cu);
13294   if (!name)
13295     {
13296       complaint (&symfile_complaints,
13297                  _("DW_AT_name missing from DW_TAG_base_type"));
13298     }
13299
13300   switch (encoding)
13301     {
13302       case DW_ATE_address:
13303         /* Turn DW_ATE_address into a void * pointer.  */
13304         code = TYPE_CODE_PTR;
13305         type_flags |= TYPE_FLAG_UNSIGNED;
13306         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13307         break;
13308       case DW_ATE_boolean:
13309         code = TYPE_CODE_BOOL;
13310         type_flags |= TYPE_FLAG_UNSIGNED;
13311         break;
13312       case DW_ATE_complex_float:
13313         code = TYPE_CODE_COMPLEX;
13314         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13315         break;
13316       case DW_ATE_decimal_float:
13317         code = TYPE_CODE_DECFLOAT;
13318         break;
13319       case DW_ATE_float:
13320         code = TYPE_CODE_FLT;
13321         break;
13322       case DW_ATE_signed:
13323         break;
13324       case DW_ATE_unsigned:
13325         type_flags |= TYPE_FLAG_UNSIGNED;
13326         if (cu->language == language_fortran
13327             && name
13328             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13329           code = TYPE_CODE_CHAR;
13330         break;
13331       case DW_ATE_signed_char:
13332         if (cu->language == language_ada || cu->language == language_m2
13333             || cu->language == language_pascal
13334             || cu->language == language_fortran)
13335           code = TYPE_CODE_CHAR;
13336         break;
13337       case DW_ATE_unsigned_char:
13338         if (cu->language == language_ada || cu->language == language_m2
13339             || cu->language == language_pascal
13340             || cu->language == language_fortran)
13341           code = TYPE_CODE_CHAR;
13342         type_flags |= TYPE_FLAG_UNSIGNED;
13343         break;
13344       case DW_ATE_UTF:
13345         /* We just treat this as an integer and then recognize the
13346            type by name elsewhere.  */
13347         break;
13348
13349       default:
13350         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13351                    dwarf_type_encoding_name (encoding));
13352         break;
13353     }
13354
13355   type = init_type (code, size, type_flags, NULL, objfile);
13356   TYPE_NAME (type) = name;
13357   TYPE_TARGET_TYPE (type) = target_type;
13358
13359   if (name && strcmp (name, "char") == 0)
13360     TYPE_NOSIGN (type) = 1;
13361
13362   return set_die_type (die, type, cu);
13363 }
13364
13365 /* Read the given DW_AT_subrange DIE.  */
13366
13367 static struct type *
13368 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13369 {
13370   struct type *base_type, *orig_base_type;
13371   struct type *range_type;
13372   struct attribute *attr;
13373   LONGEST low, high;
13374   int low_default_is_valid;
13375   const char *name;
13376   LONGEST negative_mask;
13377
13378   orig_base_type = die_type (die, cu);
13379   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13380      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13381      creating the range type, but we use the result of check_typedef
13382      when examining properties of the type.  */
13383   base_type = check_typedef (orig_base_type);
13384
13385   /* The die_type call above may have already set the type for this DIE.  */
13386   range_type = get_die_type (die, cu);
13387   if (range_type)
13388     return range_type;
13389
13390   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13391      omitting DW_AT_lower_bound.  */
13392   switch (cu->language)
13393     {
13394     case language_c:
13395     case language_cplus:
13396       low = 0;
13397       low_default_is_valid = 1;
13398       break;
13399     case language_fortran:
13400       low = 1;
13401       low_default_is_valid = 1;
13402       break;
13403     case language_d:
13404     case language_java:
13405     case language_objc:
13406       low = 0;
13407       low_default_is_valid = (cu->header.version >= 4);
13408       break;
13409     case language_ada:
13410     case language_m2:
13411     case language_pascal:
13412       low = 1;
13413       low_default_is_valid = (cu->header.version >= 4);
13414       break;
13415     default:
13416       low = 0;
13417       low_default_is_valid = 0;
13418       break;
13419     }
13420
13421   /* FIXME: For variable sized arrays either of these could be
13422      a variable rather than a constant value.  We'll allow it,
13423      but we don't know how to handle it.  */
13424   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13425   if (attr)
13426     low = dwarf2_get_attr_constant_value (attr, low);
13427   else if (!low_default_is_valid)
13428     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13429                                       "- DIE at 0x%x [in module %s]"),
13430                die->offset.sect_off, cu->objfile->name);
13431
13432   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13433   if (attr)
13434     {
13435       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
13436         {
13437           /* GCC encodes arrays with unspecified or dynamic length
13438              with a DW_FORM_block1 attribute or a reference attribute.
13439              FIXME: GDB does not yet know how to handle dynamic
13440              arrays properly, treat them as arrays with unspecified
13441              length for now.
13442
13443              FIXME: jimb/2003-09-22: GDB does not really know
13444              how to handle arrays of unspecified length
13445              either; we just represent them as zero-length
13446              arrays.  Choose an appropriate upper bound given
13447              the lower bound we've computed above.  */
13448           high = low - 1;
13449         }
13450       else
13451         high = dwarf2_get_attr_constant_value (attr, 1);
13452     }
13453   else
13454     {
13455       attr = dwarf2_attr (die, DW_AT_count, cu);
13456       if (attr)
13457         {
13458           int count = dwarf2_get_attr_constant_value (attr, 1);
13459           high = low + count - 1;
13460         }
13461       else
13462         {
13463           /* Unspecified array length.  */
13464           high = low - 1;
13465         }
13466     }
13467
13468   /* Dwarf-2 specifications explicitly allows to create subrange types
13469      without specifying a base type.
13470      In that case, the base type must be set to the type of
13471      the lower bound, upper bound or count, in that order, if any of these
13472      three attributes references an object that has a type.
13473      If no base type is found, the Dwarf-2 specifications say that
13474      a signed integer type of size equal to the size of an address should
13475      be used.
13476      For the following C code: `extern char gdb_int [];'
13477      GCC produces an empty range DIE.
13478      FIXME: muller/2010-05-28: Possible references to object for low bound,
13479      high bound or count are not yet handled by this code.  */
13480   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13481     {
13482       struct objfile *objfile = cu->objfile;
13483       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13484       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13485       struct type *int_type = objfile_type (objfile)->builtin_int;
13486
13487       /* Test "int", "long int", and "long long int" objfile types,
13488          and select the first one having a size above or equal to the
13489          architecture address size.  */
13490       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13491         base_type = int_type;
13492       else
13493         {
13494           int_type = objfile_type (objfile)->builtin_long;
13495           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13496             base_type = int_type;
13497           else
13498             {
13499               int_type = objfile_type (objfile)->builtin_long_long;
13500               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13501                 base_type = int_type;
13502             }
13503         }
13504     }
13505
13506   negative_mask =
13507     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13508   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13509     low |= negative_mask;
13510   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13511     high |= negative_mask;
13512
13513   range_type = create_range_type (NULL, orig_base_type, low, high);
13514
13515   /* Mark arrays with dynamic length at least as an array of unspecified
13516      length.  GDB could check the boundary but before it gets implemented at
13517      least allow accessing the array elements.  */
13518   if (attr && attr_form_is_block (attr))
13519     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13520
13521   /* Ada expects an empty array on no boundary attributes.  */
13522   if (attr == NULL && cu->language != language_ada)
13523     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13524
13525   name = dwarf2_name (die, cu);
13526   if (name)
13527     TYPE_NAME (range_type) = name;
13528
13529   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13530   if (attr)
13531     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13532
13533   set_die_type (die, range_type, cu);
13534
13535   /* set_die_type should be already done.  */
13536   set_descriptive_type (range_type, die, cu);
13537
13538   return range_type;
13539 }
13540
13541 static struct type *
13542 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13543 {
13544   struct type *type;
13545
13546   /* For now, we only support the C meaning of an unspecified type: void.  */
13547
13548   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13549   TYPE_NAME (type) = dwarf2_name (die, cu);
13550
13551   return set_die_type (die, type, cu);
13552 }
13553
13554 /* Read a single die and all its descendents.  Set the die's sibling
13555    field to NULL; set other fields in the die correctly, and set all
13556    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13557    location of the info_ptr after reading all of those dies.  PARENT
13558    is the parent of the die in question.  */
13559
13560 static struct die_info *
13561 read_die_and_children (const struct die_reader_specs *reader,
13562                        const gdb_byte *info_ptr,
13563                        const gdb_byte **new_info_ptr,
13564                        struct die_info *parent)
13565 {
13566   struct die_info *die;
13567   const gdb_byte *cur_ptr;
13568   int has_children;
13569
13570   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13571   if (die == NULL)
13572     {
13573       *new_info_ptr = cur_ptr;
13574       return NULL;
13575     }
13576   store_in_ref_table (die, reader->cu);
13577
13578   if (has_children)
13579     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13580   else
13581     {
13582       die->child = NULL;
13583       *new_info_ptr = cur_ptr;
13584     }
13585
13586   die->sibling = NULL;
13587   die->parent = parent;
13588   return die;
13589 }
13590
13591 /* Read a die, all of its descendents, and all of its siblings; set
13592    all of the fields of all of the dies correctly.  Arguments are as
13593    in read_die_and_children.  */
13594
13595 static struct die_info *
13596 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13597                          const gdb_byte *info_ptr,
13598                          const gdb_byte **new_info_ptr,
13599                          struct die_info *parent)
13600 {
13601   struct die_info *first_die, *last_sibling;
13602   const gdb_byte *cur_ptr;
13603
13604   cur_ptr = info_ptr;
13605   first_die = last_sibling = NULL;
13606
13607   while (1)
13608     {
13609       struct die_info *die
13610         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13611
13612       if (die == NULL)
13613         {
13614           *new_info_ptr = cur_ptr;
13615           return first_die;
13616         }
13617
13618       if (!first_die)
13619         first_die = die;
13620       else
13621         last_sibling->sibling = die;
13622
13623       last_sibling = die;
13624     }
13625 }
13626
13627 /* Read a die, all of its descendents, and all of its siblings; set
13628    all of the fields of all of the dies correctly.  Arguments are as
13629    in read_die_and_children.
13630    This the main entry point for reading a DIE and all its children.  */
13631
13632 static struct die_info *
13633 read_die_and_siblings (const struct die_reader_specs *reader,
13634                        const gdb_byte *info_ptr,
13635                        const gdb_byte **new_info_ptr,
13636                        struct die_info *parent)
13637 {
13638   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13639                                                   new_info_ptr, parent);
13640
13641   if (dwarf2_die_debug)
13642     {
13643       fprintf_unfiltered (gdb_stdlog,
13644                           "Read die from %s@0x%x of %s:\n",
13645                           bfd_section_name (reader->abfd,
13646                                             reader->die_section->asection),
13647                           (unsigned) (info_ptr - reader->die_section->buffer),
13648                           bfd_get_filename (reader->abfd));
13649       dump_die (die, dwarf2_die_debug);
13650     }
13651
13652   return die;
13653 }
13654
13655 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13656    attributes.
13657    The caller is responsible for filling in the extra attributes
13658    and updating (*DIEP)->num_attrs.
13659    Set DIEP to point to a newly allocated die with its information,
13660    except for its child, sibling, and parent fields.
13661    Set HAS_CHILDREN to tell whether the die has children or not.  */
13662
13663 static const gdb_byte *
13664 read_full_die_1 (const struct die_reader_specs *reader,
13665                  struct die_info **diep, const gdb_byte *info_ptr,
13666                  int *has_children, int num_extra_attrs)
13667 {
13668   unsigned int abbrev_number, bytes_read, i;
13669   sect_offset offset;
13670   struct abbrev_info *abbrev;
13671   struct die_info *die;
13672   struct dwarf2_cu *cu = reader->cu;
13673   bfd *abfd = reader->abfd;
13674
13675   offset.sect_off = info_ptr - reader->buffer;
13676   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13677   info_ptr += bytes_read;
13678   if (!abbrev_number)
13679     {
13680       *diep = NULL;
13681       *has_children = 0;
13682       return info_ptr;
13683     }
13684
13685   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13686   if (!abbrev)
13687     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13688            abbrev_number,
13689            bfd_get_filename (abfd));
13690
13691   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13692   die->offset = offset;
13693   die->tag = abbrev->tag;
13694   die->abbrev = abbrev_number;
13695
13696   /* Make the result usable.
13697      The caller needs to update num_attrs after adding the extra
13698      attributes.  */
13699   die->num_attrs = abbrev->num_attrs;
13700
13701   for (i = 0; i < abbrev->num_attrs; ++i)
13702     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13703                                info_ptr);
13704
13705   *diep = die;
13706   *has_children = abbrev->has_children;
13707   return info_ptr;
13708 }
13709
13710 /* Read a die and all its attributes.
13711    Set DIEP to point to a newly allocated die with its information,
13712    except for its child, sibling, and parent fields.
13713    Set HAS_CHILDREN to tell whether the die has children or not.  */
13714
13715 static const gdb_byte *
13716 read_full_die (const struct die_reader_specs *reader,
13717                struct die_info **diep, const gdb_byte *info_ptr,
13718                int *has_children)
13719 {
13720   const gdb_byte *result;
13721
13722   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13723
13724   if (dwarf2_die_debug)
13725     {
13726       fprintf_unfiltered (gdb_stdlog,
13727                           "Read die from %s@0x%x of %s:\n",
13728                           bfd_section_name (reader->abfd,
13729                                             reader->die_section->asection),
13730                           (unsigned) (info_ptr - reader->die_section->buffer),
13731                           bfd_get_filename (reader->abfd));
13732       dump_die (*diep, dwarf2_die_debug);
13733     }
13734
13735   return result;
13736 }
13737 \f
13738 /* Abbreviation tables.
13739
13740    In DWARF version 2, the description of the debugging information is
13741    stored in a separate .debug_abbrev section.  Before we read any
13742    dies from a section we read in all abbreviations and install them
13743    in a hash table.  */
13744
13745 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13746
13747 static struct abbrev_info *
13748 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13749 {
13750   struct abbrev_info *abbrev;
13751
13752   abbrev = (struct abbrev_info *)
13753     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13754   memset (abbrev, 0, sizeof (struct abbrev_info));
13755   return abbrev;
13756 }
13757
13758 /* Add an abbreviation to the table.  */
13759
13760 static void
13761 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13762                          unsigned int abbrev_number,
13763                          struct abbrev_info *abbrev)
13764 {
13765   unsigned int hash_number;
13766
13767   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13768   abbrev->next = abbrev_table->abbrevs[hash_number];
13769   abbrev_table->abbrevs[hash_number] = abbrev;
13770 }
13771
13772 /* Look up an abbrev in the table.
13773    Returns NULL if the abbrev is not found.  */
13774
13775 static struct abbrev_info *
13776 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13777                             unsigned int abbrev_number)
13778 {
13779   unsigned int hash_number;
13780   struct abbrev_info *abbrev;
13781
13782   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13783   abbrev = abbrev_table->abbrevs[hash_number];
13784
13785   while (abbrev)
13786     {
13787       if (abbrev->number == abbrev_number)
13788         return abbrev;
13789       abbrev = abbrev->next;
13790     }
13791   return NULL;
13792 }
13793
13794 /* Read in an abbrev table.  */
13795
13796 static struct abbrev_table *
13797 abbrev_table_read_table (struct dwarf2_section_info *section,
13798                          sect_offset offset)
13799 {
13800   struct objfile *objfile = dwarf2_per_objfile->objfile;
13801   bfd *abfd = section->asection->owner;
13802   struct abbrev_table *abbrev_table;
13803   const gdb_byte *abbrev_ptr;
13804   struct abbrev_info *cur_abbrev;
13805   unsigned int abbrev_number, bytes_read, abbrev_name;
13806   unsigned int abbrev_form;
13807   struct attr_abbrev *cur_attrs;
13808   unsigned int allocated_attrs;
13809
13810   abbrev_table = XMALLOC (struct abbrev_table);
13811   abbrev_table->offset = offset;
13812   obstack_init (&abbrev_table->abbrev_obstack);
13813   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13814                                          (ABBREV_HASH_SIZE
13815                                           * sizeof (struct abbrev_info *)));
13816   memset (abbrev_table->abbrevs, 0,
13817           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13818
13819   dwarf2_read_section (objfile, section);
13820   abbrev_ptr = section->buffer + offset.sect_off;
13821   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13822   abbrev_ptr += bytes_read;
13823
13824   allocated_attrs = ATTR_ALLOC_CHUNK;
13825   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13826
13827   /* Loop until we reach an abbrev number of 0.  */
13828   while (abbrev_number)
13829     {
13830       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13831
13832       /* read in abbrev header */
13833       cur_abbrev->number = abbrev_number;
13834       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13835       abbrev_ptr += bytes_read;
13836       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13837       abbrev_ptr += 1;
13838
13839       /* now read in declarations */
13840       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13841       abbrev_ptr += bytes_read;
13842       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13843       abbrev_ptr += bytes_read;
13844       while (abbrev_name)
13845         {
13846           if (cur_abbrev->num_attrs == allocated_attrs)
13847             {
13848               allocated_attrs += ATTR_ALLOC_CHUNK;
13849               cur_attrs
13850                 = xrealloc (cur_attrs, (allocated_attrs
13851                                         * sizeof (struct attr_abbrev)));
13852             }
13853
13854           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13855           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13856           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13857           abbrev_ptr += bytes_read;
13858           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13859           abbrev_ptr += bytes_read;
13860         }
13861
13862       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13863                                          (cur_abbrev->num_attrs
13864                                           * sizeof (struct attr_abbrev)));
13865       memcpy (cur_abbrev->attrs, cur_attrs,
13866               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13867
13868       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13869
13870       /* Get next abbreviation.
13871          Under Irix6 the abbreviations for a compilation unit are not
13872          always properly terminated with an abbrev number of 0.
13873          Exit loop if we encounter an abbreviation which we have
13874          already read (which means we are about to read the abbreviations
13875          for the next compile unit) or if the end of the abbreviation
13876          table is reached.  */
13877       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13878         break;
13879       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13880       abbrev_ptr += bytes_read;
13881       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13882         break;
13883     }
13884
13885   xfree (cur_attrs);
13886   return abbrev_table;
13887 }
13888
13889 /* Free the resources held by ABBREV_TABLE.  */
13890
13891 static void
13892 abbrev_table_free (struct abbrev_table *abbrev_table)
13893 {
13894   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13895   xfree (abbrev_table);
13896 }
13897
13898 /* Same as abbrev_table_free but as a cleanup.
13899    We pass in a pointer to the pointer to the table so that we can
13900    set the pointer to NULL when we're done.  It also simplifies
13901    build_type_unit_groups.  */
13902
13903 static void
13904 abbrev_table_free_cleanup (void *table_ptr)
13905 {
13906   struct abbrev_table **abbrev_table_ptr = table_ptr;
13907
13908   if (*abbrev_table_ptr != NULL)
13909     abbrev_table_free (*abbrev_table_ptr);
13910   *abbrev_table_ptr = NULL;
13911 }
13912
13913 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13914
13915 static void
13916 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13917                      struct dwarf2_section_info *abbrev_section)
13918 {
13919   cu->abbrev_table =
13920     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13921 }
13922
13923 /* Release the memory used by the abbrev table for a compilation unit.  */
13924
13925 static void
13926 dwarf2_free_abbrev_table (void *ptr_to_cu)
13927 {
13928   struct dwarf2_cu *cu = ptr_to_cu;
13929
13930   if (cu->abbrev_table != NULL)
13931     abbrev_table_free (cu->abbrev_table);
13932   /* Set this to NULL so that we SEGV if we try to read it later,
13933      and also because free_comp_unit verifies this is NULL.  */
13934   cu->abbrev_table = NULL;
13935 }
13936 \f
13937 /* Returns nonzero if TAG represents a type that we might generate a partial
13938    symbol for.  */
13939
13940 static int
13941 is_type_tag_for_partial (int tag)
13942 {
13943   switch (tag)
13944     {
13945 #if 0
13946     /* Some types that would be reasonable to generate partial symbols for,
13947        that we don't at present.  */
13948     case DW_TAG_array_type:
13949     case DW_TAG_file_type:
13950     case DW_TAG_ptr_to_member_type:
13951     case DW_TAG_set_type:
13952     case DW_TAG_string_type:
13953     case DW_TAG_subroutine_type:
13954 #endif
13955     case DW_TAG_base_type:
13956     case DW_TAG_class_type:
13957     case DW_TAG_interface_type:
13958     case DW_TAG_enumeration_type:
13959     case DW_TAG_structure_type:
13960     case DW_TAG_subrange_type:
13961     case DW_TAG_typedef:
13962     case DW_TAG_union_type:
13963       return 1;
13964     default:
13965       return 0;
13966     }
13967 }
13968
13969 /* Load all DIEs that are interesting for partial symbols into memory.  */
13970
13971 static struct partial_die_info *
13972 load_partial_dies (const struct die_reader_specs *reader,
13973                    const gdb_byte *info_ptr, int building_psymtab)
13974 {
13975   struct dwarf2_cu *cu = reader->cu;
13976   struct objfile *objfile = cu->objfile;
13977   struct partial_die_info *part_die;
13978   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13979   struct abbrev_info *abbrev;
13980   unsigned int bytes_read;
13981   unsigned int load_all = 0;
13982   int nesting_level = 1;
13983
13984   parent_die = NULL;
13985   last_die = NULL;
13986
13987   gdb_assert (cu->per_cu != NULL);
13988   if (cu->per_cu->load_all_dies)
13989     load_all = 1;
13990
13991   cu->partial_dies
13992     = htab_create_alloc_ex (cu->header.length / 12,
13993                             partial_die_hash,
13994                             partial_die_eq,
13995                             NULL,
13996                             &cu->comp_unit_obstack,
13997                             hashtab_obstack_allocate,
13998                             dummy_obstack_deallocate);
13999
14000   part_die = obstack_alloc (&cu->comp_unit_obstack,
14001                             sizeof (struct partial_die_info));
14002
14003   while (1)
14004     {
14005       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14006
14007       /* A NULL abbrev means the end of a series of children.  */
14008       if (abbrev == NULL)
14009         {
14010           if (--nesting_level == 0)
14011             {
14012               /* PART_DIE was probably the last thing allocated on the
14013                  comp_unit_obstack, so we could call obstack_free
14014                  here.  We don't do that because the waste is small,
14015                  and will be cleaned up when we're done with this
14016                  compilation unit.  This way, we're also more robust
14017                  against other users of the comp_unit_obstack.  */
14018               return first_die;
14019             }
14020           info_ptr += bytes_read;
14021           last_die = parent_die;
14022           parent_die = parent_die->die_parent;
14023           continue;
14024         }
14025
14026       /* Check for template arguments.  We never save these; if
14027          they're seen, we just mark the parent, and go on our way.  */
14028       if (parent_die != NULL
14029           && cu->language == language_cplus
14030           && (abbrev->tag == DW_TAG_template_type_param
14031               || abbrev->tag == DW_TAG_template_value_param))
14032         {
14033           parent_die->has_template_arguments = 1;
14034
14035           if (!load_all)
14036             {
14037               /* We don't need a partial DIE for the template argument.  */
14038               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14039               continue;
14040             }
14041         }
14042
14043       /* We only recurse into c++ subprograms looking for template arguments.
14044          Skip their other children.  */
14045       if (!load_all
14046           && cu->language == language_cplus
14047           && parent_die != NULL
14048           && parent_die->tag == DW_TAG_subprogram)
14049         {
14050           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14051           continue;
14052         }
14053
14054       /* Check whether this DIE is interesting enough to save.  Normally
14055          we would not be interested in members here, but there may be
14056          later variables referencing them via DW_AT_specification (for
14057          static members).  */
14058       if (!load_all
14059           && !is_type_tag_for_partial (abbrev->tag)
14060           && abbrev->tag != DW_TAG_constant
14061           && abbrev->tag != DW_TAG_enumerator
14062           && abbrev->tag != DW_TAG_subprogram
14063           && abbrev->tag != DW_TAG_lexical_block
14064           && abbrev->tag != DW_TAG_variable
14065           && abbrev->tag != DW_TAG_namespace
14066           && abbrev->tag != DW_TAG_module
14067           && abbrev->tag != DW_TAG_member
14068           && abbrev->tag != DW_TAG_imported_unit)
14069         {
14070           /* Otherwise we skip to the next sibling, if any.  */
14071           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14072           continue;
14073         }
14074
14075       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14076                                    info_ptr);
14077
14078       /* This two-pass algorithm for processing partial symbols has a
14079          high cost in cache pressure.  Thus, handle some simple cases
14080          here which cover the majority of C partial symbols.  DIEs
14081          which neither have specification tags in them, nor could have
14082          specification tags elsewhere pointing at them, can simply be
14083          processed and discarded.
14084
14085          This segment is also optional; scan_partial_symbols and
14086          add_partial_symbol will handle these DIEs if we chain
14087          them in normally.  When compilers which do not emit large
14088          quantities of duplicate debug information are more common,
14089          this code can probably be removed.  */
14090
14091       /* Any complete simple types at the top level (pretty much all
14092          of them, for a language without namespaces), can be processed
14093          directly.  */
14094       if (parent_die == NULL
14095           && part_die->has_specification == 0
14096           && part_die->is_declaration == 0
14097           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14098               || part_die->tag == DW_TAG_base_type
14099               || part_die->tag == DW_TAG_subrange_type))
14100         {
14101           if (building_psymtab && part_die->name != NULL)
14102             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14103                                  VAR_DOMAIN, LOC_TYPEDEF,
14104                                  &objfile->static_psymbols,
14105                                  0, (CORE_ADDR) 0, cu->language, objfile);
14106           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14107           continue;
14108         }
14109
14110       /* The exception for DW_TAG_typedef with has_children above is
14111          a workaround of GCC PR debug/47510.  In the case of this complaint
14112          type_name_no_tag_or_error will error on such types later.
14113
14114          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14115          it could not find the child DIEs referenced later, this is checked
14116          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14117
14118       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14119         complaint (&symfile_complaints,
14120                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14121                      "- DIE at 0x%x [in module %s]"),
14122                    part_die->offset.sect_off, objfile->name);
14123
14124       /* If we're at the second level, and we're an enumerator, and
14125          our parent has no specification (meaning possibly lives in a
14126          namespace elsewhere), then we can add the partial symbol now
14127          instead of queueing it.  */
14128       if (part_die->tag == DW_TAG_enumerator
14129           && parent_die != NULL
14130           && parent_die->die_parent == NULL
14131           && parent_die->tag == DW_TAG_enumeration_type
14132           && parent_die->has_specification == 0)
14133         {
14134           if (part_die->name == NULL)
14135             complaint (&symfile_complaints,
14136                        _("malformed enumerator DIE ignored"));
14137           else if (building_psymtab)
14138             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14139                                  VAR_DOMAIN, LOC_CONST,
14140                                  (cu->language == language_cplus
14141                                   || cu->language == language_java)
14142                                  ? &objfile->global_psymbols
14143                                  : &objfile->static_psymbols,
14144                                  0, (CORE_ADDR) 0, cu->language, objfile);
14145
14146           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14147           continue;
14148         }
14149
14150       /* We'll save this DIE so link it in.  */
14151       part_die->die_parent = parent_die;
14152       part_die->die_sibling = NULL;
14153       part_die->die_child = NULL;
14154
14155       if (last_die && last_die == parent_die)
14156         last_die->die_child = part_die;
14157       else if (last_die)
14158         last_die->die_sibling = part_die;
14159
14160       last_die = part_die;
14161
14162       if (first_die == NULL)
14163         first_die = part_die;
14164
14165       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14166          find interesting need to be in the hash table, because we
14167          also have the parent/sibling/child chains; only those that we
14168          might refer to by offset later during partial symbol reading.
14169
14170          For now this means things that might have be the target of a
14171          DW_AT_specification, DW_AT_abstract_origin, or
14172          DW_AT_extension.  DW_AT_extension will refer only to
14173          namespaces; DW_AT_abstract_origin refers to functions (and
14174          many things under the function DIE, but we do not recurse
14175          into function DIEs during partial symbol reading) and
14176          possibly variables as well; DW_AT_specification refers to
14177          declarations.  Declarations ought to have the DW_AT_declaration
14178          flag.  It happens that GCC forgets to put it in sometimes, but
14179          only for functions, not for types.
14180
14181          Adding more things than necessary to the hash table is harmless
14182          except for the performance cost.  Adding too few will result in
14183          wasted time in find_partial_die, when we reread the compilation
14184          unit with load_all_dies set.  */
14185
14186       if (load_all
14187           || abbrev->tag == DW_TAG_constant
14188           || abbrev->tag == DW_TAG_subprogram
14189           || abbrev->tag == DW_TAG_variable
14190           || abbrev->tag == DW_TAG_namespace
14191           || part_die->is_declaration)
14192         {
14193           void **slot;
14194
14195           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14196                                            part_die->offset.sect_off, INSERT);
14197           *slot = part_die;
14198         }
14199
14200       part_die = obstack_alloc (&cu->comp_unit_obstack,
14201                                 sizeof (struct partial_die_info));
14202
14203       /* For some DIEs we want to follow their children (if any).  For C
14204          we have no reason to follow the children of structures; for other
14205          languages we have to, so that we can get at method physnames
14206          to infer fully qualified class names, for DW_AT_specification,
14207          and for C++ template arguments.  For C++, we also look one level
14208          inside functions to find template arguments (if the name of the
14209          function does not already contain the template arguments).
14210
14211          For Ada, we need to scan the children of subprograms and lexical
14212          blocks as well because Ada allows the definition of nested
14213          entities that could be interesting for the debugger, such as
14214          nested subprograms for instance.  */
14215       if (last_die->has_children
14216           && (load_all
14217               || last_die->tag == DW_TAG_namespace
14218               || last_die->tag == DW_TAG_module
14219               || last_die->tag == DW_TAG_enumeration_type
14220               || (cu->language == language_cplus
14221                   && last_die->tag == DW_TAG_subprogram
14222                   && (last_die->name == NULL
14223                       || strchr (last_die->name, '<') == NULL))
14224               || (cu->language != language_c
14225                   && (last_die->tag == DW_TAG_class_type
14226                       || last_die->tag == DW_TAG_interface_type
14227                       || last_die->tag == DW_TAG_structure_type
14228                       || last_die->tag == DW_TAG_union_type))
14229               || (cu->language == language_ada
14230                   && (last_die->tag == DW_TAG_subprogram
14231                       || last_die->tag == DW_TAG_lexical_block))))
14232         {
14233           nesting_level++;
14234           parent_die = last_die;
14235           continue;
14236         }
14237
14238       /* Otherwise we skip to the next sibling, if any.  */
14239       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14240
14241       /* Back to the top, do it again.  */
14242     }
14243 }
14244
14245 /* Read a minimal amount of information into the minimal die structure.  */
14246
14247 static const gdb_byte *
14248 read_partial_die (const struct die_reader_specs *reader,
14249                   struct partial_die_info *part_die,
14250                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14251                   const gdb_byte *info_ptr)
14252 {
14253   struct dwarf2_cu *cu = reader->cu;
14254   struct objfile *objfile = cu->objfile;
14255   const gdb_byte *buffer = reader->buffer;
14256   unsigned int i;
14257   struct attribute attr;
14258   int has_low_pc_attr = 0;
14259   int has_high_pc_attr = 0;
14260   int high_pc_relative = 0;
14261
14262   memset (part_die, 0, sizeof (struct partial_die_info));
14263
14264   part_die->offset.sect_off = info_ptr - buffer;
14265
14266   info_ptr += abbrev_len;
14267
14268   if (abbrev == NULL)
14269     return info_ptr;
14270
14271   part_die->tag = abbrev->tag;
14272   part_die->has_children = abbrev->has_children;
14273
14274   for (i = 0; i < abbrev->num_attrs; ++i)
14275     {
14276       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14277
14278       /* Store the data if it is of an attribute we want to keep in a
14279          partial symbol table.  */
14280       switch (attr.name)
14281         {
14282         case DW_AT_name:
14283           switch (part_die->tag)
14284             {
14285             case DW_TAG_compile_unit:
14286             case DW_TAG_partial_unit:
14287             case DW_TAG_type_unit:
14288               /* Compilation units have a DW_AT_name that is a filename, not
14289                  a source language identifier.  */
14290             case DW_TAG_enumeration_type:
14291             case DW_TAG_enumerator:
14292               /* These tags always have simple identifiers already; no need
14293                  to canonicalize them.  */
14294               part_die->name = DW_STRING (&attr);
14295               break;
14296             default:
14297               part_die->name
14298                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14299                                             &objfile->objfile_obstack);
14300               break;
14301             }
14302           break;
14303         case DW_AT_linkage_name:
14304         case DW_AT_MIPS_linkage_name:
14305           /* Note that both forms of linkage name might appear.  We
14306              assume they will be the same, and we only store the last
14307              one we see.  */
14308           if (cu->language == language_ada)
14309             part_die->name = DW_STRING (&attr);
14310           part_die->linkage_name = DW_STRING (&attr);
14311           break;
14312         case DW_AT_low_pc:
14313           has_low_pc_attr = 1;
14314           part_die->lowpc = DW_ADDR (&attr);
14315           break;
14316         case DW_AT_high_pc:
14317           has_high_pc_attr = 1;
14318           if (attr.form == DW_FORM_addr
14319               || attr.form == DW_FORM_GNU_addr_index)
14320             part_die->highpc = DW_ADDR (&attr);
14321           else
14322             {
14323               high_pc_relative = 1;
14324               part_die->highpc = DW_UNSND (&attr);
14325             }
14326           break;
14327         case DW_AT_location:
14328           /* Support the .debug_loc offsets.  */
14329           if (attr_form_is_block (&attr))
14330             {
14331                part_die->d.locdesc = DW_BLOCK (&attr);
14332             }
14333           else if (attr_form_is_section_offset (&attr))
14334             {
14335               dwarf2_complex_location_expr_complaint ();
14336             }
14337           else
14338             {
14339               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14340                                                      "partial symbol information");
14341             }
14342           break;
14343         case DW_AT_external:
14344           part_die->is_external = DW_UNSND (&attr);
14345           break;
14346         case DW_AT_declaration:
14347           part_die->is_declaration = DW_UNSND (&attr);
14348           break;
14349         case DW_AT_type:
14350           part_die->has_type = 1;
14351           break;
14352         case DW_AT_abstract_origin:
14353         case DW_AT_specification:
14354         case DW_AT_extension:
14355           part_die->has_specification = 1;
14356           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14357           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14358                                    || cu->per_cu->is_dwz);
14359           break;
14360         case DW_AT_sibling:
14361           /* Ignore absolute siblings, they might point outside of
14362              the current compile unit.  */
14363           if (attr.form == DW_FORM_ref_addr)
14364             complaint (&symfile_complaints,
14365                        _("ignoring absolute DW_AT_sibling"));
14366           else
14367             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14368           break;
14369         case DW_AT_byte_size:
14370           part_die->has_byte_size = 1;
14371           break;
14372         case DW_AT_calling_convention:
14373           /* DWARF doesn't provide a way to identify a program's source-level
14374              entry point.  DW_AT_calling_convention attributes are only meant
14375              to describe functions' calling conventions.
14376
14377              However, because it's a necessary piece of information in
14378              Fortran, and because DW_CC_program is the only piece of debugging
14379              information whose definition refers to a 'main program' at all,
14380              several compilers have begun marking Fortran main programs with
14381              DW_CC_program --- even when those functions use the standard
14382              calling conventions.
14383
14384              So until DWARF specifies a way to provide this information and
14385              compilers pick up the new representation, we'll support this
14386              practice.  */
14387           if (DW_UNSND (&attr) == DW_CC_program
14388               && cu->language == language_fortran)
14389             {
14390               set_main_name (part_die->name);
14391
14392               /* As this DIE has a static linkage the name would be difficult
14393                  to look up later.  */
14394               language_of_main = language_fortran;
14395             }
14396           break;
14397         case DW_AT_inline:
14398           if (DW_UNSND (&attr) == DW_INL_inlined
14399               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14400             part_die->may_be_inlined = 1;
14401           break;
14402
14403         case DW_AT_import:
14404           if (part_die->tag == DW_TAG_imported_unit)
14405             {
14406               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14407               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14408                                   || cu->per_cu->is_dwz);
14409             }
14410           break;
14411
14412         default:
14413           break;
14414         }
14415     }
14416
14417   if (high_pc_relative)
14418     part_die->highpc += part_die->lowpc;
14419
14420   if (has_low_pc_attr && has_high_pc_attr)
14421     {
14422       /* When using the GNU linker, .gnu.linkonce. sections are used to
14423          eliminate duplicate copies of functions and vtables and such.
14424          The linker will arbitrarily choose one and discard the others.
14425          The AT_*_pc values for such functions refer to local labels in
14426          these sections.  If the section from that file was discarded, the
14427          labels are not in the output, so the relocs get a value of 0.
14428          If this is a discarded function, mark the pc bounds as invalid,
14429          so that GDB will ignore it.  */
14430       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14431         {
14432           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14433
14434           complaint (&symfile_complaints,
14435                      _("DW_AT_low_pc %s is zero "
14436                        "for DIE at 0x%x [in module %s]"),
14437                      paddress (gdbarch, part_die->lowpc),
14438                      part_die->offset.sect_off, objfile->name);
14439         }
14440       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14441       else if (part_die->lowpc >= part_die->highpc)
14442         {
14443           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14444
14445           complaint (&symfile_complaints,
14446                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14447                        "for DIE at 0x%x [in module %s]"),
14448                      paddress (gdbarch, part_die->lowpc),
14449                      paddress (gdbarch, part_die->highpc),
14450                      part_die->offset.sect_off, objfile->name);
14451         }
14452       else
14453         part_die->has_pc_info = 1;
14454     }
14455
14456   return info_ptr;
14457 }
14458
14459 /* Find a cached partial DIE at OFFSET in CU.  */
14460
14461 static struct partial_die_info *
14462 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14463 {
14464   struct partial_die_info *lookup_die = NULL;
14465   struct partial_die_info part_die;
14466
14467   part_die.offset = offset;
14468   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14469                                     offset.sect_off);
14470
14471   return lookup_die;
14472 }
14473
14474 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14475    except in the case of .debug_types DIEs which do not reference
14476    outside their CU (they do however referencing other types via
14477    DW_FORM_ref_sig8).  */
14478
14479 static struct partial_die_info *
14480 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14481 {
14482   struct objfile *objfile = cu->objfile;
14483   struct dwarf2_per_cu_data *per_cu = NULL;
14484   struct partial_die_info *pd = NULL;
14485
14486   if (offset_in_dwz == cu->per_cu->is_dwz
14487       && offset_in_cu_p (&cu->header, offset))
14488     {
14489       pd = find_partial_die_in_comp_unit (offset, cu);
14490       if (pd != NULL)
14491         return pd;
14492       /* We missed recording what we needed.
14493          Load all dies and try again.  */
14494       per_cu = cu->per_cu;
14495     }
14496   else
14497     {
14498       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14499       if (cu->per_cu->is_debug_types)
14500         {
14501           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14502                    " external reference to offset 0x%lx [in module %s].\n"),
14503                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14504                  bfd_get_filename (objfile->obfd));
14505         }
14506       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14507                                                  objfile);
14508
14509       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14510         load_partial_comp_unit (per_cu);
14511
14512       per_cu->cu->last_used = 0;
14513       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14514     }
14515
14516   /* If we didn't find it, and not all dies have been loaded,
14517      load them all and try again.  */
14518
14519   if (pd == NULL && per_cu->load_all_dies == 0)
14520     {
14521       per_cu->load_all_dies = 1;
14522
14523       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14524          THIS_CU->cu may already be in use.  So we can't just free it and
14525          replace its DIEs with the ones we read in.  Instead, we leave those
14526          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14527          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14528          set.  */
14529       load_partial_comp_unit (per_cu);
14530
14531       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14532     }
14533
14534   if (pd == NULL)
14535     internal_error (__FILE__, __LINE__,
14536                     _("could not find partial DIE 0x%x "
14537                       "in cache [from module %s]\n"),
14538                     offset.sect_off, bfd_get_filename (objfile->obfd));
14539   return pd;
14540 }
14541
14542 /* See if we can figure out if the class lives in a namespace.  We do
14543    this by looking for a member function; its demangled name will
14544    contain namespace info, if there is any.  */
14545
14546 static void
14547 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14548                                   struct dwarf2_cu *cu)
14549 {
14550   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14551      what template types look like, because the demangler
14552      frequently doesn't give the same name as the debug info.  We
14553      could fix this by only using the demangled name to get the
14554      prefix (but see comment in read_structure_type).  */
14555
14556   struct partial_die_info *real_pdi;
14557   struct partial_die_info *child_pdi;
14558
14559   /* If this DIE (this DIE's specification, if any) has a parent, then
14560      we should not do this.  We'll prepend the parent's fully qualified
14561      name when we create the partial symbol.  */
14562
14563   real_pdi = struct_pdi;
14564   while (real_pdi->has_specification)
14565     real_pdi = find_partial_die (real_pdi->spec_offset,
14566                                  real_pdi->spec_is_dwz, cu);
14567
14568   if (real_pdi->die_parent != NULL)
14569     return;
14570
14571   for (child_pdi = struct_pdi->die_child;
14572        child_pdi != NULL;
14573        child_pdi = child_pdi->die_sibling)
14574     {
14575       if (child_pdi->tag == DW_TAG_subprogram
14576           && child_pdi->linkage_name != NULL)
14577         {
14578           char *actual_class_name
14579             = language_class_name_from_physname (cu->language_defn,
14580                                                  child_pdi->linkage_name);
14581           if (actual_class_name != NULL)
14582             {
14583               struct_pdi->name
14584                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14585                                  actual_class_name,
14586                                  strlen (actual_class_name));
14587               xfree (actual_class_name);
14588             }
14589           break;
14590         }
14591     }
14592 }
14593
14594 /* Adjust PART_DIE before generating a symbol for it.  This function
14595    may set the is_external flag or change the DIE's name.  */
14596
14597 static void
14598 fixup_partial_die (struct partial_die_info *part_die,
14599                    struct dwarf2_cu *cu)
14600 {
14601   /* Once we've fixed up a die, there's no point in doing so again.
14602      This also avoids a memory leak if we were to call
14603      guess_partial_die_structure_name multiple times.  */
14604   if (part_die->fixup_called)
14605     return;
14606
14607   /* If we found a reference attribute and the DIE has no name, try
14608      to find a name in the referred to DIE.  */
14609
14610   if (part_die->name == NULL && part_die->has_specification)
14611     {
14612       struct partial_die_info *spec_die;
14613
14614       spec_die = find_partial_die (part_die->spec_offset,
14615                                    part_die->spec_is_dwz, cu);
14616
14617       fixup_partial_die (spec_die, cu);
14618
14619       if (spec_die->name)
14620         {
14621           part_die->name = spec_die->name;
14622
14623           /* Copy DW_AT_external attribute if it is set.  */
14624           if (spec_die->is_external)
14625             part_die->is_external = spec_die->is_external;
14626         }
14627     }
14628
14629   /* Set default names for some unnamed DIEs.  */
14630
14631   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14632     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14633
14634   /* If there is no parent die to provide a namespace, and there are
14635      children, see if we can determine the namespace from their linkage
14636      name.  */
14637   if (cu->language == language_cplus
14638       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14639       && part_die->die_parent == NULL
14640       && part_die->has_children
14641       && (part_die->tag == DW_TAG_class_type
14642           || part_die->tag == DW_TAG_structure_type
14643           || part_die->tag == DW_TAG_union_type))
14644     guess_partial_die_structure_name (part_die, cu);
14645
14646   /* GCC might emit a nameless struct or union that has a linkage
14647      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14648   if (part_die->name == NULL
14649       && (part_die->tag == DW_TAG_class_type
14650           || part_die->tag == DW_TAG_interface_type
14651           || part_die->tag == DW_TAG_structure_type
14652           || part_die->tag == DW_TAG_union_type)
14653       && part_die->linkage_name != NULL)
14654     {
14655       char *demangled;
14656
14657       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14658       if (demangled)
14659         {
14660           const char *base;
14661
14662           /* Strip any leading namespaces/classes, keep only the base name.
14663              DW_AT_name for named DIEs does not contain the prefixes.  */
14664           base = strrchr (demangled, ':');
14665           if (base && base > demangled && base[-1] == ':')
14666             base++;
14667           else
14668             base = demangled;
14669
14670           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14671                                           base, strlen (base));
14672           xfree (demangled);
14673         }
14674     }
14675
14676   part_die->fixup_called = 1;
14677 }
14678
14679 /* Read an attribute value described by an attribute form.  */
14680
14681 static const gdb_byte *
14682 read_attribute_value (const struct die_reader_specs *reader,
14683                       struct attribute *attr, unsigned form,
14684                       const gdb_byte *info_ptr)
14685 {
14686   struct dwarf2_cu *cu = reader->cu;
14687   bfd *abfd = reader->abfd;
14688   struct comp_unit_head *cu_header = &cu->header;
14689   unsigned int bytes_read;
14690   struct dwarf_block *blk;
14691
14692   attr->form = form;
14693   switch (form)
14694     {
14695     case DW_FORM_ref_addr:
14696       if (cu->header.version == 2)
14697         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14698       else
14699         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14700                                        &cu->header, &bytes_read);
14701       info_ptr += bytes_read;
14702       break;
14703     case DW_FORM_GNU_ref_alt:
14704       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14705       info_ptr += bytes_read;
14706       break;
14707     case DW_FORM_addr:
14708       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14709       info_ptr += bytes_read;
14710       break;
14711     case DW_FORM_block2:
14712       blk = dwarf_alloc_block (cu);
14713       blk->size = read_2_bytes (abfd, info_ptr);
14714       info_ptr += 2;
14715       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14716       info_ptr += blk->size;
14717       DW_BLOCK (attr) = blk;
14718       break;
14719     case DW_FORM_block4:
14720       blk = dwarf_alloc_block (cu);
14721       blk->size = read_4_bytes (abfd, info_ptr);
14722       info_ptr += 4;
14723       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14724       info_ptr += blk->size;
14725       DW_BLOCK (attr) = blk;
14726       break;
14727     case DW_FORM_data2:
14728       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14729       info_ptr += 2;
14730       break;
14731     case DW_FORM_data4:
14732       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14733       info_ptr += 4;
14734       break;
14735     case DW_FORM_data8:
14736       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14737       info_ptr += 8;
14738       break;
14739     case DW_FORM_sec_offset:
14740       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14741       info_ptr += bytes_read;
14742       break;
14743     case DW_FORM_string:
14744       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14745       DW_STRING_IS_CANONICAL (attr) = 0;
14746       info_ptr += bytes_read;
14747       break;
14748     case DW_FORM_strp:
14749       if (!cu->per_cu->is_dwz)
14750         {
14751           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14752                                                    &bytes_read);
14753           DW_STRING_IS_CANONICAL (attr) = 0;
14754           info_ptr += bytes_read;
14755           break;
14756         }
14757       /* FALLTHROUGH */
14758     case DW_FORM_GNU_strp_alt:
14759       {
14760         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14761         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14762                                           &bytes_read);
14763
14764         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14765         DW_STRING_IS_CANONICAL (attr) = 0;
14766         info_ptr += bytes_read;
14767       }
14768       break;
14769     case DW_FORM_exprloc:
14770     case DW_FORM_block:
14771       blk = dwarf_alloc_block (cu);
14772       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14773       info_ptr += bytes_read;
14774       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14775       info_ptr += blk->size;
14776       DW_BLOCK (attr) = blk;
14777       break;
14778     case DW_FORM_block1:
14779       blk = dwarf_alloc_block (cu);
14780       blk->size = read_1_byte (abfd, info_ptr);
14781       info_ptr += 1;
14782       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14783       info_ptr += blk->size;
14784       DW_BLOCK (attr) = blk;
14785       break;
14786     case DW_FORM_data1:
14787       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14788       info_ptr += 1;
14789       break;
14790     case DW_FORM_flag:
14791       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14792       info_ptr += 1;
14793       break;
14794     case DW_FORM_flag_present:
14795       DW_UNSND (attr) = 1;
14796       break;
14797     case DW_FORM_sdata:
14798       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14799       info_ptr += bytes_read;
14800       break;
14801     case DW_FORM_udata:
14802       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14803       info_ptr += bytes_read;
14804       break;
14805     case DW_FORM_ref1:
14806       DW_UNSND (attr) = (cu->header.offset.sect_off
14807                          + read_1_byte (abfd, info_ptr));
14808       info_ptr += 1;
14809       break;
14810     case DW_FORM_ref2:
14811       DW_UNSND (attr) = (cu->header.offset.sect_off
14812                          + read_2_bytes (abfd, info_ptr));
14813       info_ptr += 2;
14814       break;
14815     case DW_FORM_ref4:
14816       DW_UNSND (attr) = (cu->header.offset.sect_off
14817                          + read_4_bytes (abfd, info_ptr));
14818       info_ptr += 4;
14819       break;
14820     case DW_FORM_ref8:
14821       DW_UNSND (attr) = (cu->header.offset.sect_off
14822                          + read_8_bytes (abfd, info_ptr));
14823       info_ptr += 8;
14824       break;
14825     case DW_FORM_ref_sig8:
14826       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14827       info_ptr += 8;
14828       break;
14829     case DW_FORM_ref_udata:
14830       DW_UNSND (attr) = (cu->header.offset.sect_off
14831                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14832       info_ptr += bytes_read;
14833       break;
14834     case DW_FORM_indirect:
14835       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14836       info_ptr += bytes_read;
14837       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14838       break;
14839     case DW_FORM_GNU_addr_index:
14840       if (reader->dwo_file == NULL)
14841         {
14842           /* For now flag a hard error.
14843              Later we can turn this into a complaint.  */
14844           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14845                  dwarf_form_name (form),
14846                  bfd_get_filename (abfd));
14847         }
14848       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14849       info_ptr += bytes_read;
14850       break;
14851     case DW_FORM_GNU_str_index:
14852       if (reader->dwo_file == NULL)
14853         {
14854           /* For now flag a hard error.
14855              Later we can turn this into a complaint if warranted.  */
14856           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14857                  dwarf_form_name (form),
14858                  bfd_get_filename (abfd));
14859         }
14860       {
14861         ULONGEST str_index =
14862           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14863
14864         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14865         DW_STRING_IS_CANONICAL (attr) = 0;
14866         info_ptr += bytes_read;
14867       }
14868       break;
14869     default:
14870       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14871              dwarf_form_name (form),
14872              bfd_get_filename (abfd));
14873     }
14874
14875   /* Super hack.  */
14876   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
14877     attr->form = DW_FORM_GNU_ref_alt;
14878
14879   /* We have seen instances where the compiler tried to emit a byte
14880      size attribute of -1 which ended up being encoded as an unsigned
14881      0xffffffff.  Although 0xffffffff is technically a valid size value,
14882      an object of this size seems pretty unlikely so we can relatively
14883      safely treat these cases as if the size attribute was invalid and
14884      treat them as zero by default.  */
14885   if (attr->name == DW_AT_byte_size
14886       && form == DW_FORM_data4
14887       && DW_UNSND (attr) >= 0xffffffff)
14888     {
14889       complaint
14890         (&symfile_complaints,
14891          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14892          hex_string (DW_UNSND (attr)));
14893       DW_UNSND (attr) = 0;
14894     }
14895
14896   return info_ptr;
14897 }
14898
14899 /* Read an attribute described by an abbreviated attribute.  */
14900
14901 static const gdb_byte *
14902 read_attribute (const struct die_reader_specs *reader,
14903                 struct attribute *attr, struct attr_abbrev *abbrev,
14904                 const gdb_byte *info_ptr)
14905 {
14906   attr->name = abbrev->name;
14907   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14908 }
14909
14910 /* Read dwarf information from a buffer.  */
14911
14912 static unsigned int
14913 read_1_byte (bfd *abfd, const gdb_byte *buf)
14914 {
14915   return bfd_get_8 (abfd, buf);
14916 }
14917
14918 static int
14919 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14920 {
14921   return bfd_get_signed_8 (abfd, buf);
14922 }
14923
14924 static unsigned int
14925 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14926 {
14927   return bfd_get_16 (abfd, buf);
14928 }
14929
14930 static int
14931 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14932 {
14933   return bfd_get_signed_16 (abfd, buf);
14934 }
14935
14936 static unsigned int
14937 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14938 {
14939   return bfd_get_32 (abfd, buf);
14940 }
14941
14942 static int
14943 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14944 {
14945   return bfd_get_signed_32 (abfd, buf);
14946 }
14947
14948 static ULONGEST
14949 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14950 {
14951   return bfd_get_64 (abfd, buf);
14952 }
14953
14954 static CORE_ADDR
14955 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14956               unsigned int *bytes_read)
14957 {
14958   struct comp_unit_head *cu_header = &cu->header;
14959   CORE_ADDR retval = 0;
14960
14961   if (cu_header->signed_addr_p)
14962     {
14963       switch (cu_header->addr_size)
14964         {
14965         case 2:
14966           retval = bfd_get_signed_16 (abfd, buf);
14967           break;
14968         case 4:
14969           retval = bfd_get_signed_32 (abfd, buf);
14970           break;
14971         case 8:
14972           retval = bfd_get_signed_64 (abfd, buf);
14973           break;
14974         default:
14975           internal_error (__FILE__, __LINE__,
14976                           _("read_address: bad switch, signed [in module %s]"),
14977                           bfd_get_filename (abfd));
14978         }
14979     }
14980   else
14981     {
14982       switch (cu_header->addr_size)
14983         {
14984         case 2:
14985           retval = bfd_get_16 (abfd, buf);
14986           break;
14987         case 4:
14988           retval = bfd_get_32 (abfd, buf);
14989           break;
14990         case 8:
14991           retval = bfd_get_64 (abfd, buf);
14992           break;
14993         default:
14994           internal_error (__FILE__, __LINE__,
14995                           _("read_address: bad switch, "
14996                             "unsigned [in module %s]"),
14997                           bfd_get_filename (abfd));
14998         }
14999     }
15000
15001   *bytes_read = cu_header->addr_size;
15002   return retval;
15003 }
15004
15005 /* Read the initial length from a section.  The (draft) DWARF 3
15006    specification allows the initial length to take up either 4 bytes
15007    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15008    bytes describe the length and all offsets will be 8 bytes in length
15009    instead of 4.
15010
15011    An older, non-standard 64-bit format is also handled by this
15012    function.  The older format in question stores the initial length
15013    as an 8-byte quantity without an escape value.  Lengths greater
15014    than 2^32 aren't very common which means that the initial 4 bytes
15015    is almost always zero.  Since a length value of zero doesn't make
15016    sense for the 32-bit format, this initial zero can be considered to
15017    be an escape value which indicates the presence of the older 64-bit
15018    format.  As written, the code can't detect (old format) lengths
15019    greater than 4GB.  If it becomes necessary to handle lengths
15020    somewhat larger than 4GB, we could allow other small values (such
15021    as the non-sensical values of 1, 2, and 3) to also be used as
15022    escape values indicating the presence of the old format.
15023
15024    The value returned via bytes_read should be used to increment the
15025    relevant pointer after calling read_initial_length().
15026
15027    [ Note:  read_initial_length() and read_offset() are based on the
15028      document entitled "DWARF Debugging Information Format", revision
15029      3, draft 8, dated November 19, 2001.  This document was obtained
15030      from:
15031
15032         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15033
15034      This document is only a draft and is subject to change.  (So beware.)
15035
15036      Details regarding the older, non-standard 64-bit format were
15037      determined empirically by examining 64-bit ELF files produced by
15038      the SGI toolchain on an IRIX 6.5 machine.
15039
15040      - Kevin, July 16, 2002
15041    ] */
15042
15043 static LONGEST
15044 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15045 {
15046   LONGEST length = bfd_get_32 (abfd, buf);
15047
15048   if (length == 0xffffffff)
15049     {
15050       length = bfd_get_64 (abfd, buf + 4);
15051       *bytes_read = 12;
15052     }
15053   else if (length == 0)
15054     {
15055       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15056       length = bfd_get_64 (abfd, buf);
15057       *bytes_read = 8;
15058     }
15059   else
15060     {
15061       *bytes_read = 4;
15062     }
15063
15064   return length;
15065 }
15066
15067 /* Cover function for read_initial_length.
15068    Returns the length of the object at BUF, and stores the size of the
15069    initial length in *BYTES_READ and stores the size that offsets will be in
15070    *OFFSET_SIZE.
15071    If the initial length size is not equivalent to that specified in
15072    CU_HEADER then issue a complaint.
15073    This is useful when reading non-comp-unit headers.  */
15074
15075 static LONGEST
15076 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15077                                         const struct comp_unit_head *cu_header,
15078                                         unsigned int *bytes_read,
15079                                         unsigned int *offset_size)
15080 {
15081   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15082
15083   gdb_assert (cu_header->initial_length_size == 4
15084               || cu_header->initial_length_size == 8
15085               || cu_header->initial_length_size == 12);
15086
15087   if (cu_header->initial_length_size != *bytes_read)
15088     complaint (&symfile_complaints,
15089                _("intermixed 32-bit and 64-bit DWARF sections"));
15090
15091   *offset_size = (*bytes_read == 4) ? 4 : 8;
15092   return length;
15093 }
15094
15095 /* Read an offset from the data stream.  The size of the offset is
15096    given by cu_header->offset_size.  */
15097
15098 static LONGEST
15099 read_offset (bfd *abfd, const gdb_byte *buf,
15100              const struct comp_unit_head *cu_header,
15101              unsigned int *bytes_read)
15102 {
15103   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15104
15105   *bytes_read = cu_header->offset_size;
15106   return offset;
15107 }
15108
15109 /* Read an offset from the data stream.  */
15110
15111 static LONGEST
15112 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15113 {
15114   LONGEST retval = 0;
15115
15116   switch (offset_size)
15117     {
15118     case 4:
15119       retval = bfd_get_32 (abfd, buf);
15120       break;
15121     case 8:
15122       retval = bfd_get_64 (abfd, buf);
15123       break;
15124     default:
15125       internal_error (__FILE__, __LINE__,
15126                       _("read_offset_1: bad switch [in module %s]"),
15127                       bfd_get_filename (abfd));
15128     }
15129
15130   return retval;
15131 }
15132
15133 static const gdb_byte *
15134 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15135 {
15136   /* If the size of a host char is 8 bits, we can return a pointer
15137      to the buffer, otherwise we have to copy the data to a buffer
15138      allocated on the temporary obstack.  */
15139   gdb_assert (HOST_CHAR_BIT == 8);
15140   return buf;
15141 }
15142
15143 static const char *
15144 read_direct_string (bfd *abfd, const gdb_byte *buf,
15145                     unsigned int *bytes_read_ptr)
15146 {
15147   /* If the size of a host char is 8 bits, we can return a pointer
15148      to the string, otherwise we have to copy the string to a buffer
15149      allocated on the temporary obstack.  */
15150   gdb_assert (HOST_CHAR_BIT == 8);
15151   if (*buf == '\0')
15152     {
15153       *bytes_read_ptr = 1;
15154       return NULL;
15155     }
15156   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15157   return (const char *) buf;
15158 }
15159
15160 static const char *
15161 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15162 {
15163   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15164   if (dwarf2_per_objfile->str.buffer == NULL)
15165     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15166            bfd_get_filename (abfd));
15167   if (str_offset >= dwarf2_per_objfile->str.size)
15168     error (_("DW_FORM_strp pointing outside of "
15169              ".debug_str section [in module %s]"),
15170            bfd_get_filename (abfd));
15171   gdb_assert (HOST_CHAR_BIT == 8);
15172   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15173     return NULL;
15174   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15175 }
15176
15177 /* Read a string at offset STR_OFFSET in the .debug_str section from
15178    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15179    the string consists of a single NUL byte, return NULL; otherwise
15180    return a pointer to the string.  */
15181
15182 static const char *
15183 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15184 {
15185   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15186
15187   if (dwz->str.buffer == NULL)
15188     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15189              "section [in module %s]"),
15190            bfd_get_filename (dwz->dwz_bfd));
15191   if (str_offset >= dwz->str.size)
15192     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15193              ".debug_str section [in module %s]"),
15194            bfd_get_filename (dwz->dwz_bfd));
15195   gdb_assert (HOST_CHAR_BIT == 8);
15196   if (dwz->str.buffer[str_offset] == '\0')
15197     return NULL;
15198   return (const char *) (dwz->str.buffer + str_offset);
15199 }
15200
15201 static const char *
15202 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15203                       const struct comp_unit_head *cu_header,
15204                       unsigned int *bytes_read_ptr)
15205 {
15206   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15207
15208   return read_indirect_string_at_offset (abfd, str_offset);
15209 }
15210
15211 static ULONGEST
15212 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15213                       unsigned int *bytes_read_ptr)
15214 {
15215   ULONGEST result;
15216   unsigned int num_read;
15217   int i, shift;
15218   unsigned char byte;
15219
15220   result = 0;
15221   shift = 0;
15222   num_read = 0;
15223   i = 0;
15224   while (1)
15225     {
15226       byte = bfd_get_8 (abfd, buf);
15227       buf++;
15228       num_read++;
15229       result |= ((ULONGEST) (byte & 127) << shift);
15230       if ((byte & 128) == 0)
15231         {
15232           break;
15233         }
15234       shift += 7;
15235     }
15236   *bytes_read_ptr = num_read;
15237   return result;
15238 }
15239
15240 static LONGEST
15241 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15242                     unsigned int *bytes_read_ptr)
15243 {
15244   LONGEST result;
15245   int i, shift, num_read;
15246   unsigned char byte;
15247
15248   result = 0;
15249   shift = 0;
15250   num_read = 0;
15251   i = 0;
15252   while (1)
15253     {
15254       byte = bfd_get_8 (abfd, buf);
15255       buf++;
15256       num_read++;
15257       result |= ((LONGEST) (byte & 127) << shift);
15258       shift += 7;
15259       if ((byte & 128) == 0)
15260         {
15261           break;
15262         }
15263     }
15264   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15265     result |= -(((LONGEST) 1) << shift);
15266   *bytes_read_ptr = num_read;
15267   return result;
15268 }
15269
15270 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15271    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15272    ADDR_SIZE is the size of addresses from the CU header.  */
15273
15274 static CORE_ADDR
15275 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15276 {
15277   struct objfile *objfile = dwarf2_per_objfile->objfile;
15278   bfd *abfd = objfile->obfd;
15279   const gdb_byte *info_ptr;
15280
15281   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15282   if (dwarf2_per_objfile->addr.buffer == NULL)
15283     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15284            objfile->name);
15285   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15286     error (_("DW_FORM_addr_index pointing outside of "
15287              ".debug_addr section [in module %s]"),
15288            objfile->name);
15289   info_ptr = (dwarf2_per_objfile->addr.buffer
15290               + addr_base + addr_index * addr_size);
15291   if (addr_size == 4)
15292     return bfd_get_32 (abfd, info_ptr);
15293   else
15294     return bfd_get_64 (abfd, info_ptr);
15295 }
15296
15297 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15298
15299 static CORE_ADDR
15300 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15301 {
15302   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15303 }
15304
15305 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15306
15307 static CORE_ADDR
15308 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15309                              unsigned int *bytes_read)
15310 {
15311   bfd *abfd = cu->objfile->obfd;
15312   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15313
15314   return read_addr_index (cu, addr_index);
15315 }
15316
15317 /* Data structure to pass results from dwarf2_read_addr_index_reader
15318    back to dwarf2_read_addr_index.  */
15319
15320 struct dwarf2_read_addr_index_data
15321 {
15322   ULONGEST addr_base;
15323   int addr_size;
15324 };
15325
15326 /* die_reader_func for dwarf2_read_addr_index.  */
15327
15328 static void
15329 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15330                                const gdb_byte *info_ptr,
15331                                struct die_info *comp_unit_die,
15332                                int has_children,
15333                                void *data)
15334 {
15335   struct dwarf2_cu *cu = reader->cu;
15336   struct dwarf2_read_addr_index_data *aidata =
15337     (struct dwarf2_read_addr_index_data *) data;
15338
15339   aidata->addr_base = cu->addr_base;
15340   aidata->addr_size = cu->header.addr_size;
15341 }
15342
15343 /* Given an index in .debug_addr, fetch the value.
15344    NOTE: This can be called during dwarf expression evaluation,
15345    long after the debug information has been read, and thus per_cu->cu
15346    may no longer exist.  */
15347
15348 CORE_ADDR
15349 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15350                         unsigned int addr_index)
15351 {
15352   struct objfile *objfile = per_cu->objfile;
15353   struct dwarf2_cu *cu = per_cu->cu;
15354   ULONGEST addr_base;
15355   int addr_size;
15356
15357   /* This is intended to be called from outside this file.  */
15358   dw2_setup (objfile);
15359
15360   /* We need addr_base and addr_size.
15361      If we don't have PER_CU->cu, we have to get it.
15362      Nasty, but the alternative is storing the needed info in PER_CU,
15363      which at this point doesn't seem justified: it's not clear how frequently
15364      it would get used and it would increase the size of every PER_CU.
15365      Entry points like dwarf2_per_cu_addr_size do a similar thing
15366      so we're not in uncharted territory here.
15367      Alas we need to be a bit more complicated as addr_base is contained
15368      in the DIE.
15369
15370      We don't need to read the entire CU(/TU).
15371      We just need the header and top level die.
15372
15373      IWBN to use the aging mechanism to let us lazily later discard the CU.
15374      For now we skip this optimization.  */
15375
15376   if (cu != NULL)
15377     {
15378       addr_base = cu->addr_base;
15379       addr_size = cu->header.addr_size;
15380     }
15381   else
15382     {
15383       struct dwarf2_read_addr_index_data aidata;
15384
15385       /* Note: We can't use init_cutu_and_read_dies_simple here,
15386          we need addr_base.  */
15387       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15388                                dwarf2_read_addr_index_reader, &aidata);
15389       addr_base = aidata.addr_base;
15390       addr_size = aidata.addr_size;
15391     }
15392
15393   return read_addr_index_1 (addr_index, addr_base, addr_size);
15394 }
15395
15396 /* Given a DW_AT_str_index, fetch the string.  */
15397
15398 static const char *
15399 read_str_index (const struct die_reader_specs *reader,
15400                 struct dwarf2_cu *cu, ULONGEST str_index)
15401 {
15402   struct objfile *objfile = dwarf2_per_objfile->objfile;
15403   const char *dwo_name = objfile->name;
15404   bfd *abfd = objfile->obfd;
15405   struct dwo_sections *sections = &reader->dwo_file->sections;
15406   const gdb_byte *info_ptr;
15407   ULONGEST str_offset;
15408
15409   dwarf2_read_section (objfile, &sections->str);
15410   dwarf2_read_section (objfile, &sections->str_offsets);
15411   if (sections->str.buffer == NULL)
15412     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15413              " in CU at offset 0x%lx [in module %s]"),
15414            (long) cu->header.offset.sect_off, dwo_name);
15415   if (sections->str_offsets.buffer == NULL)
15416     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15417              " in CU at offset 0x%lx [in module %s]"),
15418            (long) cu->header.offset.sect_off, dwo_name);
15419   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15420     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15421              " section in CU at offset 0x%lx [in module %s]"),
15422            (long) cu->header.offset.sect_off, dwo_name);
15423   info_ptr = (sections->str_offsets.buffer
15424               + str_index * cu->header.offset_size);
15425   if (cu->header.offset_size == 4)
15426     str_offset = bfd_get_32 (abfd, info_ptr);
15427   else
15428     str_offset = bfd_get_64 (abfd, info_ptr);
15429   if (str_offset >= sections->str.size)
15430     error (_("Offset from DW_FORM_str_index pointing outside of"
15431              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15432            (long) cu->header.offset.sect_off, dwo_name);
15433   return (const char *) (sections->str.buffer + str_offset);
15434 }
15435
15436 /* Return the length of an LEB128 number in BUF.  */
15437
15438 static int
15439 leb128_size (const gdb_byte *buf)
15440 {
15441   const gdb_byte *begin = buf;
15442   gdb_byte byte;
15443
15444   while (1)
15445     {
15446       byte = *buf++;
15447       if ((byte & 128) == 0)
15448         return buf - begin;
15449     }
15450 }
15451
15452 static void
15453 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15454 {
15455   switch (lang)
15456     {
15457     case DW_LANG_C89:
15458     case DW_LANG_C99:
15459     case DW_LANG_C:
15460     case DW_LANG_UPC:
15461       cu->language = language_c;
15462       break;
15463     case DW_LANG_C_plus_plus:
15464       cu->language = language_cplus;
15465       break;
15466     case DW_LANG_D:
15467       cu->language = language_d;
15468       break;
15469     case DW_LANG_Fortran77:
15470     case DW_LANG_Fortran90:
15471     case DW_LANG_Fortran95:
15472       cu->language = language_fortran;
15473       break;
15474     case DW_LANG_Go:
15475       cu->language = language_go;
15476       break;
15477     case DW_LANG_Mips_Assembler:
15478       cu->language = language_asm;
15479       break;
15480     case DW_LANG_Java:
15481       cu->language = language_java;
15482       break;
15483     case DW_LANG_Ada83:
15484     case DW_LANG_Ada95:
15485       cu->language = language_ada;
15486       break;
15487     case DW_LANG_Modula2:
15488       cu->language = language_m2;
15489       break;
15490     case DW_LANG_Pascal83:
15491       cu->language = language_pascal;
15492       break;
15493     case DW_LANG_ObjC:
15494       cu->language = language_objc;
15495       break;
15496     case DW_LANG_Cobol74:
15497     case DW_LANG_Cobol85:
15498     default:
15499       cu->language = language_minimal;
15500       break;
15501     }
15502   cu->language_defn = language_def (cu->language);
15503 }
15504
15505 /* Return the named attribute or NULL if not there.  */
15506
15507 static struct attribute *
15508 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15509 {
15510   for (;;)
15511     {
15512       unsigned int i;
15513       struct attribute *spec = NULL;
15514
15515       for (i = 0; i < die->num_attrs; ++i)
15516         {
15517           if (die->attrs[i].name == name)
15518             return &die->attrs[i];
15519           if (die->attrs[i].name == DW_AT_specification
15520               || die->attrs[i].name == DW_AT_abstract_origin)
15521             spec = &die->attrs[i];
15522         }
15523
15524       if (!spec)
15525         break;
15526
15527       die = follow_die_ref (die, spec, &cu);
15528     }
15529
15530   return NULL;
15531 }
15532
15533 /* Return the named attribute or NULL if not there,
15534    but do not follow DW_AT_specification, etc.
15535    This is for use in contexts where we're reading .debug_types dies.
15536    Following DW_AT_specification, DW_AT_abstract_origin will take us
15537    back up the chain, and we want to go down.  */
15538
15539 static struct attribute *
15540 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15541 {
15542   unsigned int i;
15543
15544   for (i = 0; i < die->num_attrs; ++i)
15545     if (die->attrs[i].name == name)
15546       return &die->attrs[i];
15547
15548   return NULL;
15549 }
15550
15551 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15552    and holds a non-zero value.  This function should only be used for
15553    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15554
15555 static int
15556 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15557 {
15558   struct attribute *attr = dwarf2_attr (die, name, cu);
15559
15560   return (attr && DW_UNSND (attr));
15561 }
15562
15563 static int
15564 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15565 {
15566   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15567      which value is non-zero.  However, we have to be careful with
15568      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15569      (via dwarf2_flag_true_p) follows this attribute.  So we may
15570      end up accidently finding a declaration attribute that belongs
15571      to a different DIE referenced by the specification attribute,
15572      even though the given DIE does not have a declaration attribute.  */
15573   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15574           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15575 }
15576
15577 /* Return the die giving the specification for DIE, if there is
15578    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15579    containing the return value on output.  If there is no
15580    specification, but there is an abstract origin, that is
15581    returned.  */
15582
15583 static struct die_info *
15584 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15585 {
15586   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15587                                              *spec_cu);
15588
15589   if (spec_attr == NULL)
15590     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15591
15592   if (spec_attr == NULL)
15593     return NULL;
15594   else
15595     return follow_die_ref (die, spec_attr, spec_cu);
15596 }
15597
15598 /* Free the line_header structure *LH, and any arrays and strings it
15599    refers to.
15600    NOTE: This is also used as a "cleanup" function.  */
15601
15602 static void
15603 free_line_header (struct line_header *lh)
15604 {
15605   if (lh->standard_opcode_lengths)
15606     xfree (lh->standard_opcode_lengths);
15607
15608   /* Remember that all the lh->file_names[i].name pointers are
15609      pointers into debug_line_buffer, and don't need to be freed.  */
15610   if (lh->file_names)
15611     xfree (lh->file_names);
15612
15613   /* Similarly for the include directory names.  */
15614   if (lh->include_dirs)
15615     xfree (lh->include_dirs);
15616
15617   xfree (lh);
15618 }
15619
15620 /* Add an entry to LH's include directory table.  */
15621
15622 static void
15623 add_include_dir (struct line_header *lh, const char *include_dir)
15624 {
15625   /* Grow the array if necessary.  */
15626   if (lh->include_dirs_size == 0)
15627     {
15628       lh->include_dirs_size = 1; /* for testing */
15629       lh->include_dirs = xmalloc (lh->include_dirs_size
15630                                   * sizeof (*lh->include_dirs));
15631     }
15632   else if (lh->num_include_dirs >= lh->include_dirs_size)
15633     {
15634       lh->include_dirs_size *= 2;
15635       lh->include_dirs = xrealloc (lh->include_dirs,
15636                                    (lh->include_dirs_size
15637                                     * sizeof (*lh->include_dirs)));
15638     }
15639
15640   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15641 }
15642
15643 /* Add an entry to LH's file name table.  */
15644
15645 static void
15646 add_file_name (struct line_header *lh,
15647                const char *name,
15648                unsigned int dir_index,
15649                unsigned int mod_time,
15650                unsigned int length)
15651 {
15652   struct file_entry *fe;
15653
15654   /* Grow the array if necessary.  */
15655   if (lh->file_names_size == 0)
15656     {
15657       lh->file_names_size = 1; /* for testing */
15658       lh->file_names = xmalloc (lh->file_names_size
15659                                 * sizeof (*lh->file_names));
15660     }
15661   else if (lh->num_file_names >= lh->file_names_size)
15662     {
15663       lh->file_names_size *= 2;
15664       lh->file_names = xrealloc (lh->file_names,
15665                                  (lh->file_names_size
15666                                   * sizeof (*lh->file_names)));
15667     }
15668
15669   fe = &lh->file_names[lh->num_file_names++];
15670   fe->name = name;
15671   fe->dir_index = dir_index;
15672   fe->mod_time = mod_time;
15673   fe->length = length;
15674   fe->included_p = 0;
15675   fe->symtab = NULL;
15676 }
15677
15678 /* A convenience function to find the proper .debug_line section for a
15679    CU.  */
15680
15681 static struct dwarf2_section_info *
15682 get_debug_line_section (struct dwarf2_cu *cu)
15683 {
15684   struct dwarf2_section_info *section;
15685
15686   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15687      DWO file.  */
15688   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15689     section = &cu->dwo_unit->dwo_file->sections.line;
15690   else if (cu->per_cu->is_dwz)
15691     {
15692       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15693
15694       section = &dwz->line;
15695     }
15696   else
15697     section = &dwarf2_per_objfile->line;
15698
15699   return section;
15700 }
15701
15702 /* Read the statement program header starting at OFFSET in
15703    .debug_line, or .debug_line.dwo.  Return a pointer
15704    to a struct line_header, allocated using xmalloc.
15705
15706    NOTE: the strings in the include directory and file name tables of
15707    the returned object point into the dwarf line section buffer,
15708    and must not be freed.  */
15709
15710 static struct line_header *
15711 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15712 {
15713   struct cleanup *back_to;
15714   struct line_header *lh;
15715   const gdb_byte *line_ptr;
15716   unsigned int bytes_read, offset_size;
15717   int i;
15718   const char *cur_dir, *cur_file;
15719   struct dwarf2_section_info *section;
15720   bfd *abfd;
15721
15722   section = get_debug_line_section (cu);
15723   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15724   if (section->buffer == NULL)
15725     {
15726       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15727         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15728       else
15729         complaint (&symfile_complaints, _("missing .debug_line section"));
15730       return 0;
15731     }
15732
15733   /* We can't do this until we know the section is non-empty.
15734      Only then do we know we have such a section.  */
15735   abfd = section->asection->owner;
15736
15737   /* Make sure that at least there's room for the total_length field.
15738      That could be 12 bytes long, but we're just going to fudge that.  */
15739   if (offset + 4 >= section->size)
15740     {
15741       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15742       return 0;
15743     }
15744
15745   lh = xmalloc (sizeof (*lh));
15746   memset (lh, 0, sizeof (*lh));
15747   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15748                           (void *) lh);
15749
15750   line_ptr = section->buffer + offset;
15751
15752   /* Read in the header.  */
15753   lh->total_length =
15754     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15755                                             &bytes_read, &offset_size);
15756   line_ptr += bytes_read;
15757   if (line_ptr + lh->total_length > (section->buffer + section->size))
15758     {
15759       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15760       do_cleanups (back_to);
15761       return 0;
15762     }
15763   lh->statement_program_end = line_ptr + lh->total_length;
15764   lh->version = read_2_bytes (abfd, line_ptr);
15765   line_ptr += 2;
15766   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15767   line_ptr += offset_size;
15768   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15769   line_ptr += 1;
15770   if (lh->version >= 4)
15771     {
15772       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15773       line_ptr += 1;
15774     }
15775   else
15776     lh->maximum_ops_per_instruction = 1;
15777
15778   if (lh->maximum_ops_per_instruction == 0)
15779     {
15780       lh->maximum_ops_per_instruction = 1;
15781       complaint (&symfile_complaints,
15782                  _("invalid maximum_ops_per_instruction "
15783                    "in `.debug_line' section"));
15784     }
15785
15786   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15787   line_ptr += 1;
15788   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15789   line_ptr += 1;
15790   lh->line_range = read_1_byte (abfd, line_ptr);
15791   line_ptr += 1;
15792   lh->opcode_base = read_1_byte (abfd, line_ptr);
15793   line_ptr += 1;
15794   lh->standard_opcode_lengths
15795     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15796
15797   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15798   for (i = 1; i < lh->opcode_base; ++i)
15799     {
15800       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15801       line_ptr += 1;
15802     }
15803
15804   /* Read directory table.  */
15805   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15806     {
15807       line_ptr += bytes_read;
15808       add_include_dir (lh, cur_dir);
15809     }
15810   line_ptr += bytes_read;
15811
15812   /* Read file name table.  */
15813   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15814     {
15815       unsigned int dir_index, mod_time, length;
15816
15817       line_ptr += bytes_read;
15818       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15819       line_ptr += bytes_read;
15820       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15821       line_ptr += bytes_read;
15822       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15823       line_ptr += bytes_read;
15824
15825       add_file_name (lh, cur_file, dir_index, mod_time, length);
15826     }
15827   line_ptr += bytes_read;
15828   lh->statement_program_start = line_ptr;
15829
15830   if (line_ptr > (section->buffer + section->size))
15831     complaint (&symfile_complaints,
15832                _("line number info header doesn't "
15833                  "fit in `.debug_line' section"));
15834
15835   discard_cleanups (back_to);
15836   return lh;
15837 }
15838
15839 /* Subroutine of dwarf_decode_lines to simplify it.
15840    Return the file name of the psymtab for included file FILE_INDEX
15841    in line header LH of PST.
15842    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15843    If space for the result is malloc'd, it will be freed by a cleanup.
15844    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15845
15846    The function creates dangling cleanup registration.  */
15847
15848 static const char *
15849 psymtab_include_file_name (const struct line_header *lh, int file_index,
15850                            const struct partial_symtab *pst,
15851                            const char *comp_dir)
15852 {
15853   const struct file_entry fe = lh->file_names [file_index];
15854   const char *include_name = fe.name;
15855   const char *include_name_to_compare = include_name;
15856   const char *dir_name = NULL;
15857   const char *pst_filename;
15858   char *copied_name = NULL;
15859   int file_is_pst;
15860
15861   if (fe.dir_index)
15862     dir_name = lh->include_dirs[fe.dir_index - 1];
15863
15864   if (!IS_ABSOLUTE_PATH (include_name)
15865       && (dir_name != NULL || comp_dir != NULL))
15866     {
15867       /* Avoid creating a duplicate psymtab for PST.
15868          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15869          Before we do the comparison, however, we need to account
15870          for DIR_NAME and COMP_DIR.
15871          First prepend dir_name (if non-NULL).  If we still don't
15872          have an absolute path prepend comp_dir (if non-NULL).
15873          However, the directory we record in the include-file's
15874          psymtab does not contain COMP_DIR (to match the
15875          corresponding symtab(s)).
15876
15877          Example:
15878
15879          bash$ cd /tmp
15880          bash$ gcc -g ./hello.c
15881          include_name = "hello.c"
15882          dir_name = "."
15883          DW_AT_comp_dir = comp_dir = "/tmp"
15884          DW_AT_name = "./hello.c"  */
15885
15886       if (dir_name != NULL)
15887         {
15888           char *tem = concat (dir_name, SLASH_STRING,
15889                               include_name, (char *)NULL);
15890
15891           make_cleanup (xfree, tem);
15892           include_name = tem;
15893           include_name_to_compare = include_name;
15894         }
15895       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15896         {
15897           char *tem = concat (comp_dir, SLASH_STRING,
15898                               include_name, (char *)NULL);
15899
15900           make_cleanup (xfree, tem);
15901           include_name_to_compare = tem;
15902         }
15903     }
15904
15905   pst_filename = pst->filename;
15906   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15907     {
15908       copied_name = concat (pst->dirname, SLASH_STRING,
15909                             pst_filename, (char *)NULL);
15910       pst_filename = copied_name;
15911     }
15912
15913   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15914
15915   if (copied_name != NULL)
15916     xfree (copied_name);
15917
15918   if (file_is_pst)
15919     return NULL;
15920   return include_name;
15921 }
15922
15923 /* Ignore this record_line request.  */
15924
15925 static void
15926 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15927 {
15928   return;
15929 }
15930
15931 /* Subroutine of dwarf_decode_lines to simplify it.
15932    Process the line number information in LH.  */
15933
15934 static void
15935 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15936                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15937 {
15938   const gdb_byte *line_ptr, *extended_end;
15939   const gdb_byte *line_end;
15940   unsigned int bytes_read, extended_len;
15941   unsigned char op_code, extended_op, adj_opcode;
15942   CORE_ADDR baseaddr;
15943   struct objfile *objfile = cu->objfile;
15944   bfd *abfd = objfile->obfd;
15945   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15946   const int decode_for_pst_p = (pst != NULL);
15947   struct subfile *last_subfile = NULL;
15948   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15949     = record_line;
15950
15951   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15952
15953   line_ptr = lh->statement_program_start;
15954   line_end = lh->statement_program_end;
15955
15956   /* Read the statement sequences until there's nothing left.  */
15957   while (line_ptr < line_end)
15958     {
15959       /* state machine registers  */
15960       CORE_ADDR address = 0;
15961       unsigned int file = 1;
15962       unsigned int line = 1;
15963       unsigned int column = 0;
15964       int is_stmt = lh->default_is_stmt;
15965       int basic_block = 0;
15966       int end_sequence = 0;
15967       CORE_ADDR addr;
15968       unsigned char op_index = 0;
15969
15970       if (!decode_for_pst_p && lh->num_file_names >= file)
15971         {
15972           /* Start a subfile for the current file of the state machine.  */
15973           /* lh->include_dirs and lh->file_names are 0-based, but the
15974              directory and file name numbers in the statement program
15975              are 1-based.  */
15976           struct file_entry *fe = &lh->file_names[file - 1];
15977           const char *dir = NULL;
15978
15979           if (fe->dir_index)
15980             dir = lh->include_dirs[fe->dir_index - 1];
15981
15982           dwarf2_start_subfile (fe->name, dir, comp_dir);
15983         }
15984
15985       /* Decode the table.  */
15986       while (!end_sequence)
15987         {
15988           op_code = read_1_byte (abfd, line_ptr);
15989           line_ptr += 1;
15990           if (line_ptr > line_end)
15991             {
15992               dwarf2_debug_line_missing_end_sequence_complaint ();
15993               break;
15994             }
15995
15996           if (op_code >= lh->opcode_base)
15997             {
15998               /* Special operand.  */
15999               adj_opcode = op_code - lh->opcode_base;
16000               address += (((op_index + (adj_opcode / lh->line_range))
16001                            / lh->maximum_ops_per_instruction)
16002                           * lh->minimum_instruction_length);
16003               op_index = ((op_index + (adj_opcode / lh->line_range))
16004                           % lh->maximum_ops_per_instruction);
16005               line += lh->line_base + (adj_opcode % lh->line_range);
16006               if (lh->num_file_names < file || file == 0)
16007                 dwarf2_debug_line_missing_file_complaint ();
16008               /* For now we ignore lines not starting on an
16009                  instruction boundary.  */
16010               else if (op_index == 0)
16011                 {
16012                   lh->file_names[file - 1].included_p = 1;
16013                   if (!decode_for_pst_p && is_stmt)
16014                     {
16015                       if (last_subfile != current_subfile)
16016                         {
16017                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16018                           if (last_subfile)
16019                             (*p_record_line) (last_subfile, 0, addr);
16020                           last_subfile = current_subfile;
16021                         }
16022                       /* Append row to matrix using current values.  */
16023                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16024                       (*p_record_line) (current_subfile, line, addr);
16025                     }
16026                 }
16027               basic_block = 0;
16028             }
16029           else switch (op_code)
16030             {
16031             case DW_LNS_extended_op:
16032               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16033                                                    &bytes_read);
16034               line_ptr += bytes_read;
16035               extended_end = line_ptr + extended_len;
16036               extended_op = read_1_byte (abfd, line_ptr);
16037               line_ptr += 1;
16038               switch (extended_op)
16039                 {
16040                 case DW_LNE_end_sequence:
16041                   p_record_line = record_line;
16042                   end_sequence = 1;
16043                   break;
16044                 case DW_LNE_set_address:
16045                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16046
16047                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16048                     {
16049                       /* This line table is for a function which has been
16050                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16051
16052                       long line_offset
16053                         = line_ptr - get_debug_line_section (cu)->buffer;
16054
16055                       complaint (&symfile_complaints,
16056                                  _(".debug_line address at offset 0x%lx is 0 "
16057                                    "[in module %s]"),
16058                                  line_offset, objfile->name);
16059                       p_record_line = noop_record_line;
16060                     }
16061
16062                   op_index = 0;
16063                   line_ptr += bytes_read;
16064                   address += baseaddr;
16065                   break;
16066                 case DW_LNE_define_file:
16067                   {
16068                     const char *cur_file;
16069                     unsigned int dir_index, mod_time, length;
16070
16071                     cur_file = read_direct_string (abfd, line_ptr,
16072                                                    &bytes_read);
16073                     line_ptr += bytes_read;
16074                     dir_index =
16075                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16076                     line_ptr += bytes_read;
16077                     mod_time =
16078                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16079                     line_ptr += bytes_read;
16080                     length =
16081                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16082                     line_ptr += bytes_read;
16083                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16084                   }
16085                   break;
16086                 case DW_LNE_set_discriminator:
16087                   /* The discriminator is not interesting to the debugger;
16088                      just ignore it.  */
16089                   line_ptr = extended_end;
16090                   break;
16091                 default:
16092                   complaint (&symfile_complaints,
16093                              _("mangled .debug_line section"));
16094                   return;
16095                 }
16096               /* Make sure that we parsed the extended op correctly.  If e.g.
16097                  we expected a different address size than the producer used,
16098                  we may have read the wrong number of bytes.  */
16099               if (line_ptr != extended_end)
16100                 {
16101                   complaint (&symfile_complaints,
16102                              _("mangled .debug_line section"));
16103                   return;
16104                 }
16105               break;
16106             case DW_LNS_copy:
16107               if (lh->num_file_names < file || file == 0)
16108                 dwarf2_debug_line_missing_file_complaint ();
16109               else
16110                 {
16111                   lh->file_names[file - 1].included_p = 1;
16112                   if (!decode_for_pst_p && is_stmt)
16113                     {
16114                       if (last_subfile != current_subfile)
16115                         {
16116                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16117                           if (last_subfile)
16118                             (*p_record_line) (last_subfile, 0, addr);
16119                           last_subfile = current_subfile;
16120                         }
16121                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16122                       (*p_record_line) (current_subfile, line, addr);
16123                     }
16124                 }
16125               basic_block = 0;
16126               break;
16127             case DW_LNS_advance_pc:
16128               {
16129                 CORE_ADDR adjust
16130                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16131
16132                 address += (((op_index + adjust)
16133                              / lh->maximum_ops_per_instruction)
16134                             * lh->minimum_instruction_length);
16135                 op_index = ((op_index + adjust)
16136                             % lh->maximum_ops_per_instruction);
16137                 line_ptr += bytes_read;
16138               }
16139               break;
16140             case DW_LNS_advance_line:
16141               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16142               line_ptr += bytes_read;
16143               break;
16144             case DW_LNS_set_file:
16145               {
16146                 /* The arrays lh->include_dirs and lh->file_names are
16147                    0-based, but the directory and file name numbers in
16148                    the statement program are 1-based.  */
16149                 struct file_entry *fe;
16150                 const char *dir = NULL;
16151
16152                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16153                 line_ptr += bytes_read;
16154                 if (lh->num_file_names < file || file == 0)
16155                   dwarf2_debug_line_missing_file_complaint ();
16156                 else
16157                   {
16158                     fe = &lh->file_names[file - 1];
16159                     if (fe->dir_index)
16160                       dir = lh->include_dirs[fe->dir_index - 1];
16161                     if (!decode_for_pst_p)
16162                       {
16163                         last_subfile = current_subfile;
16164                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16165                       }
16166                   }
16167               }
16168               break;
16169             case DW_LNS_set_column:
16170               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16171               line_ptr += bytes_read;
16172               break;
16173             case DW_LNS_negate_stmt:
16174               is_stmt = (!is_stmt);
16175               break;
16176             case DW_LNS_set_basic_block:
16177               basic_block = 1;
16178               break;
16179             /* Add to the address register of the state machine the
16180                address increment value corresponding to special opcode
16181                255.  I.e., this value is scaled by the minimum
16182                instruction length since special opcode 255 would have
16183                scaled the increment.  */
16184             case DW_LNS_const_add_pc:
16185               {
16186                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16187
16188                 address += (((op_index + adjust)
16189                              / lh->maximum_ops_per_instruction)
16190                             * lh->minimum_instruction_length);
16191                 op_index = ((op_index + adjust)
16192                             % lh->maximum_ops_per_instruction);
16193               }
16194               break;
16195             case DW_LNS_fixed_advance_pc:
16196               address += read_2_bytes (abfd, line_ptr);
16197               op_index = 0;
16198               line_ptr += 2;
16199               break;
16200             default:
16201               {
16202                 /* Unknown standard opcode, ignore it.  */
16203                 int i;
16204
16205                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16206                   {
16207                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16208                     line_ptr += bytes_read;
16209                   }
16210               }
16211             }
16212         }
16213       if (lh->num_file_names < file || file == 0)
16214         dwarf2_debug_line_missing_file_complaint ();
16215       else
16216         {
16217           lh->file_names[file - 1].included_p = 1;
16218           if (!decode_for_pst_p)
16219             {
16220               addr = gdbarch_addr_bits_remove (gdbarch, address);
16221               (*p_record_line) (current_subfile, 0, addr);
16222             }
16223         }
16224     }
16225 }
16226
16227 /* Decode the Line Number Program (LNP) for the given line_header
16228    structure and CU.  The actual information extracted and the type
16229    of structures created from the LNP depends on the value of PST.
16230
16231    1. If PST is NULL, then this procedure uses the data from the program
16232       to create all necessary symbol tables, and their linetables.
16233
16234    2. If PST is not NULL, this procedure reads the program to determine
16235       the list of files included by the unit represented by PST, and
16236       builds all the associated partial symbol tables.
16237
16238    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16239    It is used for relative paths in the line table.
16240    NOTE: When processing partial symtabs (pst != NULL),
16241    comp_dir == pst->dirname.
16242
16243    NOTE: It is important that psymtabs have the same file name (via strcmp)
16244    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16245    symtab we don't use it in the name of the psymtabs we create.
16246    E.g. expand_line_sal requires this when finding psymtabs to expand.
16247    A good testcase for this is mb-inline.exp.  */
16248
16249 static void
16250 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16251                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16252                     int want_line_info)
16253 {
16254   struct objfile *objfile = cu->objfile;
16255   const int decode_for_pst_p = (pst != NULL);
16256   struct subfile *first_subfile = current_subfile;
16257
16258   if (want_line_info)
16259     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16260
16261   if (decode_for_pst_p)
16262     {
16263       int file_index;
16264
16265       /* Now that we're done scanning the Line Header Program, we can
16266          create the psymtab of each included file.  */
16267       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16268         if (lh->file_names[file_index].included_p == 1)
16269           {
16270             const char *include_name =
16271               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16272             if (include_name != NULL)
16273               dwarf2_create_include_psymtab (include_name, pst, objfile);
16274           }
16275     }
16276   else
16277     {
16278       /* Make sure a symtab is created for every file, even files
16279          which contain only variables (i.e. no code with associated
16280          line numbers).  */
16281       int i;
16282
16283       for (i = 0; i < lh->num_file_names; i++)
16284         {
16285           const char *dir = NULL;
16286           struct file_entry *fe;
16287
16288           fe = &lh->file_names[i];
16289           if (fe->dir_index)
16290             dir = lh->include_dirs[fe->dir_index - 1];
16291           dwarf2_start_subfile (fe->name, dir, comp_dir);
16292
16293           /* Skip the main file; we don't need it, and it must be
16294              allocated last, so that it will show up before the
16295              non-primary symtabs in the objfile's symtab list.  */
16296           if (current_subfile == first_subfile)
16297             continue;
16298
16299           if (current_subfile->symtab == NULL)
16300             current_subfile->symtab = allocate_symtab (current_subfile->name,
16301                                                        objfile);
16302           fe->symtab = current_subfile->symtab;
16303         }
16304     }
16305 }
16306
16307 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16308    DIRNAME the name of the source directory which contains FILENAME
16309    or NULL if not known.  COMP_DIR is the compilation directory for the
16310    linetable's compilation unit or NULL if not known.
16311    This routine tries to keep line numbers from identical absolute and
16312    relative file names in a common subfile.
16313
16314    Using the `list' example from the GDB testsuite, which resides in
16315    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16316    of /srcdir/list0.c yields the following debugging information for list0.c:
16317
16318    DW_AT_name:          /srcdir/list0.c
16319    DW_AT_comp_dir:              /compdir
16320    files.files[0].name: list0.h
16321    files.files[0].dir:  /srcdir
16322    files.files[1].name: list0.c
16323    files.files[1].dir:  /srcdir
16324
16325    The line number information for list0.c has to end up in a single
16326    subfile, so that `break /srcdir/list0.c:1' works as expected.
16327    start_subfile will ensure that this happens provided that we pass the
16328    concatenation of files.files[1].dir and files.files[1].name as the
16329    subfile's name.  */
16330
16331 static void
16332 dwarf2_start_subfile (const char *filename, const char *dirname,
16333                       const char *comp_dir)
16334 {
16335   char *copy = NULL;
16336
16337   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16338      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16339      second argument to start_subfile.  To be consistent, we do the
16340      same here.  In order not to lose the line information directory,
16341      we concatenate it to the filename when it makes sense.
16342      Note that the Dwarf3 standard says (speaking of filenames in line
16343      information): ``The directory index is ignored for file names
16344      that represent full path names''.  Thus ignoring dirname in the
16345      `else' branch below isn't an issue.  */
16346
16347   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16348     {
16349       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16350       filename = copy;
16351     }
16352
16353   start_subfile (filename, comp_dir);
16354
16355   if (copy != NULL)
16356     xfree (copy);
16357 }
16358
16359 /* Start a symtab for DWARF.
16360    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16361
16362 static void
16363 dwarf2_start_symtab (struct dwarf2_cu *cu,
16364                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16365 {
16366   start_symtab (name, comp_dir, low_pc);
16367   record_debugformat ("DWARF 2");
16368   record_producer (cu->producer);
16369
16370   /* We assume that we're processing GCC output.  */
16371   processing_gcc_compilation = 2;
16372
16373   cu->processing_has_namespace_info = 0;
16374 }
16375
16376 static void
16377 var_decode_location (struct attribute *attr, struct symbol *sym,
16378                      struct dwarf2_cu *cu)
16379 {
16380   struct objfile *objfile = cu->objfile;
16381   struct comp_unit_head *cu_header = &cu->header;
16382
16383   /* NOTE drow/2003-01-30: There used to be a comment and some special
16384      code here to turn a symbol with DW_AT_external and a
16385      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16386      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16387      with some versions of binutils) where shared libraries could have
16388      relocations against symbols in their debug information - the
16389      minimal symbol would have the right address, but the debug info
16390      would not.  It's no longer necessary, because we will explicitly
16391      apply relocations when we read in the debug information now.  */
16392
16393   /* A DW_AT_location attribute with no contents indicates that a
16394      variable has been optimized away.  */
16395   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16396     {
16397       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16398       return;
16399     }
16400
16401   /* Handle one degenerate form of location expression specially, to
16402      preserve GDB's previous behavior when section offsets are
16403      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16404      then mark this symbol as LOC_STATIC.  */
16405
16406   if (attr_form_is_block (attr)
16407       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16408            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16409           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16410               && (DW_BLOCK (attr)->size
16411                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16412     {
16413       unsigned int dummy;
16414
16415       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16416         SYMBOL_VALUE_ADDRESS (sym) =
16417           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16418       else
16419         SYMBOL_VALUE_ADDRESS (sym) =
16420           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16421       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16422       fixup_symbol_section (sym, objfile);
16423       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16424                                               SYMBOL_SECTION (sym));
16425       return;
16426     }
16427
16428   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16429      expression evaluator, and use LOC_COMPUTED only when necessary
16430      (i.e. when the value of a register or memory location is
16431      referenced, or a thread-local block, etc.).  Then again, it might
16432      not be worthwhile.  I'm assuming that it isn't unless performance
16433      or memory numbers show me otherwise.  */
16434
16435   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16436
16437   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16438     cu->has_loclist = 1;
16439 }
16440
16441 /* Given a pointer to a DWARF information entry, figure out if we need
16442    to make a symbol table entry for it, and if so, create a new entry
16443    and return a pointer to it.
16444    If TYPE is NULL, determine symbol type from the die, otherwise
16445    used the passed type.
16446    If SPACE is not NULL, use it to hold the new symbol.  If it is
16447    NULL, allocate a new symbol on the objfile's obstack.  */
16448
16449 static struct symbol *
16450 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16451                  struct symbol *space)
16452 {
16453   struct objfile *objfile = cu->objfile;
16454   struct symbol *sym = NULL;
16455   const char *name;
16456   struct attribute *attr = NULL;
16457   struct attribute *attr2 = NULL;
16458   CORE_ADDR baseaddr;
16459   struct pending **list_to_add = NULL;
16460
16461   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16462
16463   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16464
16465   name = dwarf2_name (die, cu);
16466   if (name)
16467     {
16468       const char *linkagename;
16469       int suppress_add = 0;
16470
16471       if (space)
16472         sym = space;
16473       else
16474         sym = allocate_symbol (objfile);
16475       OBJSTAT (objfile, n_syms++);
16476
16477       /* Cache this symbol's name and the name's demangled form (if any).  */
16478       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16479       linkagename = dwarf2_physname (name, die, cu);
16480       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16481
16482       /* Fortran does not have mangling standard and the mangling does differ
16483          between gfortran, iFort etc.  */
16484       if (cu->language == language_fortran
16485           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16486         symbol_set_demangled_name (&(sym->ginfo),
16487                                    dwarf2_full_name (name, die, cu),
16488                                    NULL);
16489
16490       /* Default assumptions.
16491          Use the passed type or decode it from the die.  */
16492       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16493       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16494       if (type != NULL)
16495         SYMBOL_TYPE (sym) = type;
16496       else
16497         SYMBOL_TYPE (sym) = die_type (die, cu);
16498       attr = dwarf2_attr (die,
16499                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16500                           cu);
16501       if (attr)
16502         {
16503           SYMBOL_LINE (sym) = DW_UNSND (attr);
16504         }
16505
16506       attr = dwarf2_attr (die,
16507                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16508                           cu);
16509       if (attr)
16510         {
16511           int file_index = DW_UNSND (attr);
16512
16513           if (cu->line_header == NULL
16514               || file_index > cu->line_header->num_file_names)
16515             complaint (&symfile_complaints,
16516                        _("file index out of range"));
16517           else if (file_index > 0)
16518             {
16519               struct file_entry *fe;
16520
16521               fe = &cu->line_header->file_names[file_index - 1];
16522               SYMBOL_SYMTAB (sym) = fe->symtab;
16523             }
16524         }
16525
16526       switch (die->tag)
16527         {
16528         case DW_TAG_label:
16529           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16530           if (attr)
16531             {
16532               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16533             }
16534           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16535           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16536           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16537           add_symbol_to_list (sym, cu->list_in_scope);
16538           break;
16539         case DW_TAG_subprogram:
16540           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16541              finish_block.  */
16542           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16543           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16544           if ((attr2 && (DW_UNSND (attr2) != 0))
16545               || cu->language == language_ada)
16546             {
16547               /* Subprograms marked external are stored as a global symbol.
16548                  Ada subprograms, whether marked external or not, are always
16549                  stored as a global symbol, because we want to be able to
16550                  access them globally.  For instance, we want to be able
16551                  to break on a nested subprogram without having to
16552                  specify the context.  */
16553               list_to_add = &global_symbols;
16554             }
16555           else
16556             {
16557               list_to_add = cu->list_in_scope;
16558             }
16559           break;
16560         case DW_TAG_inlined_subroutine:
16561           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16562              finish_block.  */
16563           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16564           SYMBOL_INLINED (sym) = 1;
16565           list_to_add = cu->list_in_scope;
16566           break;
16567         case DW_TAG_template_value_param:
16568           suppress_add = 1;
16569           /* Fall through.  */
16570         case DW_TAG_constant:
16571         case DW_TAG_variable:
16572         case DW_TAG_member:
16573           /* Compilation with minimal debug info may result in
16574              variables with missing type entries.  Change the
16575              misleading `void' type to something sensible.  */
16576           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16577             SYMBOL_TYPE (sym)
16578               = objfile_type (objfile)->nodebug_data_symbol;
16579
16580           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16581           /* In the case of DW_TAG_member, we should only be called for
16582              static const members.  */
16583           if (die->tag == DW_TAG_member)
16584             {
16585               /* dwarf2_add_field uses die_is_declaration,
16586                  so we do the same.  */
16587               gdb_assert (die_is_declaration (die, cu));
16588               gdb_assert (attr);
16589             }
16590           if (attr)
16591             {
16592               dwarf2_const_value (attr, sym, cu);
16593               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16594               if (!suppress_add)
16595                 {
16596                   if (attr2 && (DW_UNSND (attr2) != 0))
16597                     list_to_add = &global_symbols;
16598                   else
16599                     list_to_add = cu->list_in_scope;
16600                 }
16601               break;
16602             }
16603           attr = dwarf2_attr (die, DW_AT_location, cu);
16604           if (attr)
16605             {
16606               var_decode_location (attr, sym, cu);
16607               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16608
16609               /* Fortran explicitly imports any global symbols to the local
16610                  scope by DW_TAG_common_block.  */
16611               if (cu->language == language_fortran && die->parent
16612                   && die->parent->tag == DW_TAG_common_block)
16613                 attr2 = NULL;
16614
16615               if (SYMBOL_CLASS (sym) == LOC_STATIC
16616                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16617                   && !dwarf2_per_objfile->has_section_at_zero)
16618                 {
16619                   /* When a static variable is eliminated by the linker,
16620                      the corresponding debug information is not stripped
16621                      out, but the variable address is set to null;
16622                      do not add such variables into symbol table.  */
16623                 }
16624               else if (attr2 && (DW_UNSND (attr2) != 0))
16625                 {
16626                   /* Workaround gfortran PR debug/40040 - it uses
16627                      DW_AT_location for variables in -fPIC libraries which may
16628                      get overriden by other libraries/executable and get
16629                      a different address.  Resolve it by the minimal symbol
16630                      which may come from inferior's executable using copy
16631                      relocation.  Make this workaround only for gfortran as for
16632                      other compilers GDB cannot guess the minimal symbol
16633                      Fortran mangling kind.  */
16634                   if (cu->language == language_fortran && die->parent
16635                       && die->parent->tag == DW_TAG_module
16636                       && cu->producer
16637                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16638                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16639
16640                   /* A variable with DW_AT_external is never static,
16641                      but it may be block-scoped.  */
16642                   list_to_add = (cu->list_in_scope == &file_symbols
16643                                  ? &global_symbols : cu->list_in_scope);
16644                 }
16645               else
16646                 list_to_add = cu->list_in_scope;
16647             }
16648           else
16649             {
16650               /* We do not know the address of this symbol.
16651                  If it is an external symbol and we have type information
16652                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16653                  The address of the variable will then be determined from
16654                  the minimal symbol table whenever the variable is
16655                  referenced.  */
16656               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16657
16658               /* Fortran explicitly imports any global symbols to the local
16659                  scope by DW_TAG_common_block.  */
16660               if (cu->language == language_fortran && die->parent
16661                   && die->parent->tag == DW_TAG_common_block)
16662                 {
16663                   /* SYMBOL_CLASS doesn't matter here because
16664                      read_common_block is going to reset it.  */
16665                   if (!suppress_add)
16666                     list_to_add = cu->list_in_scope;
16667                 }
16668               else if (attr2 && (DW_UNSND (attr2) != 0)
16669                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16670                 {
16671                   /* A variable with DW_AT_external is never static, but it
16672                      may be block-scoped.  */
16673                   list_to_add = (cu->list_in_scope == &file_symbols
16674                                  ? &global_symbols : cu->list_in_scope);
16675
16676                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16677                 }
16678               else if (!die_is_declaration (die, cu))
16679                 {
16680                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16681                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16682                   if (!suppress_add)
16683                     list_to_add = cu->list_in_scope;
16684                 }
16685             }
16686           break;
16687         case DW_TAG_formal_parameter:
16688           /* If we are inside a function, mark this as an argument.  If
16689              not, we might be looking at an argument to an inlined function
16690              when we do not have enough information to show inlined frames;
16691              pretend it's a local variable in that case so that the user can
16692              still see it.  */
16693           if (context_stack_depth > 0
16694               && context_stack[context_stack_depth - 1].name != NULL)
16695             SYMBOL_IS_ARGUMENT (sym) = 1;
16696           attr = dwarf2_attr (die, DW_AT_location, cu);
16697           if (attr)
16698             {
16699               var_decode_location (attr, sym, cu);
16700             }
16701           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16702           if (attr)
16703             {
16704               dwarf2_const_value (attr, sym, cu);
16705             }
16706
16707           list_to_add = cu->list_in_scope;
16708           break;
16709         case DW_TAG_unspecified_parameters:
16710           /* From varargs functions; gdb doesn't seem to have any
16711              interest in this information, so just ignore it for now.
16712              (FIXME?) */
16713           break;
16714         case DW_TAG_template_type_param:
16715           suppress_add = 1;
16716           /* Fall through.  */
16717         case DW_TAG_class_type:
16718         case DW_TAG_interface_type:
16719         case DW_TAG_structure_type:
16720         case DW_TAG_union_type:
16721         case DW_TAG_set_type:
16722         case DW_TAG_enumeration_type:
16723           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16724           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16725
16726           {
16727             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16728                really ever be static objects: otherwise, if you try
16729                to, say, break of a class's method and you're in a file
16730                which doesn't mention that class, it won't work unless
16731                the check for all static symbols in lookup_symbol_aux
16732                saves you.  See the OtherFileClass tests in
16733                gdb.c++/namespace.exp.  */
16734
16735             if (!suppress_add)
16736               {
16737                 list_to_add = (cu->list_in_scope == &file_symbols
16738                                && (cu->language == language_cplus
16739                                    || cu->language == language_java)
16740                                ? &global_symbols : cu->list_in_scope);
16741
16742                 /* The semantics of C++ state that "struct foo {
16743                    ... }" also defines a typedef for "foo".  A Java
16744                    class declaration also defines a typedef for the
16745                    class.  */
16746                 if (cu->language == language_cplus
16747                     || cu->language == language_java
16748                     || cu->language == language_ada)
16749                   {
16750                     /* The symbol's name is already allocated along
16751                        with this objfile, so we don't need to
16752                        duplicate it for the type.  */
16753                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16754                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16755                   }
16756               }
16757           }
16758           break;
16759         case DW_TAG_typedef:
16760           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16761           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16762           list_to_add = cu->list_in_scope;
16763           break;
16764         case DW_TAG_base_type:
16765         case DW_TAG_subrange_type:
16766           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16767           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16768           list_to_add = cu->list_in_scope;
16769           break;
16770         case DW_TAG_enumerator:
16771           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16772           if (attr)
16773             {
16774               dwarf2_const_value (attr, sym, cu);
16775             }
16776           {
16777             /* NOTE: carlton/2003-11-10: See comment above in the
16778                DW_TAG_class_type, etc. block.  */
16779
16780             list_to_add = (cu->list_in_scope == &file_symbols
16781                            && (cu->language == language_cplus
16782                                || cu->language == language_java)
16783                            ? &global_symbols : cu->list_in_scope);
16784           }
16785           break;
16786         case DW_TAG_namespace:
16787           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16788           list_to_add = &global_symbols;
16789           break;
16790         case DW_TAG_common_block:
16791           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16792           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16793           add_symbol_to_list (sym, cu->list_in_scope);
16794           break;
16795         default:
16796           /* Not a tag we recognize.  Hopefully we aren't processing
16797              trash data, but since we must specifically ignore things
16798              we don't recognize, there is nothing else we should do at
16799              this point.  */
16800           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16801                      dwarf_tag_name (die->tag));
16802           break;
16803         }
16804
16805       if (suppress_add)
16806         {
16807           sym->hash_next = objfile->template_symbols;
16808           objfile->template_symbols = sym;
16809           list_to_add = NULL;
16810         }
16811
16812       if (list_to_add != NULL)
16813         add_symbol_to_list (sym, list_to_add);
16814
16815       /* For the benefit of old versions of GCC, check for anonymous
16816          namespaces based on the demangled name.  */
16817       if (!cu->processing_has_namespace_info
16818           && cu->language == language_cplus)
16819         cp_scan_for_anonymous_namespaces (sym, objfile);
16820     }
16821   return (sym);
16822 }
16823
16824 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16825
16826 static struct symbol *
16827 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16828 {
16829   return new_symbol_full (die, type, cu, NULL);
16830 }
16831
16832 /* Given an attr with a DW_FORM_dataN value in host byte order,
16833    zero-extend it as appropriate for the symbol's type.  The DWARF
16834    standard (v4) is not entirely clear about the meaning of using
16835    DW_FORM_dataN for a constant with a signed type, where the type is
16836    wider than the data.  The conclusion of a discussion on the DWARF
16837    list was that this is unspecified.  We choose to always zero-extend
16838    because that is the interpretation long in use by GCC.  */
16839
16840 static gdb_byte *
16841 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
16842                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16843 {
16844   struct objfile *objfile = cu->objfile;
16845   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16846                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16847   LONGEST l = DW_UNSND (attr);
16848
16849   if (bits < sizeof (*value) * 8)
16850     {
16851       l &= ((LONGEST) 1 << bits) - 1;
16852       *value = l;
16853     }
16854   else if (bits == sizeof (*value) * 8)
16855     *value = l;
16856   else
16857     {
16858       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16859       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16860       return bytes;
16861     }
16862
16863   return NULL;
16864 }
16865
16866 /* Read a constant value from an attribute.  Either set *VALUE, or if
16867    the value does not fit in *VALUE, set *BYTES - either already
16868    allocated on the objfile obstack, or newly allocated on OBSTACK,
16869    or, set *BATON, if we translated the constant to a location
16870    expression.  */
16871
16872 static void
16873 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
16874                          const char *name, struct obstack *obstack,
16875                          struct dwarf2_cu *cu,
16876                          LONGEST *value, const gdb_byte **bytes,
16877                          struct dwarf2_locexpr_baton **baton)
16878 {
16879   struct objfile *objfile = cu->objfile;
16880   struct comp_unit_head *cu_header = &cu->header;
16881   struct dwarf_block *blk;
16882   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16883                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16884
16885   *value = 0;
16886   *bytes = NULL;
16887   *baton = NULL;
16888
16889   switch (attr->form)
16890     {
16891     case DW_FORM_addr:
16892     case DW_FORM_GNU_addr_index:
16893       {
16894         gdb_byte *data;
16895
16896         if (TYPE_LENGTH (type) != cu_header->addr_size)
16897           dwarf2_const_value_length_mismatch_complaint (name,
16898                                                         cu_header->addr_size,
16899                                                         TYPE_LENGTH (type));
16900         /* Symbols of this form are reasonably rare, so we just
16901            piggyback on the existing location code rather than writing
16902            a new implementation of symbol_computed_ops.  */
16903         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16904         (*baton)->per_cu = cu->per_cu;
16905         gdb_assert ((*baton)->per_cu);
16906
16907         (*baton)->size = 2 + cu_header->addr_size;
16908         data = obstack_alloc (obstack, (*baton)->size);
16909         (*baton)->data = data;
16910
16911         data[0] = DW_OP_addr;
16912         store_unsigned_integer (&data[1], cu_header->addr_size,
16913                                 byte_order, DW_ADDR (attr));
16914         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16915       }
16916       break;
16917     case DW_FORM_string:
16918     case DW_FORM_strp:
16919     case DW_FORM_GNU_str_index:
16920     case DW_FORM_GNU_strp_alt:
16921       /* DW_STRING is already allocated on the objfile obstack, point
16922          directly to it.  */
16923       *bytes = (const gdb_byte *) DW_STRING (attr);
16924       break;
16925     case DW_FORM_block1:
16926     case DW_FORM_block2:
16927     case DW_FORM_block4:
16928     case DW_FORM_block:
16929     case DW_FORM_exprloc:
16930       blk = DW_BLOCK (attr);
16931       if (TYPE_LENGTH (type) != blk->size)
16932         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16933                                                       TYPE_LENGTH (type));
16934       *bytes = blk->data;
16935       break;
16936
16937       /* The DW_AT_const_value attributes are supposed to carry the
16938          symbol's value "represented as it would be on the target
16939          architecture."  By the time we get here, it's already been
16940          converted to host endianness, so we just need to sign- or
16941          zero-extend it as appropriate.  */
16942     case DW_FORM_data1:
16943       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16944       break;
16945     case DW_FORM_data2:
16946       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16947       break;
16948     case DW_FORM_data4:
16949       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16950       break;
16951     case DW_FORM_data8:
16952       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16953       break;
16954
16955     case DW_FORM_sdata:
16956       *value = DW_SND (attr);
16957       break;
16958
16959     case DW_FORM_udata:
16960       *value = DW_UNSND (attr);
16961       break;
16962
16963     default:
16964       complaint (&symfile_complaints,
16965                  _("unsupported const value attribute form: '%s'"),
16966                  dwarf_form_name (attr->form));
16967       *value = 0;
16968       break;
16969     }
16970 }
16971
16972
16973 /* Copy constant value from an attribute to a symbol.  */
16974
16975 static void
16976 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
16977                     struct dwarf2_cu *cu)
16978 {
16979   struct objfile *objfile = cu->objfile;
16980   struct comp_unit_head *cu_header = &cu->header;
16981   LONGEST value;
16982   const gdb_byte *bytes;
16983   struct dwarf2_locexpr_baton *baton;
16984
16985   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16986                            SYMBOL_PRINT_NAME (sym),
16987                            &objfile->objfile_obstack, cu,
16988                            &value, &bytes, &baton);
16989
16990   if (baton != NULL)
16991     {
16992       SYMBOL_LOCATION_BATON (sym) = baton;
16993       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16994     }
16995   else if (bytes != NULL)
16996      {
16997       SYMBOL_VALUE_BYTES (sym) = bytes;
16998       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16999     }
17000   else
17001     {
17002       SYMBOL_VALUE (sym) = value;
17003       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17004     }
17005 }
17006
17007 /* Return the type of the die in question using its DW_AT_type attribute.  */
17008
17009 static struct type *
17010 die_type (struct die_info *die, struct dwarf2_cu *cu)
17011 {
17012   struct attribute *type_attr;
17013
17014   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17015   if (!type_attr)
17016     {
17017       /* A missing DW_AT_type represents a void type.  */
17018       return objfile_type (cu->objfile)->builtin_void;
17019     }
17020
17021   return lookup_die_type (die, type_attr, cu);
17022 }
17023
17024 /* True iff CU's producer generates GNAT Ada auxiliary information
17025    that allows to find parallel types through that information instead
17026    of having to do expensive parallel lookups by type name.  */
17027
17028 static int
17029 need_gnat_info (struct dwarf2_cu *cu)
17030 {
17031   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17032      of GNAT produces this auxiliary information, without any indication
17033      that it is produced.  Part of enhancing the FSF version of GNAT
17034      to produce that information will be to put in place an indicator
17035      that we can use in order to determine whether the descriptive type
17036      info is available or not.  One suggestion that has been made is
17037      to use a new attribute, attached to the CU die.  For now, assume
17038      that the descriptive type info is not available.  */
17039   return 0;
17040 }
17041
17042 /* Return the auxiliary type of the die in question using its
17043    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17044    attribute is not present.  */
17045
17046 static struct type *
17047 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17048 {
17049   struct attribute *type_attr;
17050
17051   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17052   if (!type_attr)
17053     return NULL;
17054
17055   return lookup_die_type (die, type_attr, cu);
17056 }
17057
17058 /* If DIE has a descriptive_type attribute, then set the TYPE's
17059    descriptive type accordingly.  */
17060
17061 static void
17062 set_descriptive_type (struct type *type, struct die_info *die,
17063                       struct dwarf2_cu *cu)
17064 {
17065   struct type *descriptive_type = die_descriptive_type (die, cu);
17066
17067   if (descriptive_type)
17068     {
17069       ALLOCATE_GNAT_AUX_TYPE (type);
17070       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17071     }
17072 }
17073
17074 /* Return the containing type of the die in question using its
17075    DW_AT_containing_type attribute.  */
17076
17077 static struct type *
17078 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17079 {
17080   struct attribute *type_attr;
17081
17082   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17083   if (!type_attr)
17084     error (_("Dwarf Error: Problem turning containing type into gdb type "
17085              "[in module %s]"), cu->objfile->name);
17086
17087   return lookup_die_type (die, type_attr, cu);
17088 }
17089
17090 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17091
17092 static struct type *
17093 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17094 {
17095   struct objfile *objfile = dwarf2_per_objfile->objfile;
17096   char *message, *saved;
17097
17098   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17099                         objfile->name,
17100                         cu->header.offset.sect_off,
17101                         die->offset.sect_off);
17102   saved = obstack_copy0 (&objfile->objfile_obstack,
17103                          message, strlen (message));
17104   xfree (message);
17105
17106   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17107 }
17108
17109 /* Look up the type of DIE in CU using its type attribute ATTR.
17110    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17111    DW_AT_containing_type.
17112    If there is no type substitute an error marker.  */
17113
17114 static struct type *
17115 lookup_die_type (struct die_info *die, const struct attribute *attr,
17116                  struct dwarf2_cu *cu)
17117 {
17118   struct objfile *objfile = cu->objfile;
17119   struct type *this_type;
17120
17121   gdb_assert (attr->name == DW_AT_type
17122               || attr->name == DW_AT_GNAT_descriptive_type
17123               || attr->name == DW_AT_containing_type);
17124
17125   /* First see if we have it cached.  */
17126
17127   if (attr->form == DW_FORM_GNU_ref_alt)
17128     {
17129       struct dwarf2_per_cu_data *per_cu;
17130       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17131
17132       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17133       this_type = get_die_type_at_offset (offset, per_cu);
17134     }
17135   else if (attr_form_is_ref (attr))
17136     {
17137       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17138
17139       this_type = get_die_type_at_offset (offset, cu->per_cu);
17140     }
17141   else if (attr->form == DW_FORM_ref_sig8)
17142     {
17143       ULONGEST signature = DW_SIGNATURE (attr);
17144
17145       return get_signatured_type (die, signature, cu);
17146     }
17147   else
17148     {
17149       complaint (&symfile_complaints,
17150                  _("Dwarf Error: Bad type attribute %s in DIE"
17151                    " at 0x%x [in module %s]"),
17152                  dwarf_attr_name (attr->name), die->offset.sect_off,
17153                  objfile->name);
17154       return build_error_marker_type (cu, die);
17155     }
17156
17157   /* If not cached we need to read it in.  */
17158
17159   if (this_type == NULL)
17160     {
17161       struct die_info *type_die = NULL;
17162       struct dwarf2_cu *type_cu = cu;
17163
17164       if (attr_form_is_ref (attr))
17165         type_die = follow_die_ref (die, attr, &type_cu);
17166       if (type_die == NULL)
17167         return build_error_marker_type (cu, die);
17168       /* If we find the type now, it's probably because the type came
17169          from an inter-CU reference and the type's CU got expanded before
17170          ours.  */
17171       this_type = read_type_die (type_die, type_cu);
17172     }
17173
17174   /* If we still don't have a type use an error marker.  */
17175
17176   if (this_type == NULL)
17177     return build_error_marker_type (cu, die);
17178
17179   return this_type;
17180 }
17181
17182 /* Return the type in DIE, CU.
17183    Returns NULL for invalid types.
17184
17185    This first does a lookup in die_type_hash,
17186    and only reads the die in if necessary.
17187
17188    NOTE: This can be called when reading in partial or full symbols.  */
17189
17190 static struct type *
17191 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17192 {
17193   struct type *this_type;
17194
17195   this_type = get_die_type (die, cu);
17196   if (this_type)
17197     return this_type;
17198
17199   return read_type_die_1 (die, cu);
17200 }
17201
17202 /* Read the type in DIE, CU.
17203    Returns NULL for invalid types.  */
17204
17205 static struct type *
17206 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17207 {
17208   struct type *this_type = NULL;
17209
17210   switch (die->tag)
17211     {
17212     case DW_TAG_class_type:
17213     case DW_TAG_interface_type:
17214     case DW_TAG_structure_type:
17215     case DW_TAG_union_type:
17216       this_type = read_structure_type (die, cu);
17217       break;
17218     case DW_TAG_enumeration_type:
17219       this_type = read_enumeration_type (die, cu);
17220       break;
17221     case DW_TAG_subprogram:
17222     case DW_TAG_subroutine_type:
17223     case DW_TAG_inlined_subroutine:
17224       this_type = read_subroutine_type (die, cu);
17225       break;
17226     case DW_TAG_array_type:
17227       this_type = read_array_type (die, cu);
17228       break;
17229     case DW_TAG_set_type:
17230       this_type = read_set_type (die, cu);
17231       break;
17232     case DW_TAG_pointer_type:
17233       this_type = read_tag_pointer_type (die, cu);
17234       break;
17235     case DW_TAG_ptr_to_member_type:
17236       this_type = read_tag_ptr_to_member_type (die, cu);
17237       break;
17238     case DW_TAG_reference_type:
17239       this_type = read_tag_reference_type (die, cu);
17240       break;
17241     case DW_TAG_const_type:
17242       this_type = read_tag_const_type (die, cu);
17243       break;
17244     case DW_TAG_volatile_type:
17245       this_type = read_tag_volatile_type (die, cu);
17246       break;
17247     case DW_TAG_restrict_type:
17248       this_type = read_tag_restrict_type (die, cu);
17249       break;
17250     case DW_TAG_string_type:
17251       this_type = read_tag_string_type (die, cu);
17252       break;
17253     case DW_TAG_typedef:
17254       this_type = read_typedef (die, cu);
17255       break;
17256     case DW_TAG_subrange_type:
17257       this_type = read_subrange_type (die, cu);
17258       break;
17259     case DW_TAG_base_type:
17260       this_type = read_base_type (die, cu);
17261       break;
17262     case DW_TAG_unspecified_type:
17263       this_type = read_unspecified_type (die, cu);
17264       break;
17265     case DW_TAG_namespace:
17266       this_type = read_namespace_type (die, cu);
17267       break;
17268     case DW_TAG_module:
17269       this_type = read_module_type (die, cu);
17270       break;
17271     default:
17272       complaint (&symfile_complaints,
17273                  _("unexpected tag in read_type_die: '%s'"),
17274                  dwarf_tag_name (die->tag));
17275       break;
17276     }
17277
17278   return this_type;
17279 }
17280
17281 /* See if we can figure out if the class lives in a namespace.  We do
17282    this by looking for a member function; its demangled name will
17283    contain namespace info, if there is any.
17284    Return the computed name or NULL.
17285    Space for the result is allocated on the objfile's obstack.
17286    This is the full-die version of guess_partial_die_structure_name.
17287    In this case we know DIE has no useful parent.  */
17288
17289 static char *
17290 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17291 {
17292   struct die_info *spec_die;
17293   struct dwarf2_cu *spec_cu;
17294   struct die_info *child;
17295
17296   spec_cu = cu;
17297   spec_die = die_specification (die, &spec_cu);
17298   if (spec_die != NULL)
17299     {
17300       die = spec_die;
17301       cu = spec_cu;
17302     }
17303
17304   for (child = die->child;
17305        child != NULL;
17306        child = child->sibling)
17307     {
17308       if (child->tag == DW_TAG_subprogram)
17309         {
17310           struct attribute *attr;
17311
17312           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17313           if (attr == NULL)
17314             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17315           if (attr != NULL)
17316             {
17317               char *actual_name
17318                 = language_class_name_from_physname (cu->language_defn,
17319                                                      DW_STRING (attr));
17320               char *name = NULL;
17321
17322               if (actual_name != NULL)
17323                 {
17324                   const char *die_name = dwarf2_name (die, cu);
17325
17326                   if (die_name != NULL
17327                       && strcmp (die_name, actual_name) != 0)
17328                     {
17329                       /* Strip off the class name from the full name.
17330                          We want the prefix.  */
17331                       int die_name_len = strlen (die_name);
17332                       int actual_name_len = strlen (actual_name);
17333
17334                       /* Test for '::' as a sanity check.  */
17335                       if (actual_name_len > die_name_len + 2
17336                           && actual_name[actual_name_len
17337                                          - die_name_len - 1] == ':')
17338                         name =
17339                           obstack_copy0 (&cu->objfile->objfile_obstack,
17340                                          actual_name,
17341                                          actual_name_len - die_name_len - 2);
17342                     }
17343                 }
17344               xfree (actual_name);
17345               return name;
17346             }
17347         }
17348     }
17349
17350   return NULL;
17351 }
17352
17353 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17354    prefix part in such case.  See
17355    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17356
17357 static char *
17358 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17359 {
17360   struct attribute *attr;
17361   char *base;
17362
17363   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17364       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17365     return NULL;
17366
17367   attr = dwarf2_attr (die, DW_AT_name, cu);
17368   if (attr != NULL && DW_STRING (attr) != NULL)
17369     return NULL;
17370
17371   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17372   if (attr == NULL)
17373     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17374   if (attr == NULL || DW_STRING (attr) == NULL)
17375     return NULL;
17376
17377   /* dwarf2_name had to be already called.  */
17378   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17379
17380   /* Strip the base name, keep any leading namespaces/classes.  */
17381   base = strrchr (DW_STRING (attr), ':');
17382   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17383     return "";
17384
17385   return obstack_copy0 (&cu->objfile->objfile_obstack,
17386                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17387 }
17388
17389 /* Return the name of the namespace/class that DIE is defined within,
17390    or "" if we can't tell.  The caller should not xfree the result.
17391
17392    For example, if we're within the method foo() in the following
17393    code:
17394
17395    namespace N {
17396      class C {
17397        void foo () {
17398        }
17399      };
17400    }
17401
17402    then determine_prefix on foo's die will return "N::C".  */
17403
17404 static const char *
17405 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17406 {
17407   struct die_info *parent, *spec_die;
17408   struct dwarf2_cu *spec_cu;
17409   struct type *parent_type;
17410   char *retval;
17411
17412   if (cu->language != language_cplus && cu->language != language_java
17413       && cu->language != language_fortran)
17414     return "";
17415
17416   retval = anonymous_struct_prefix (die, cu);
17417   if (retval)
17418     return retval;
17419
17420   /* We have to be careful in the presence of DW_AT_specification.
17421      For example, with GCC 3.4, given the code
17422
17423      namespace N {
17424        void foo() {
17425          // Definition of N::foo.
17426        }
17427      }
17428
17429      then we'll have a tree of DIEs like this:
17430
17431      1: DW_TAG_compile_unit
17432        2: DW_TAG_namespace        // N
17433          3: DW_TAG_subprogram     // declaration of N::foo
17434        4: DW_TAG_subprogram       // definition of N::foo
17435             DW_AT_specification   // refers to die #3
17436
17437      Thus, when processing die #4, we have to pretend that we're in
17438      the context of its DW_AT_specification, namely the contex of die
17439      #3.  */
17440   spec_cu = cu;
17441   spec_die = die_specification (die, &spec_cu);
17442   if (spec_die == NULL)
17443     parent = die->parent;
17444   else
17445     {
17446       parent = spec_die->parent;
17447       cu = spec_cu;
17448     }
17449
17450   if (parent == NULL)
17451     return "";
17452   else if (parent->building_fullname)
17453     {
17454       const char *name;
17455       const char *parent_name;
17456
17457       /* It has been seen on RealView 2.2 built binaries,
17458          DW_TAG_template_type_param types actually _defined_ as
17459          children of the parent class:
17460
17461          enum E {};
17462          template class <class Enum> Class{};
17463          Class<enum E> class_e;
17464
17465          1: DW_TAG_class_type (Class)
17466            2: DW_TAG_enumeration_type (E)
17467              3: DW_TAG_enumerator (enum1:0)
17468              3: DW_TAG_enumerator (enum2:1)
17469              ...
17470            2: DW_TAG_template_type_param
17471               DW_AT_type  DW_FORM_ref_udata (E)
17472
17473          Besides being broken debug info, it can put GDB into an
17474          infinite loop.  Consider:
17475
17476          When we're building the full name for Class<E>, we'll start
17477          at Class, and go look over its template type parameters,
17478          finding E.  We'll then try to build the full name of E, and
17479          reach here.  We're now trying to build the full name of E,
17480          and look over the parent DIE for containing scope.  In the
17481          broken case, if we followed the parent DIE of E, we'd again
17482          find Class, and once again go look at its template type
17483          arguments, etc., etc.  Simply don't consider such parent die
17484          as source-level parent of this die (it can't be, the language
17485          doesn't allow it), and break the loop here.  */
17486       name = dwarf2_name (die, cu);
17487       parent_name = dwarf2_name (parent, cu);
17488       complaint (&symfile_complaints,
17489                  _("template param type '%s' defined within parent '%s'"),
17490                  name ? name : "<unknown>",
17491                  parent_name ? parent_name : "<unknown>");
17492       return "";
17493     }
17494   else
17495     switch (parent->tag)
17496       {
17497       case DW_TAG_namespace:
17498         parent_type = read_type_die (parent, cu);
17499         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17500            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17501            Work around this problem here.  */
17502         if (cu->language == language_cplus
17503             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17504           return "";
17505         /* We give a name to even anonymous namespaces.  */
17506         return TYPE_TAG_NAME (parent_type);
17507       case DW_TAG_class_type:
17508       case DW_TAG_interface_type:
17509       case DW_TAG_structure_type:
17510       case DW_TAG_union_type:
17511       case DW_TAG_module:
17512         parent_type = read_type_die (parent, cu);
17513         if (TYPE_TAG_NAME (parent_type) != NULL)
17514           return TYPE_TAG_NAME (parent_type);
17515         else
17516           /* An anonymous structure is only allowed non-static data
17517              members; no typedefs, no member functions, et cetera.
17518              So it does not need a prefix.  */
17519           return "";
17520       case DW_TAG_compile_unit:
17521       case DW_TAG_partial_unit:
17522         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17523         if (cu->language == language_cplus
17524             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17525             && die->child != NULL
17526             && (die->tag == DW_TAG_class_type
17527                 || die->tag == DW_TAG_structure_type
17528                 || die->tag == DW_TAG_union_type))
17529           {
17530             char *name = guess_full_die_structure_name (die, cu);
17531             if (name != NULL)
17532               return name;
17533           }
17534         return "";
17535       default:
17536         return determine_prefix (parent, cu);
17537       }
17538 }
17539
17540 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17541    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17542    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17543    an obconcat, otherwise allocate storage for the result.  The CU argument is
17544    used to determine the language and hence, the appropriate separator.  */
17545
17546 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17547
17548 static char *
17549 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17550                  int physname, struct dwarf2_cu *cu)
17551 {
17552   const char *lead = "";
17553   const char *sep;
17554
17555   if (suffix == NULL || suffix[0] == '\0'
17556       || prefix == NULL || prefix[0] == '\0')
17557     sep = "";
17558   else if (cu->language == language_java)
17559     sep = ".";
17560   else if (cu->language == language_fortran && physname)
17561     {
17562       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17563          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17564
17565       lead = "__";
17566       sep = "_MOD_";
17567     }
17568   else
17569     sep = "::";
17570
17571   if (prefix == NULL)
17572     prefix = "";
17573   if (suffix == NULL)
17574     suffix = "";
17575
17576   if (obs == NULL)
17577     {
17578       char *retval
17579         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17580
17581       strcpy (retval, lead);
17582       strcat (retval, prefix);
17583       strcat (retval, sep);
17584       strcat (retval, suffix);
17585       return retval;
17586     }
17587   else
17588     {
17589       /* We have an obstack.  */
17590       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17591     }
17592 }
17593
17594 /* Return sibling of die, NULL if no sibling.  */
17595
17596 static struct die_info *
17597 sibling_die (struct die_info *die)
17598 {
17599   return die->sibling;
17600 }
17601
17602 /* Get name of a die, return NULL if not found.  */
17603
17604 static const char *
17605 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17606                           struct obstack *obstack)
17607 {
17608   if (name && cu->language == language_cplus)
17609     {
17610       char *canon_name = cp_canonicalize_string (name);
17611
17612       if (canon_name != NULL)
17613         {
17614           if (strcmp (canon_name, name) != 0)
17615             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17616           xfree (canon_name);
17617         }
17618     }
17619
17620   return name;
17621 }
17622
17623 /* Get name of a die, return NULL if not found.  */
17624
17625 static const char *
17626 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17627 {
17628   struct attribute *attr;
17629
17630   attr = dwarf2_attr (die, DW_AT_name, cu);
17631   if ((!attr || !DW_STRING (attr))
17632       && die->tag != DW_TAG_class_type
17633       && die->tag != DW_TAG_interface_type
17634       && die->tag != DW_TAG_structure_type
17635       && die->tag != DW_TAG_union_type)
17636     return NULL;
17637
17638   switch (die->tag)
17639     {
17640     case DW_TAG_compile_unit:
17641     case DW_TAG_partial_unit:
17642       /* Compilation units have a DW_AT_name that is a filename, not
17643          a source language identifier.  */
17644     case DW_TAG_enumeration_type:
17645     case DW_TAG_enumerator:
17646       /* These tags always have simple identifiers already; no need
17647          to canonicalize them.  */
17648       return DW_STRING (attr);
17649
17650     case DW_TAG_subprogram:
17651       /* Java constructors will all be named "<init>", so return
17652          the class name when we see this special case.  */
17653       if (cu->language == language_java
17654           && DW_STRING (attr) != NULL
17655           && strcmp (DW_STRING (attr), "<init>") == 0)
17656         {
17657           struct dwarf2_cu *spec_cu = cu;
17658           struct die_info *spec_die;
17659
17660           /* GCJ will output '<init>' for Java constructor names.
17661              For this special case, return the name of the parent class.  */
17662
17663           /* GCJ may output suprogram DIEs with AT_specification set.
17664              If so, use the name of the specified DIE.  */
17665           spec_die = die_specification (die, &spec_cu);
17666           if (spec_die != NULL)
17667             return dwarf2_name (spec_die, spec_cu);
17668
17669           do
17670             {
17671               die = die->parent;
17672               if (die->tag == DW_TAG_class_type)
17673                 return dwarf2_name (die, cu);
17674             }
17675           while (die->tag != DW_TAG_compile_unit
17676                  && die->tag != DW_TAG_partial_unit);
17677         }
17678       break;
17679
17680     case DW_TAG_class_type:
17681     case DW_TAG_interface_type:
17682     case DW_TAG_structure_type:
17683     case DW_TAG_union_type:
17684       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17685          structures or unions.  These were of the form "._%d" in GCC 4.1,
17686          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17687          and GCC 4.4.  We work around this problem by ignoring these.  */
17688       if (attr && DW_STRING (attr)
17689           && (strncmp (DW_STRING (attr), "._", 2) == 0
17690               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17691         return NULL;
17692
17693       /* GCC might emit a nameless typedef that has a linkage name.  See
17694          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17695       if (!attr || DW_STRING (attr) == NULL)
17696         {
17697           char *demangled = NULL;
17698
17699           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17700           if (attr == NULL)
17701             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17702
17703           if (attr == NULL || DW_STRING (attr) == NULL)
17704             return NULL;
17705
17706           /* Avoid demangling DW_STRING (attr) the second time on a second
17707              call for the same DIE.  */
17708           if (!DW_STRING_IS_CANONICAL (attr))
17709             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17710
17711           if (demangled)
17712             {
17713               char *base;
17714
17715               /* FIXME: we already did this for the partial symbol... */
17716               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17717                                                 demangled, strlen (demangled));
17718               DW_STRING_IS_CANONICAL (attr) = 1;
17719               xfree (demangled);
17720
17721               /* Strip any leading namespaces/classes, keep only the base name.
17722                  DW_AT_name for named DIEs does not contain the prefixes.  */
17723               base = strrchr (DW_STRING (attr), ':');
17724               if (base && base > DW_STRING (attr) && base[-1] == ':')
17725                 return &base[1];
17726               else
17727                 return DW_STRING (attr);
17728             }
17729         }
17730       break;
17731
17732     default:
17733       break;
17734     }
17735
17736   if (!DW_STRING_IS_CANONICAL (attr))
17737     {
17738       DW_STRING (attr)
17739         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17740                                     &cu->objfile->objfile_obstack);
17741       DW_STRING_IS_CANONICAL (attr) = 1;
17742     }
17743   return DW_STRING (attr);
17744 }
17745
17746 /* Return the die that this die in an extension of, or NULL if there
17747    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17748    containing the return value on output.  */
17749
17750 static struct die_info *
17751 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17752 {
17753   struct attribute *attr;
17754
17755   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17756   if (attr == NULL)
17757     return NULL;
17758
17759   return follow_die_ref (die, attr, ext_cu);
17760 }
17761
17762 /* Convert a DIE tag into its string name.  */
17763
17764 static const char *
17765 dwarf_tag_name (unsigned tag)
17766 {
17767   const char *name = get_DW_TAG_name (tag);
17768
17769   if (name == NULL)
17770     return "DW_TAG_<unknown>";
17771
17772   return name;
17773 }
17774
17775 /* Convert a DWARF attribute code into its string name.  */
17776
17777 static const char *
17778 dwarf_attr_name (unsigned attr)
17779 {
17780   const char *name;
17781
17782 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17783   if (attr == DW_AT_MIPS_fde)
17784     return "DW_AT_MIPS_fde";
17785 #else
17786   if (attr == DW_AT_HP_block_index)
17787     return "DW_AT_HP_block_index";
17788 #endif
17789
17790   name = get_DW_AT_name (attr);
17791
17792   if (name == NULL)
17793     return "DW_AT_<unknown>";
17794
17795   return name;
17796 }
17797
17798 /* Convert a DWARF value form code into its string name.  */
17799
17800 static const char *
17801 dwarf_form_name (unsigned form)
17802 {
17803   const char *name = get_DW_FORM_name (form);
17804
17805   if (name == NULL)
17806     return "DW_FORM_<unknown>";
17807
17808   return name;
17809 }
17810
17811 static char *
17812 dwarf_bool_name (unsigned mybool)
17813 {
17814   if (mybool)
17815     return "TRUE";
17816   else
17817     return "FALSE";
17818 }
17819
17820 /* Convert a DWARF type code into its string name.  */
17821
17822 static const char *
17823 dwarf_type_encoding_name (unsigned enc)
17824 {
17825   const char *name = get_DW_ATE_name (enc);
17826
17827   if (name == NULL)
17828     return "DW_ATE_<unknown>";
17829
17830   return name;
17831 }
17832
17833 static void
17834 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17835 {
17836   unsigned int i;
17837
17838   print_spaces (indent, f);
17839   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17840            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17841
17842   if (die->parent != NULL)
17843     {
17844       print_spaces (indent, f);
17845       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17846                           die->parent->offset.sect_off);
17847     }
17848
17849   print_spaces (indent, f);
17850   fprintf_unfiltered (f, "  has children: %s\n",
17851            dwarf_bool_name (die->child != NULL));
17852
17853   print_spaces (indent, f);
17854   fprintf_unfiltered (f, "  attributes:\n");
17855
17856   for (i = 0; i < die->num_attrs; ++i)
17857     {
17858       print_spaces (indent, f);
17859       fprintf_unfiltered (f, "    %s (%s) ",
17860                dwarf_attr_name (die->attrs[i].name),
17861                dwarf_form_name (die->attrs[i].form));
17862
17863       switch (die->attrs[i].form)
17864         {
17865         case DW_FORM_addr:
17866         case DW_FORM_GNU_addr_index:
17867           fprintf_unfiltered (f, "address: ");
17868           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17869           break;
17870         case DW_FORM_block2:
17871         case DW_FORM_block4:
17872         case DW_FORM_block:
17873         case DW_FORM_block1:
17874           fprintf_unfiltered (f, "block: size %s",
17875                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17876           break;
17877         case DW_FORM_exprloc:
17878           fprintf_unfiltered (f, "expression: size %s",
17879                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17880           break;
17881         case DW_FORM_ref_addr:
17882           fprintf_unfiltered (f, "ref address: ");
17883           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17884           break;
17885         case DW_FORM_GNU_ref_alt:
17886           fprintf_unfiltered (f, "alt ref address: ");
17887           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17888           break;
17889         case DW_FORM_ref1:
17890         case DW_FORM_ref2:
17891         case DW_FORM_ref4:
17892         case DW_FORM_ref8:
17893         case DW_FORM_ref_udata:
17894           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17895                               (long) (DW_UNSND (&die->attrs[i])));
17896           break;
17897         case DW_FORM_data1:
17898         case DW_FORM_data2:
17899         case DW_FORM_data4:
17900         case DW_FORM_data8:
17901         case DW_FORM_udata:
17902         case DW_FORM_sdata:
17903           fprintf_unfiltered (f, "constant: %s",
17904                               pulongest (DW_UNSND (&die->attrs[i])));
17905           break;
17906         case DW_FORM_sec_offset:
17907           fprintf_unfiltered (f, "section offset: %s",
17908                               pulongest (DW_UNSND (&die->attrs[i])));
17909           break;
17910         case DW_FORM_ref_sig8:
17911           fprintf_unfiltered (f, "signature: %s",
17912                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17913           break;
17914         case DW_FORM_string:
17915         case DW_FORM_strp:
17916         case DW_FORM_GNU_str_index:
17917         case DW_FORM_GNU_strp_alt:
17918           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17919                    DW_STRING (&die->attrs[i])
17920                    ? DW_STRING (&die->attrs[i]) : "",
17921                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17922           break;
17923         case DW_FORM_flag:
17924           if (DW_UNSND (&die->attrs[i]))
17925             fprintf_unfiltered (f, "flag: TRUE");
17926           else
17927             fprintf_unfiltered (f, "flag: FALSE");
17928           break;
17929         case DW_FORM_flag_present:
17930           fprintf_unfiltered (f, "flag: TRUE");
17931           break;
17932         case DW_FORM_indirect:
17933           /* The reader will have reduced the indirect form to
17934              the "base form" so this form should not occur.  */
17935           fprintf_unfiltered (f, 
17936                               "unexpected attribute form: DW_FORM_indirect");
17937           break;
17938         default:
17939           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17940                    die->attrs[i].form);
17941           break;
17942         }
17943       fprintf_unfiltered (f, "\n");
17944     }
17945 }
17946
17947 static void
17948 dump_die_for_error (struct die_info *die)
17949 {
17950   dump_die_shallow (gdb_stderr, 0, die);
17951 }
17952
17953 static void
17954 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17955 {
17956   int indent = level * 4;
17957
17958   gdb_assert (die != NULL);
17959
17960   if (level >= max_level)
17961     return;
17962
17963   dump_die_shallow (f, indent, die);
17964
17965   if (die->child != NULL)
17966     {
17967       print_spaces (indent, f);
17968       fprintf_unfiltered (f, "  Children:");
17969       if (level + 1 < max_level)
17970         {
17971           fprintf_unfiltered (f, "\n");
17972           dump_die_1 (f, level + 1, max_level, die->child);
17973         }
17974       else
17975         {
17976           fprintf_unfiltered (f,
17977                               " [not printed, max nesting level reached]\n");
17978         }
17979     }
17980
17981   if (die->sibling != NULL && level > 0)
17982     {
17983       dump_die_1 (f, level, max_level, die->sibling);
17984     }
17985 }
17986
17987 /* This is called from the pdie macro in gdbinit.in.
17988    It's not static so gcc will keep a copy callable from gdb.  */
17989
17990 void
17991 dump_die (struct die_info *die, int max_level)
17992 {
17993   dump_die_1 (gdb_stdlog, 0, max_level, die);
17994 }
17995
17996 static void
17997 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17998 {
17999   void **slot;
18000
18001   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18002                                    INSERT);
18003
18004   *slot = die;
18005 }
18006
18007 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18008    required kind.  */
18009
18010 static sect_offset
18011 dwarf2_get_ref_die_offset (const struct attribute *attr)
18012 {
18013   sect_offset retval = { DW_UNSND (attr) };
18014
18015   if (attr_form_is_ref (attr))
18016     return retval;
18017
18018   retval.sect_off = 0;
18019   complaint (&symfile_complaints,
18020              _("unsupported die ref attribute form: '%s'"),
18021              dwarf_form_name (attr->form));
18022   return retval;
18023 }
18024
18025 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18026  * the value held by the attribute is not constant.  */
18027
18028 static LONGEST
18029 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18030 {
18031   if (attr->form == DW_FORM_sdata)
18032     return DW_SND (attr);
18033   else if (attr->form == DW_FORM_udata
18034            || attr->form == DW_FORM_data1
18035            || attr->form == DW_FORM_data2
18036            || attr->form == DW_FORM_data4
18037            || attr->form == DW_FORM_data8)
18038     return DW_UNSND (attr);
18039   else
18040     {
18041       complaint (&symfile_complaints,
18042                  _("Attribute value is not a constant (%s)"),
18043                  dwarf_form_name (attr->form));
18044       return default_value;
18045     }
18046 }
18047
18048 /* Follow reference or signature attribute ATTR of SRC_DIE.
18049    On entry *REF_CU is the CU of SRC_DIE.
18050    On exit *REF_CU is the CU of the result.  */
18051
18052 static struct die_info *
18053 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18054                        struct dwarf2_cu **ref_cu)
18055 {
18056   struct die_info *die;
18057
18058   if (attr_form_is_ref (attr))
18059     die = follow_die_ref (src_die, attr, ref_cu);
18060   else if (attr->form == DW_FORM_ref_sig8)
18061     die = follow_die_sig (src_die, attr, ref_cu);
18062   else
18063     {
18064       dump_die_for_error (src_die);
18065       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18066              (*ref_cu)->objfile->name);
18067     }
18068
18069   return die;
18070 }
18071
18072 /* Follow reference OFFSET.
18073    On entry *REF_CU is the CU of the source die referencing OFFSET.
18074    On exit *REF_CU is the CU of the result.
18075    Returns NULL if OFFSET is invalid.  */
18076
18077 static struct die_info *
18078 follow_die_offset (sect_offset offset, int offset_in_dwz,
18079                    struct dwarf2_cu **ref_cu)
18080 {
18081   struct die_info temp_die;
18082   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18083
18084   gdb_assert (cu->per_cu != NULL);
18085
18086   target_cu = cu;
18087
18088   if (cu->per_cu->is_debug_types)
18089     {
18090       /* .debug_types CUs cannot reference anything outside their CU.
18091          If they need to, they have to reference a signatured type via
18092          DW_FORM_ref_sig8.  */
18093       if (! offset_in_cu_p (&cu->header, offset))
18094         return NULL;
18095     }
18096   else if (offset_in_dwz != cu->per_cu->is_dwz
18097            || ! offset_in_cu_p (&cu->header, offset))
18098     {
18099       struct dwarf2_per_cu_data *per_cu;
18100
18101       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18102                                                  cu->objfile);
18103
18104       /* If necessary, add it to the queue and load its DIEs.  */
18105       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18106         load_full_comp_unit (per_cu, cu->language);
18107
18108       target_cu = per_cu->cu;
18109     }
18110   else if (cu->dies == NULL)
18111     {
18112       /* We're loading full DIEs during partial symbol reading.  */
18113       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18114       load_full_comp_unit (cu->per_cu, language_minimal);
18115     }
18116
18117   *ref_cu = target_cu;
18118   temp_die.offset = offset;
18119   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18120 }
18121
18122 /* Follow reference attribute ATTR of SRC_DIE.
18123    On entry *REF_CU is the CU of SRC_DIE.
18124    On exit *REF_CU is the CU of the result.  */
18125
18126 static struct die_info *
18127 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18128                 struct dwarf2_cu **ref_cu)
18129 {
18130   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18131   struct dwarf2_cu *cu = *ref_cu;
18132   struct die_info *die;
18133
18134   die = follow_die_offset (offset,
18135                            (attr->form == DW_FORM_GNU_ref_alt
18136                             || cu->per_cu->is_dwz),
18137                            ref_cu);
18138   if (!die)
18139     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18140            "at 0x%x [in module %s]"),
18141            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
18142
18143   return die;
18144 }
18145
18146 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18147    Returned value is intended for DW_OP_call*.  Returned
18148    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18149
18150 struct dwarf2_locexpr_baton
18151 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18152                                struct dwarf2_per_cu_data *per_cu,
18153                                CORE_ADDR (*get_frame_pc) (void *baton),
18154                                void *baton)
18155 {
18156   struct dwarf2_cu *cu;
18157   struct die_info *die;
18158   struct attribute *attr;
18159   struct dwarf2_locexpr_baton retval;
18160
18161   dw2_setup (per_cu->objfile);
18162
18163   if (per_cu->cu == NULL)
18164     load_cu (per_cu);
18165   cu = per_cu->cu;
18166
18167   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18168   if (!die)
18169     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18170            offset.sect_off, per_cu->objfile->name);
18171
18172   attr = dwarf2_attr (die, DW_AT_location, cu);
18173   if (!attr)
18174     {
18175       /* DWARF: "If there is no such attribute, then there is no effect.".
18176          DATA is ignored if SIZE is 0.  */
18177
18178       retval.data = NULL;
18179       retval.size = 0;
18180     }
18181   else if (attr_form_is_section_offset (attr))
18182     {
18183       struct dwarf2_loclist_baton loclist_baton;
18184       CORE_ADDR pc = (*get_frame_pc) (baton);
18185       size_t size;
18186
18187       fill_in_loclist_baton (cu, &loclist_baton, attr);
18188
18189       retval.data = dwarf2_find_location_expression (&loclist_baton,
18190                                                      &size, pc);
18191       retval.size = size;
18192     }
18193   else
18194     {
18195       if (!attr_form_is_block (attr))
18196         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18197                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18198                offset.sect_off, per_cu->objfile->name);
18199
18200       retval.data = DW_BLOCK (attr)->data;
18201       retval.size = DW_BLOCK (attr)->size;
18202     }
18203   retval.per_cu = cu->per_cu;
18204
18205   age_cached_comp_units ();
18206
18207   return retval;
18208 }
18209
18210 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18211    offset.  */
18212
18213 struct dwarf2_locexpr_baton
18214 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18215                              struct dwarf2_per_cu_data *per_cu,
18216                              CORE_ADDR (*get_frame_pc) (void *baton),
18217                              void *baton)
18218 {
18219   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18220
18221   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18222 }
18223
18224 /* Write a constant of a given type as target-ordered bytes into
18225    OBSTACK.  */
18226
18227 static const gdb_byte *
18228 write_constant_as_bytes (struct obstack *obstack,
18229                          enum bfd_endian byte_order,
18230                          struct type *type,
18231                          ULONGEST value,
18232                          LONGEST *len)
18233 {
18234   gdb_byte *result;
18235
18236   *len = TYPE_LENGTH (type);
18237   result = obstack_alloc (obstack, *len);
18238   store_unsigned_integer (result, *len, byte_order, value);
18239
18240   return result;
18241 }
18242
18243 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18244    pointer to the constant bytes and set LEN to the length of the
18245    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18246    does not have a DW_AT_const_value, return NULL.  */
18247
18248 const gdb_byte *
18249 dwarf2_fetch_constant_bytes (sect_offset offset,
18250                              struct dwarf2_per_cu_data *per_cu,
18251                              struct obstack *obstack,
18252                              LONGEST *len)
18253 {
18254   struct dwarf2_cu *cu;
18255   struct die_info *die;
18256   struct attribute *attr;
18257   const gdb_byte *result = NULL;
18258   struct type *type;
18259   LONGEST value;
18260   enum bfd_endian byte_order;
18261
18262   dw2_setup (per_cu->objfile);
18263
18264   if (per_cu->cu == NULL)
18265     load_cu (per_cu);
18266   cu = per_cu->cu;
18267
18268   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18269   if (!die)
18270     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18271            offset.sect_off, per_cu->objfile->name);
18272
18273
18274   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18275   if (attr == NULL)
18276     return NULL;
18277
18278   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18279                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18280
18281   switch (attr->form)
18282     {
18283     case DW_FORM_addr:
18284     case DW_FORM_GNU_addr_index:
18285       {
18286         gdb_byte *tem;
18287
18288         *len = cu->header.addr_size;
18289         tem = obstack_alloc (obstack, *len);
18290         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18291         result = tem;
18292       }
18293       break;
18294     case DW_FORM_string:
18295     case DW_FORM_strp:
18296     case DW_FORM_GNU_str_index:
18297     case DW_FORM_GNU_strp_alt:
18298       /* DW_STRING is already allocated on the objfile obstack, point
18299          directly to it.  */
18300       result = (const gdb_byte *) DW_STRING (attr);
18301       *len = strlen (DW_STRING (attr));
18302       break;
18303     case DW_FORM_block1:
18304     case DW_FORM_block2:
18305     case DW_FORM_block4:
18306     case DW_FORM_block:
18307     case DW_FORM_exprloc:
18308       result = DW_BLOCK (attr)->data;
18309       *len = DW_BLOCK (attr)->size;
18310       break;
18311
18312       /* The DW_AT_const_value attributes are supposed to carry the
18313          symbol's value "represented as it would be on the target
18314          architecture."  By the time we get here, it's already been
18315          converted to host endianness, so we just need to sign- or
18316          zero-extend it as appropriate.  */
18317     case DW_FORM_data1:
18318       type = die_type (die, cu);
18319       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18320       if (result == NULL)
18321         result = write_constant_as_bytes (obstack, byte_order,
18322                                           type, value, len);
18323       break;
18324     case DW_FORM_data2:
18325       type = die_type (die, cu);
18326       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18327       if (result == NULL)
18328         result = write_constant_as_bytes (obstack, byte_order,
18329                                           type, value, len);
18330       break;
18331     case DW_FORM_data4:
18332       type = die_type (die, cu);
18333       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18334       if (result == NULL)
18335         result = write_constant_as_bytes (obstack, byte_order,
18336                                           type, value, len);
18337       break;
18338     case DW_FORM_data8:
18339       type = die_type (die, cu);
18340       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18341       if (result == NULL)
18342         result = write_constant_as_bytes (obstack, byte_order,
18343                                           type, value, len);
18344       break;
18345
18346     case DW_FORM_sdata:
18347       type = die_type (die, cu);
18348       result = write_constant_as_bytes (obstack, byte_order,
18349                                         type, DW_SND (attr), len);
18350       break;
18351
18352     case DW_FORM_udata:
18353       type = die_type (die, cu);
18354       result = write_constant_as_bytes (obstack, byte_order,
18355                                         type, DW_UNSND (attr), len);
18356       break;
18357
18358     default:
18359       complaint (&symfile_complaints,
18360                  _("unsupported const value attribute form: '%s'"),
18361                  dwarf_form_name (attr->form));
18362       break;
18363     }
18364
18365   return result;
18366 }
18367
18368 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18369    PER_CU.  */
18370
18371 struct type *
18372 dwarf2_get_die_type (cu_offset die_offset,
18373                      struct dwarf2_per_cu_data *per_cu)
18374 {
18375   sect_offset die_offset_sect;
18376
18377   dw2_setup (per_cu->objfile);
18378
18379   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18380   return get_die_type_at_offset (die_offset_sect, per_cu);
18381 }
18382
18383 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18384    On entry *REF_CU is the CU of SRC_DIE.
18385    On exit *REF_CU is the CU of the result.
18386    Returns NULL if the referenced DIE isn't found.  */
18387
18388 static struct die_info *
18389 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18390                   struct dwarf2_cu **ref_cu)
18391 {
18392   struct objfile *objfile = (*ref_cu)->objfile;
18393   struct die_info temp_die;
18394   struct dwarf2_cu *sig_cu;
18395   struct die_info *die;
18396
18397   /* While it might be nice to assert sig_type->type == NULL here,
18398      we can get here for DW_AT_imported_declaration where we need
18399      the DIE not the type.  */
18400
18401   /* If necessary, add it to the queue and load its DIEs.  */
18402
18403   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18404     read_signatured_type (sig_type);
18405
18406   gdb_assert (sig_type->per_cu.cu != NULL);
18407
18408   sig_cu = sig_type->per_cu.cu;
18409   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18410   temp_die.offset = sig_type->type_offset_in_section;
18411   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18412                              temp_die.offset.sect_off);
18413   if (die)
18414     {
18415       /* For .gdb_index version 7 keep track of included TUs.
18416          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18417       if (dwarf2_per_objfile->index_table != NULL
18418           && dwarf2_per_objfile->index_table->version <= 7)
18419         {
18420           VEC_safe_push (dwarf2_per_cu_ptr,
18421                          (*ref_cu)->per_cu->imported_symtabs,
18422                          sig_cu->per_cu);
18423         }
18424
18425       *ref_cu = sig_cu;
18426       return die;
18427     }
18428
18429   return NULL;
18430 }
18431
18432 /* Follow signatured type referenced by ATTR in SRC_DIE.
18433    On entry *REF_CU is the CU of SRC_DIE.
18434    On exit *REF_CU is the CU of the result.
18435    The result is the DIE of the type.
18436    If the referenced type cannot be found an error is thrown.  */
18437
18438 static struct die_info *
18439 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
18440                 struct dwarf2_cu **ref_cu)
18441 {
18442   ULONGEST signature = DW_SIGNATURE (attr);
18443   struct signatured_type *sig_type;
18444   struct die_info *die;
18445
18446   gdb_assert (attr->form == DW_FORM_ref_sig8);
18447
18448   sig_type = lookup_signatured_type (*ref_cu, signature);
18449   /* sig_type will be NULL if the signatured type is missing from
18450      the debug info.  */
18451   if (sig_type == NULL)
18452     {
18453       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18454                " from DIE at 0x%x [in module %s]"),
18455              hex_string (signature), src_die->offset.sect_off,
18456              (*ref_cu)->objfile->name);
18457     }
18458
18459   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18460   if (die == NULL)
18461     {
18462       dump_die_for_error (src_die);
18463       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18464                " from DIE at 0x%x [in module %s]"),
18465              hex_string (signature), src_die->offset.sect_off,
18466              (*ref_cu)->objfile->name);
18467     }
18468
18469   return die;
18470 }
18471
18472 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18473    reading in and processing the type unit if necessary.  */
18474
18475 static struct type *
18476 get_signatured_type (struct die_info *die, ULONGEST signature,
18477                      struct dwarf2_cu *cu)
18478 {
18479   struct signatured_type *sig_type;
18480   struct dwarf2_cu *type_cu;
18481   struct die_info *type_die;
18482   struct type *type;
18483
18484   sig_type = lookup_signatured_type (cu, signature);
18485   /* sig_type will be NULL if the signatured type is missing from
18486      the debug info.  */
18487   if (sig_type == NULL)
18488     {
18489       complaint (&symfile_complaints,
18490                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18491                    " from DIE at 0x%x [in module %s]"),
18492                  hex_string (signature), die->offset.sect_off,
18493                  dwarf2_per_objfile->objfile->name);
18494       return build_error_marker_type (cu, die);
18495     }
18496
18497   /* If we already know the type we're done.  */
18498   if (sig_type->type != NULL)
18499     return sig_type->type;
18500
18501   type_cu = cu;
18502   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18503   if (type_die != NULL)
18504     {
18505       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18506          is created.  This is important, for example, because for c++ classes
18507          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18508       type = read_type_die (type_die, type_cu);
18509       if (type == NULL)
18510         {
18511           complaint (&symfile_complaints,
18512                      _("Dwarf Error: Cannot build signatured type %s"
18513                        " referenced from DIE at 0x%x [in module %s]"),
18514                      hex_string (signature), die->offset.sect_off,
18515                      dwarf2_per_objfile->objfile->name);
18516           type = build_error_marker_type (cu, die);
18517         }
18518     }
18519   else
18520     {
18521       complaint (&symfile_complaints,
18522                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18523                    " from DIE at 0x%x [in module %s]"),
18524                  hex_string (signature), die->offset.sect_off,
18525                  dwarf2_per_objfile->objfile->name);
18526       type = build_error_marker_type (cu, die);
18527     }
18528   sig_type->type = type;
18529
18530   return type;
18531 }
18532
18533 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18534    reading in and processing the type unit if necessary.  */
18535
18536 static struct type *
18537 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
18538                           struct dwarf2_cu *cu) /* ARI: editCase function */
18539 {
18540   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18541   if (attr_form_is_ref (attr))
18542     {
18543       struct dwarf2_cu *type_cu = cu;
18544       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18545
18546       return read_type_die (type_die, type_cu);
18547     }
18548   else if (attr->form == DW_FORM_ref_sig8)
18549     {
18550       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18551     }
18552   else
18553     {
18554       complaint (&symfile_complaints,
18555                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18556                    " at 0x%x [in module %s]"),
18557                  dwarf_form_name (attr->form), die->offset.sect_off,
18558                  dwarf2_per_objfile->objfile->name);
18559       return build_error_marker_type (cu, die);
18560     }
18561 }
18562
18563 /* Load the DIEs associated with type unit PER_CU into memory.  */
18564
18565 static void
18566 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18567 {
18568   struct signatured_type *sig_type;
18569
18570   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18571   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18572
18573   /* We have the per_cu, but we need the signatured_type.
18574      Fortunately this is an easy translation.  */
18575   gdb_assert (per_cu->is_debug_types);
18576   sig_type = (struct signatured_type *) per_cu;
18577
18578   gdb_assert (per_cu->cu == NULL);
18579
18580   read_signatured_type (sig_type);
18581
18582   gdb_assert (per_cu->cu != NULL);
18583 }
18584
18585 /* die_reader_func for read_signatured_type.
18586    This is identical to load_full_comp_unit_reader,
18587    but is kept separate for now.  */
18588
18589 static void
18590 read_signatured_type_reader (const struct die_reader_specs *reader,
18591                              const gdb_byte *info_ptr,
18592                              struct die_info *comp_unit_die,
18593                              int has_children,
18594                              void *data)
18595 {
18596   struct dwarf2_cu *cu = reader->cu;
18597
18598   gdb_assert (cu->die_hash == NULL);
18599   cu->die_hash =
18600     htab_create_alloc_ex (cu->header.length / 12,
18601                           die_hash,
18602                           die_eq,
18603                           NULL,
18604                           &cu->comp_unit_obstack,
18605                           hashtab_obstack_allocate,
18606                           dummy_obstack_deallocate);
18607
18608   if (has_children)
18609     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18610                                                   &info_ptr, comp_unit_die);
18611   cu->dies = comp_unit_die;
18612   /* comp_unit_die is not stored in die_hash, no need.  */
18613
18614   /* We try not to read any attributes in this function, because not
18615      all CUs needed for references have been loaded yet, and symbol
18616      table processing isn't initialized.  But we have to set the CU language,
18617      or we won't be able to build types correctly.
18618      Similarly, if we do not read the producer, we can not apply
18619      producer-specific interpretation.  */
18620   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18621 }
18622
18623 /* Read in a signatured type and build its CU and DIEs.
18624    If the type is a stub for the real type in a DWO file,
18625    read in the real type from the DWO file as well.  */
18626
18627 static void
18628 read_signatured_type (struct signatured_type *sig_type)
18629 {
18630   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18631
18632   gdb_assert (per_cu->is_debug_types);
18633   gdb_assert (per_cu->cu == NULL);
18634
18635   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18636                            read_signatured_type_reader, NULL);
18637   sig_type->per_cu.tu_read = 1;
18638 }
18639
18640 /* Decode simple location descriptions.
18641    Given a pointer to a dwarf block that defines a location, compute
18642    the location and return the value.
18643
18644    NOTE drow/2003-11-18: This function is called in two situations
18645    now: for the address of static or global variables (partial symbols
18646    only) and for offsets into structures which are expected to be
18647    (more or less) constant.  The partial symbol case should go away,
18648    and only the constant case should remain.  That will let this
18649    function complain more accurately.  A few special modes are allowed
18650    without complaint for global variables (for instance, global
18651    register values and thread-local values).
18652
18653    A location description containing no operations indicates that the
18654    object is optimized out.  The return value is 0 for that case.
18655    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18656    callers will only want a very basic result and this can become a
18657    complaint.
18658
18659    Note that stack[0] is unused except as a default error return.  */
18660
18661 static CORE_ADDR
18662 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18663 {
18664   struct objfile *objfile = cu->objfile;
18665   size_t i;
18666   size_t size = blk->size;
18667   const gdb_byte *data = blk->data;
18668   CORE_ADDR stack[64];
18669   int stacki;
18670   unsigned int bytes_read, unsnd;
18671   gdb_byte op;
18672
18673   i = 0;
18674   stacki = 0;
18675   stack[stacki] = 0;
18676   stack[++stacki] = 0;
18677
18678   while (i < size)
18679     {
18680       op = data[i++];
18681       switch (op)
18682         {
18683         case DW_OP_lit0:
18684         case DW_OP_lit1:
18685         case DW_OP_lit2:
18686         case DW_OP_lit3:
18687         case DW_OP_lit4:
18688         case DW_OP_lit5:
18689         case DW_OP_lit6:
18690         case DW_OP_lit7:
18691         case DW_OP_lit8:
18692         case DW_OP_lit9:
18693         case DW_OP_lit10:
18694         case DW_OP_lit11:
18695         case DW_OP_lit12:
18696         case DW_OP_lit13:
18697         case DW_OP_lit14:
18698         case DW_OP_lit15:
18699         case DW_OP_lit16:
18700         case DW_OP_lit17:
18701         case DW_OP_lit18:
18702         case DW_OP_lit19:
18703         case DW_OP_lit20:
18704         case DW_OP_lit21:
18705         case DW_OP_lit22:
18706         case DW_OP_lit23:
18707         case DW_OP_lit24:
18708         case DW_OP_lit25:
18709         case DW_OP_lit26:
18710         case DW_OP_lit27:
18711         case DW_OP_lit28:
18712         case DW_OP_lit29:
18713         case DW_OP_lit30:
18714         case DW_OP_lit31:
18715           stack[++stacki] = op - DW_OP_lit0;
18716           break;
18717
18718         case DW_OP_reg0:
18719         case DW_OP_reg1:
18720         case DW_OP_reg2:
18721         case DW_OP_reg3:
18722         case DW_OP_reg4:
18723         case DW_OP_reg5:
18724         case DW_OP_reg6:
18725         case DW_OP_reg7:
18726         case DW_OP_reg8:
18727         case DW_OP_reg9:
18728         case DW_OP_reg10:
18729         case DW_OP_reg11:
18730         case DW_OP_reg12:
18731         case DW_OP_reg13:
18732         case DW_OP_reg14:
18733         case DW_OP_reg15:
18734         case DW_OP_reg16:
18735         case DW_OP_reg17:
18736         case DW_OP_reg18:
18737         case DW_OP_reg19:
18738         case DW_OP_reg20:
18739         case DW_OP_reg21:
18740         case DW_OP_reg22:
18741         case DW_OP_reg23:
18742         case DW_OP_reg24:
18743         case DW_OP_reg25:
18744         case DW_OP_reg26:
18745         case DW_OP_reg27:
18746         case DW_OP_reg28:
18747         case DW_OP_reg29:
18748         case DW_OP_reg30:
18749         case DW_OP_reg31:
18750           stack[++stacki] = op - DW_OP_reg0;
18751           if (i < size)
18752             dwarf2_complex_location_expr_complaint ();
18753           break;
18754
18755         case DW_OP_regx:
18756           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18757           i += bytes_read;
18758           stack[++stacki] = unsnd;
18759           if (i < size)
18760             dwarf2_complex_location_expr_complaint ();
18761           break;
18762
18763         case DW_OP_addr:
18764           stack[++stacki] = read_address (objfile->obfd, &data[i],
18765                                           cu, &bytes_read);
18766           i += bytes_read;
18767           break;
18768
18769         case DW_OP_const1u:
18770           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18771           i += 1;
18772           break;
18773
18774         case DW_OP_const1s:
18775           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18776           i += 1;
18777           break;
18778
18779         case DW_OP_const2u:
18780           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18781           i += 2;
18782           break;
18783
18784         case DW_OP_const2s:
18785           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18786           i += 2;
18787           break;
18788
18789         case DW_OP_const4u:
18790           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18791           i += 4;
18792           break;
18793
18794         case DW_OP_const4s:
18795           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18796           i += 4;
18797           break;
18798
18799         case DW_OP_const8u:
18800           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18801           i += 8;
18802           break;
18803
18804         case DW_OP_constu:
18805           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18806                                                   &bytes_read);
18807           i += bytes_read;
18808           break;
18809
18810         case DW_OP_consts:
18811           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18812           i += bytes_read;
18813           break;
18814
18815         case DW_OP_dup:
18816           stack[stacki + 1] = stack[stacki];
18817           stacki++;
18818           break;
18819
18820         case DW_OP_plus:
18821           stack[stacki - 1] += stack[stacki];
18822           stacki--;
18823           break;
18824
18825         case DW_OP_plus_uconst:
18826           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18827                                                  &bytes_read);
18828           i += bytes_read;
18829           break;
18830
18831         case DW_OP_minus:
18832           stack[stacki - 1] -= stack[stacki];
18833           stacki--;
18834           break;
18835
18836         case DW_OP_deref:
18837           /* If we're not the last op, then we definitely can't encode
18838              this using GDB's address_class enum.  This is valid for partial
18839              global symbols, although the variable's address will be bogus
18840              in the psymtab.  */
18841           if (i < size)
18842             dwarf2_complex_location_expr_complaint ();
18843           break;
18844
18845         case DW_OP_GNU_push_tls_address:
18846           /* The top of the stack has the offset from the beginning
18847              of the thread control block at which the variable is located.  */
18848           /* Nothing should follow this operator, so the top of stack would
18849              be returned.  */
18850           /* This is valid for partial global symbols, but the variable's
18851              address will be bogus in the psymtab.  Make it always at least
18852              non-zero to not look as a variable garbage collected by linker
18853              which have DW_OP_addr 0.  */
18854           if (i < size)
18855             dwarf2_complex_location_expr_complaint ();
18856           stack[stacki]++;
18857           break;
18858
18859         case DW_OP_GNU_uninit:
18860           break;
18861
18862         case DW_OP_GNU_addr_index:
18863         case DW_OP_GNU_const_index:
18864           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18865                                                          &bytes_read);
18866           i += bytes_read;
18867           break;
18868
18869         default:
18870           {
18871             const char *name = get_DW_OP_name (op);
18872
18873             if (name)
18874               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18875                          name);
18876             else
18877               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18878                          op);
18879           }
18880
18881           return (stack[stacki]);
18882         }
18883
18884       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18885          outside of the allocated space.  Also enforce minimum>0.  */
18886       if (stacki >= ARRAY_SIZE (stack) - 1)
18887         {
18888           complaint (&symfile_complaints,
18889                      _("location description stack overflow"));
18890           return 0;
18891         }
18892
18893       if (stacki <= 0)
18894         {
18895           complaint (&symfile_complaints,
18896                      _("location description stack underflow"));
18897           return 0;
18898         }
18899     }
18900   return (stack[stacki]);
18901 }
18902
18903 /* memory allocation interface */
18904
18905 static struct dwarf_block *
18906 dwarf_alloc_block (struct dwarf2_cu *cu)
18907 {
18908   struct dwarf_block *blk;
18909
18910   blk = (struct dwarf_block *)
18911     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18912   return (blk);
18913 }
18914
18915 static struct die_info *
18916 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18917 {
18918   struct die_info *die;
18919   size_t size = sizeof (struct die_info);
18920
18921   if (num_attrs > 1)
18922     size += (num_attrs - 1) * sizeof (struct attribute);
18923
18924   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18925   memset (die, 0, sizeof (struct die_info));
18926   return (die);
18927 }
18928
18929 \f
18930 /* Macro support.  */
18931
18932 /* Return file name relative to the compilation directory of file number I in
18933    *LH's file name table.  The result is allocated using xmalloc; the caller is
18934    responsible for freeing it.  */
18935
18936 static char *
18937 file_file_name (int file, struct line_header *lh)
18938 {
18939   /* Is the file number a valid index into the line header's file name
18940      table?  Remember that file numbers start with one, not zero.  */
18941   if (1 <= file && file <= lh->num_file_names)
18942     {
18943       struct file_entry *fe = &lh->file_names[file - 1];
18944
18945       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18946         return xstrdup (fe->name);
18947       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18948                      fe->name, NULL);
18949     }
18950   else
18951     {
18952       /* The compiler produced a bogus file number.  We can at least
18953          record the macro definitions made in the file, even if we
18954          won't be able to find the file by name.  */
18955       char fake_name[80];
18956
18957       xsnprintf (fake_name, sizeof (fake_name),
18958                  "<bad macro file number %d>", file);
18959
18960       complaint (&symfile_complaints,
18961                  _("bad file number in macro information (%d)"),
18962                  file);
18963
18964       return xstrdup (fake_name);
18965     }
18966 }
18967
18968 /* Return the full name of file number I in *LH's file name table.
18969    Use COMP_DIR as the name of the current directory of the
18970    compilation.  The result is allocated using xmalloc; the caller is
18971    responsible for freeing it.  */
18972 static char *
18973 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18974 {
18975   /* Is the file number a valid index into the line header's file name
18976      table?  Remember that file numbers start with one, not zero.  */
18977   if (1 <= file && file <= lh->num_file_names)
18978     {
18979       char *relative = file_file_name (file, lh);
18980
18981       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18982         return relative;
18983       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18984     }
18985   else
18986     return file_file_name (file, lh);
18987 }
18988
18989
18990 static struct macro_source_file *
18991 macro_start_file (int file, int line,
18992                   struct macro_source_file *current_file,
18993                   const char *comp_dir,
18994                   struct line_header *lh, struct objfile *objfile)
18995 {
18996   /* File name relative to the compilation directory of this source file.  */
18997   char *file_name = file_file_name (file, lh);
18998
18999   /* We don't create a macro table for this compilation unit
19000      at all until we actually get a filename.  */
19001   if (! pending_macros)
19002     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
19003                                       objfile->per_bfd->macro_cache,
19004                                       comp_dir);
19005
19006   if (! current_file)
19007     {
19008       /* If we have no current file, then this must be the start_file
19009          directive for the compilation unit's main source file.  */
19010       current_file = macro_set_main (pending_macros, file_name);
19011       macro_define_special (pending_macros);
19012     }
19013   else
19014     current_file = macro_include (current_file, line, file_name);
19015
19016   xfree (file_name);
19017
19018   return current_file;
19019 }
19020
19021
19022 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19023    followed by a null byte.  */
19024 static char *
19025 copy_string (const char *buf, int len)
19026 {
19027   char *s = xmalloc (len + 1);
19028
19029   memcpy (s, buf, len);
19030   s[len] = '\0';
19031   return s;
19032 }
19033
19034
19035 static const char *
19036 consume_improper_spaces (const char *p, const char *body)
19037 {
19038   if (*p == ' ')
19039     {
19040       complaint (&symfile_complaints,
19041                  _("macro definition contains spaces "
19042                    "in formal argument list:\n`%s'"),
19043                  body);
19044
19045       while (*p == ' ')
19046         p++;
19047     }
19048
19049   return p;
19050 }
19051
19052
19053 static void
19054 parse_macro_definition (struct macro_source_file *file, int line,
19055                         const char *body)
19056 {
19057   const char *p;
19058
19059   /* The body string takes one of two forms.  For object-like macro
19060      definitions, it should be:
19061
19062         <macro name> " " <definition>
19063
19064      For function-like macro definitions, it should be:
19065
19066         <macro name> "() " <definition>
19067      or
19068         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19069
19070      Spaces may appear only where explicitly indicated, and in the
19071      <definition>.
19072
19073      The Dwarf 2 spec says that an object-like macro's name is always
19074      followed by a space, but versions of GCC around March 2002 omit
19075      the space when the macro's definition is the empty string.
19076
19077      The Dwarf 2 spec says that there should be no spaces between the
19078      formal arguments in a function-like macro's formal argument list,
19079      but versions of GCC around March 2002 include spaces after the
19080      commas.  */
19081
19082
19083   /* Find the extent of the macro name.  The macro name is terminated
19084      by either a space or null character (for an object-like macro) or
19085      an opening paren (for a function-like macro).  */
19086   for (p = body; *p; p++)
19087     if (*p == ' ' || *p == '(')
19088       break;
19089
19090   if (*p == ' ' || *p == '\0')
19091     {
19092       /* It's an object-like macro.  */
19093       int name_len = p - body;
19094       char *name = copy_string (body, name_len);
19095       const char *replacement;
19096
19097       if (*p == ' ')
19098         replacement = body + name_len + 1;
19099       else
19100         {
19101           dwarf2_macro_malformed_definition_complaint (body);
19102           replacement = body + name_len;
19103         }
19104
19105       macro_define_object (file, line, name, replacement);
19106
19107       xfree (name);
19108     }
19109   else if (*p == '(')
19110     {
19111       /* It's a function-like macro.  */
19112       char *name = copy_string (body, p - body);
19113       int argc = 0;
19114       int argv_size = 1;
19115       char **argv = xmalloc (argv_size * sizeof (*argv));
19116
19117       p++;
19118
19119       p = consume_improper_spaces (p, body);
19120
19121       /* Parse the formal argument list.  */
19122       while (*p && *p != ')')
19123         {
19124           /* Find the extent of the current argument name.  */
19125           const char *arg_start = p;
19126
19127           while (*p && *p != ',' && *p != ')' && *p != ' ')
19128             p++;
19129
19130           if (! *p || p == arg_start)
19131             dwarf2_macro_malformed_definition_complaint (body);
19132           else
19133             {
19134               /* Make sure argv has room for the new argument.  */
19135               if (argc >= argv_size)
19136                 {
19137                   argv_size *= 2;
19138                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19139                 }
19140
19141               argv[argc++] = copy_string (arg_start, p - arg_start);
19142             }
19143
19144           p = consume_improper_spaces (p, body);
19145
19146           /* Consume the comma, if present.  */
19147           if (*p == ',')
19148             {
19149               p++;
19150
19151               p = consume_improper_spaces (p, body);
19152             }
19153         }
19154
19155       if (*p == ')')
19156         {
19157           p++;
19158
19159           if (*p == ' ')
19160             /* Perfectly formed definition, no complaints.  */
19161             macro_define_function (file, line, name,
19162                                    argc, (const char **) argv,
19163                                    p + 1);
19164           else if (*p == '\0')
19165             {
19166               /* Complain, but do define it.  */
19167               dwarf2_macro_malformed_definition_complaint (body);
19168               macro_define_function (file, line, name,
19169                                      argc, (const char **) argv,
19170                                      p);
19171             }
19172           else
19173             /* Just complain.  */
19174             dwarf2_macro_malformed_definition_complaint (body);
19175         }
19176       else
19177         /* Just complain.  */
19178         dwarf2_macro_malformed_definition_complaint (body);
19179
19180       xfree (name);
19181       {
19182         int i;
19183
19184         for (i = 0; i < argc; i++)
19185           xfree (argv[i]);
19186       }
19187       xfree (argv);
19188     }
19189   else
19190     dwarf2_macro_malformed_definition_complaint (body);
19191 }
19192
19193 /* Skip some bytes from BYTES according to the form given in FORM.
19194    Returns the new pointer.  */
19195
19196 static const gdb_byte *
19197 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19198                  enum dwarf_form form,
19199                  unsigned int offset_size,
19200                  struct dwarf2_section_info *section)
19201 {
19202   unsigned int bytes_read;
19203
19204   switch (form)
19205     {
19206     case DW_FORM_data1:
19207     case DW_FORM_flag:
19208       ++bytes;
19209       break;
19210
19211     case DW_FORM_data2:
19212       bytes += 2;
19213       break;
19214
19215     case DW_FORM_data4:
19216       bytes += 4;
19217       break;
19218
19219     case DW_FORM_data8:
19220       bytes += 8;
19221       break;
19222
19223     case DW_FORM_string:
19224       read_direct_string (abfd, bytes, &bytes_read);
19225       bytes += bytes_read;
19226       break;
19227
19228     case DW_FORM_sec_offset:
19229     case DW_FORM_strp:
19230     case DW_FORM_GNU_strp_alt:
19231       bytes += offset_size;
19232       break;
19233
19234     case DW_FORM_block:
19235       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19236       bytes += bytes_read;
19237       break;
19238
19239     case DW_FORM_block1:
19240       bytes += 1 + read_1_byte (abfd, bytes);
19241       break;
19242     case DW_FORM_block2:
19243       bytes += 2 + read_2_bytes (abfd, bytes);
19244       break;
19245     case DW_FORM_block4:
19246       bytes += 4 + read_4_bytes (abfd, bytes);
19247       break;
19248
19249     case DW_FORM_sdata:
19250     case DW_FORM_udata:
19251     case DW_FORM_GNU_addr_index:
19252     case DW_FORM_GNU_str_index:
19253       bytes = gdb_skip_leb128 (bytes, buffer_end);
19254       if (bytes == NULL)
19255         {
19256           dwarf2_section_buffer_overflow_complaint (section);
19257           return NULL;
19258         }
19259       break;
19260
19261     default:
19262       {
19263       complain:
19264         complaint (&symfile_complaints,
19265                    _("invalid form 0x%x in `%s'"),
19266                    form,
19267                    section->asection->name);
19268         return NULL;
19269       }
19270     }
19271
19272   return bytes;
19273 }
19274
19275 /* A helper for dwarf_decode_macros that handles skipping an unknown
19276    opcode.  Returns an updated pointer to the macro data buffer; or,
19277    on error, issues a complaint and returns NULL.  */
19278
19279 static const gdb_byte *
19280 skip_unknown_opcode (unsigned int opcode,
19281                      const gdb_byte **opcode_definitions,
19282                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19283                      bfd *abfd,
19284                      unsigned int offset_size,
19285                      struct dwarf2_section_info *section)
19286 {
19287   unsigned int bytes_read, i;
19288   unsigned long arg;
19289   const gdb_byte *defn;
19290
19291   if (opcode_definitions[opcode] == NULL)
19292     {
19293       complaint (&symfile_complaints,
19294                  _("unrecognized DW_MACFINO opcode 0x%x"),
19295                  opcode);
19296       return NULL;
19297     }
19298
19299   defn = opcode_definitions[opcode];
19300   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19301   defn += bytes_read;
19302
19303   for (i = 0; i < arg; ++i)
19304     {
19305       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19306                                  section);
19307       if (mac_ptr == NULL)
19308         {
19309           /* skip_form_bytes already issued the complaint.  */
19310           return NULL;
19311         }
19312     }
19313
19314   return mac_ptr;
19315 }
19316
19317 /* A helper function which parses the header of a macro section.
19318    If the macro section is the extended (for now called "GNU") type,
19319    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19320    the header, or issues a complaint and returns NULL on error.  */
19321
19322 static const gdb_byte *
19323 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19324                           bfd *abfd,
19325                           const gdb_byte *mac_ptr,
19326                           unsigned int *offset_size,
19327                           int section_is_gnu)
19328 {
19329   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19330
19331   if (section_is_gnu)
19332     {
19333       unsigned int version, flags;
19334
19335       version = read_2_bytes (abfd, mac_ptr);
19336       if (version != 4)
19337         {
19338           complaint (&symfile_complaints,
19339                      _("unrecognized version `%d' in .debug_macro section"),
19340                      version);
19341           return NULL;
19342         }
19343       mac_ptr += 2;
19344
19345       flags = read_1_byte (abfd, mac_ptr);
19346       ++mac_ptr;
19347       *offset_size = (flags & 1) ? 8 : 4;
19348
19349       if ((flags & 2) != 0)
19350         /* We don't need the line table offset.  */
19351         mac_ptr += *offset_size;
19352
19353       /* Vendor opcode descriptions.  */
19354       if ((flags & 4) != 0)
19355         {
19356           unsigned int i, count;
19357
19358           count = read_1_byte (abfd, mac_ptr);
19359           ++mac_ptr;
19360           for (i = 0; i < count; ++i)
19361             {
19362               unsigned int opcode, bytes_read;
19363               unsigned long arg;
19364
19365               opcode = read_1_byte (abfd, mac_ptr);
19366               ++mac_ptr;
19367               opcode_definitions[opcode] = mac_ptr;
19368               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19369               mac_ptr += bytes_read;
19370               mac_ptr += arg;
19371             }
19372         }
19373     }
19374
19375   return mac_ptr;
19376 }
19377
19378 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19379    including DW_MACRO_GNU_transparent_include.  */
19380
19381 static void
19382 dwarf_decode_macro_bytes (bfd *abfd,
19383                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19384                           struct macro_source_file *current_file,
19385                           struct line_header *lh, const char *comp_dir,
19386                           struct dwarf2_section_info *section,
19387                           int section_is_gnu, int section_is_dwz,
19388                           unsigned int offset_size,
19389                           struct objfile *objfile,
19390                           htab_t include_hash)
19391 {
19392   enum dwarf_macro_record_type macinfo_type;
19393   int at_commandline;
19394   const gdb_byte *opcode_definitions[256];
19395
19396   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19397                                       &offset_size, section_is_gnu);
19398   if (mac_ptr == NULL)
19399     {
19400       /* We already issued a complaint.  */
19401       return;
19402     }
19403
19404   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19405      GDB is still reading the definitions from command line.  First
19406      DW_MACINFO_start_file will need to be ignored as it was already executed
19407      to create CURRENT_FILE for the main source holding also the command line
19408      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19409      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19410
19411   at_commandline = 1;
19412
19413   do
19414     {
19415       /* Do we at least have room for a macinfo type byte?  */
19416       if (mac_ptr >= mac_end)
19417         {
19418           dwarf2_section_buffer_overflow_complaint (section);
19419           break;
19420         }
19421
19422       macinfo_type = read_1_byte (abfd, mac_ptr);
19423       mac_ptr++;
19424
19425       /* Note that we rely on the fact that the corresponding GNU and
19426          DWARF constants are the same.  */
19427       switch (macinfo_type)
19428         {
19429           /* A zero macinfo type indicates the end of the macro
19430              information.  */
19431         case 0:
19432           break;
19433
19434         case DW_MACRO_GNU_define:
19435         case DW_MACRO_GNU_undef:
19436         case DW_MACRO_GNU_define_indirect:
19437         case DW_MACRO_GNU_undef_indirect:
19438         case DW_MACRO_GNU_define_indirect_alt:
19439         case DW_MACRO_GNU_undef_indirect_alt:
19440           {
19441             unsigned int bytes_read;
19442             int line;
19443             const char *body;
19444             int is_define;
19445
19446             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19447             mac_ptr += bytes_read;
19448
19449             if (macinfo_type == DW_MACRO_GNU_define
19450                 || macinfo_type == DW_MACRO_GNU_undef)
19451               {
19452                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19453                 mac_ptr += bytes_read;
19454               }
19455             else
19456               {
19457                 LONGEST str_offset;
19458
19459                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19460                 mac_ptr += offset_size;
19461
19462                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19463                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19464                     || section_is_dwz)
19465                   {
19466                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19467
19468                     body = read_indirect_string_from_dwz (dwz, str_offset);
19469                   }
19470                 else
19471                   body = read_indirect_string_at_offset (abfd, str_offset);
19472               }
19473
19474             is_define = (macinfo_type == DW_MACRO_GNU_define
19475                          || macinfo_type == DW_MACRO_GNU_define_indirect
19476                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19477             if (! current_file)
19478               {
19479                 /* DWARF violation as no main source is present.  */
19480                 complaint (&symfile_complaints,
19481                            _("debug info with no main source gives macro %s "
19482                              "on line %d: %s"),
19483                            is_define ? _("definition") : _("undefinition"),
19484                            line, body);
19485                 break;
19486               }
19487             if ((line == 0 && !at_commandline)
19488                 || (line != 0 && at_commandline))
19489               complaint (&symfile_complaints,
19490                          _("debug info gives %s macro %s with %s line %d: %s"),
19491                          at_commandline ? _("command-line") : _("in-file"),
19492                          is_define ? _("definition") : _("undefinition"),
19493                          line == 0 ? _("zero") : _("non-zero"), line, body);
19494
19495             if (is_define)
19496               parse_macro_definition (current_file, line, body);
19497             else
19498               {
19499                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19500                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19501                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19502                 macro_undef (current_file, line, body);
19503               }
19504           }
19505           break;
19506
19507         case DW_MACRO_GNU_start_file:
19508           {
19509             unsigned int bytes_read;
19510             int line, file;
19511
19512             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19513             mac_ptr += bytes_read;
19514             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19515             mac_ptr += bytes_read;
19516
19517             if ((line == 0 && !at_commandline)
19518                 || (line != 0 && at_commandline))
19519               complaint (&symfile_complaints,
19520                          _("debug info gives source %d included "
19521                            "from %s at %s line %d"),
19522                          file, at_commandline ? _("command-line") : _("file"),
19523                          line == 0 ? _("zero") : _("non-zero"), line);
19524
19525             if (at_commandline)
19526               {
19527                 /* This DW_MACRO_GNU_start_file was executed in the
19528                    pass one.  */
19529                 at_commandline = 0;
19530               }
19531             else
19532               current_file = macro_start_file (file, line,
19533                                                current_file, comp_dir,
19534                                                lh, objfile);
19535           }
19536           break;
19537
19538         case DW_MACRO_GNU_end_file:
19539           if (! current_file)
19540             complaint (&symfile_complaints,
19541                        _("macro debug info has an unmatched "
19542                          "`close_file' directive"));
19543           else
19544             {
19545               current_file = current_file->included_by;
19546               if (! current_file)
19547                 {
19548                   enum dwarf_macro_record_type next_type;
19549
19550                   /* GCC circa March 2002 doesn't produce the zero
19551                      type byte marking the end of the compilation
19552                      unit.  Complain if it's not there, but exit no
19553                      matter what.  */
19554
19555                   /* Do we at least have room for a macinfo type byte?  */
19556                   if (mac_ptr >= mac_end)
19557                     {
19558                       dwarf2_section_buffer_overflow_complaint (section);
19559                       return;
19560                     }
19561
19562                   /* We don't increment mac_ptr here, so this is just
19563                      a look-ahead.  */
19564                   next_type = read_1_byte (abfd, mac_ptr);
19565                   if (next_type != 0)
19566                     complaint (&symfile_complaints,
19567                                _("no terminating 0-type entry for "
19568                                  "macros in `.debug_macinfo' section"));
19569
19570                   return;
19571                 }
19572             }
19573           break;
19574
19575         case DW_MACRO_GNU_transparent_include:
19576         case DW_MACRO_GNU_transparent_include_alt:
19577           {
19578             LONGEST offset;
19579             void **slot;
19580             bfd *include_bfd = abfd;
19581             struct dwarf2_section_info *include_section = section;
19582             struct dwarf2_section_info alt_section;
19583             const gdb_byte *include_mac_end = mac_end;
19584             int is_dwz = section_is_dwz;
19585             const gdb_byte *new_mac_ptr;
19586
19587             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19588             mac_ptr += offset_size;
19589
19590             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19591               {
19592                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19593
19594                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19595                                      &dwz->macro);
19596
19597                 include_bfd = dwz->macro.asection->owner;
19598                 include_section = &dwz->macro;
19599                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19600                 is_dwz = 1;
19601               }
19602
19603             new_mac_ptr = include_section->buffer + offset;
19604             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19605
19606             if (*slot != NULL)
19607               {
19608                 /* This has actually happened; see
19609                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19610                 complaint (&symfile_complaints,
19611                            _("recursive DW_MACRO_GNU_transparent_include in "
19612                              ".debug_macro section"));
19613               }
19614             else
19615               {
19616                 *slot = (void *) new_mac_ptr;
19617
19618                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19619                                           include_mac_end, current_file,
19620                                           lh, comp_dir,
19621                                           section, section_is_gnu, is_dwz,
19622                                           offset_size, objfile, include_hash);
19623
19624                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19625               }
19626           }
19627           break;
19628
19629         case DW_MACINFO_vendor_ext:
19630           if (!section_is_gnu)
19631             {
19632               unsigned int bytes_read;
19633               int constant;
19634
19635               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19636               mac_ptr += bytes_read;
19637               read_direct_string (abfd, mac_ptr, &bytes_read);
19638               mac_ptr += bytes_read;
19639
19640               /* We don't recognize any vendor extensions.  */
19641               break;
19642             }
19643           /* FALLTHROUGH */
19644
19645         default:
19646           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19647                                          mac_ptr, mac_end, abfd, offset_size,
19648                                          section);
19649           if (mac_ptr == NULL)
19650             return;
19651           break;
19652         }
19653     } while (macinfo_type != 0);
19654 }
19655
19656 static void
19657 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19658                      const char *comp_dir, int section_is_gnu)
19659 {
19660   struct objfile *objfile = dwarf2_per_objfile->objfile;
19661   struct line_header *lh = cu->line_header;
19662   bfd *abfd;
19663   const gdb_byte *mac_ptr, *mac_end;
19664   struct macro_source_file *current_file = 0;
19665   enum dwarf_macro_record_type macinfo_type;
19666   unsigned int offset_size = cu->header.offset_size;
19667   const gdb_byte *opcode_definitions[256];
19668   struct cleanup *cleanup;
19669   htab_t include_hash;
19670   void **slot;
19671   struct dwarf2_section_info *section;
19672   const char *section_name;
19673
19674   if (cu->dwo_unit != NULL)
19675     {
19676       if (section_is_gnu)
19677         {
19678           section = &cu->dwo_unit->dwo_file->sections.macro;
19679           section_name = ".debug_macro.dwo";
19680         }
19681       else
19682         {
19683           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19684           section_name = ".debug_macinfo.dwo";
19685         }
19686     }
19687   else
19688     {
19689       if (section_is_gnu)
19690         {
19691           section = &dwarf2_per_objfile->macro;
19692           section_name = ".debug_macro";
19693         }
19694       else
19695         {
19696           section = &dwarf2_per_objfile->macinfo;
19697           section_name = ".debug_macinfo";
19698         }
19699     }
19700
19701   dwarf2_read_section (objfile, section);
19702   if (section->buffer == NULL)
19703     {
19704       complaint (&symfile_complaints, _("missing %s section"), section_name);
19705       return;
19706     }
19707   abfd = section->asection->owner;
19708
19709   /* First pass: Find the name of the base filename.
19710      This filename is needed in order to process all macros whose definition
19711      (or undefinition) comes from the command line.  These macros are defined
19712      before the first DW_MACINFO_start_file entry, and yet still need to be
19713      associated to the base file.
19714
19715      To determine the base file name, we scan the macro definitions until we
19716      reach the first DW_MACINFO_start_file entry.  We then initialize
19717      CURRENT_FILE accordingly so that any macro definition found before the
19718      first DW_MACINFO_start_file can still be associated to the base file.  */
19719
19720   mac_ptr = section->buffer + offset;
19721   mac_end = section->buffer + section->size;
19722
19723   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19724                                       &offset_size, section_is_gnu);
19725   if (mac_ptr == NULL)
19726     {
19727       /* We already issued a complaint.  */
19728       return;
19729     }
19730
19731   do
19732     {
19733       /* Do we at least have room for a macinfo type byte?  */
19734       if (mac_ptr >= mac_end)
19735         {
19736           /* Complaint is printed during the second pass as GDB will probably
19737              stop the first pass earlier upon finding
19738              DW_MACINFO_start_file.  */
19739           break;
19740         }
19741
19742       macinfo_type = read_1_byte (abfd, mac_ptr);
19743       mac_ptr++;
19744
19745       /* Note that we rely on the fact that the corresponding GNU and
19746          DWARF constants are the same.  */
19747       switch (macinfo_type)
19748         {
19749           /* A zero macinfo type indicates the end of the macro
19750              information.  */
19751         case 0:
19752           break;
19753
19754         case DW_MACRO_GNU_define:
19755         case DW_MACRO_GNU_undef:
19756           /* Only skip the data by MAC_PTR.  */
19757           {
19758             unsigned int bytes_read;
19759
19760             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19761             mac_ptr += bytes_read;
19762             read_direct_string (abfd, mac_ptr, &bytes_read);
19763             mac_ptr += bytes_read;
19764           }
19765           break;
19766
19767         case DW_MACRO_GNU_start_file:
19768           {
19769             unsigned int bytes_read;
19770             int line, file;
19771
19772             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19773             mac_ptr += bytes_read;
19774             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19775             mac_ptr += bytes_read;
19776
19777             current_file = macro_start_file (file, line, current_file,
19778                                              comp_dir, lh, objfile);
19779           }
19780           break;
19781
19782         case DW_MACRO_GNU_end_file:
19783           /* No data to skip by MAC_PTR.  */
19784           break;
19785
19786         case DW_MACRO_GNU_define_indirect:
19787         case DW_MACRO_GNU_undef_indirect:
19788         case DW_MACRO_GNU_define_indirect_alt:
19789         case DW_MACRO_GNU_undef_indirect_alt:
19790           {
19791             unsigned int bytes_read;
19792
19793             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19794             mac_ptr += bytes_read;
19795             mac_ptr += offset_size;
19796           }
19797           break;
19798
19799         case DW_MACRO_GNU_transparent_include:
19800         case DW_MACRO_GNU_transparent_include_alt:
19801           /* Note that, according to the spec, a transparent include
19802              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19803              skip this opcode.  */
19804           mac_ptr += offset_size;
19805           break;
19806
19807         case DW_MACINFO_vendor_ext:
19808           /* Only skip the data by MAC_PTR.  */
19809           if (!section_is_gnu)
19810             {
19811               unsigned int bytes_read;
19812
19813               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19814               mac_ptr += bytes_read;
19815               read_direct_string (abfd, mac_ptr, &bytes_read);
19816               mac_ptr += bytes_read;
19817             }
19818           /* FALLTHROUGH */
19819
19820         default:
19821           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19822                                          mac_ptr, mac_end, abfd, offset_size,
19823                                          section);
19824           if (mac_ptr == NULL)
19825             return;
19826           break;
19827         }
19828     } while (macinfo_type != 0 && current_file == NULL);
19829
19830   /* Second pass: Process all entries.
19831
19832      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19833      command-line macro definitions/undefinitions.  This flag is unset when we
19834      reach the first DW_MACINFO_start_file entry.  */
19835
19836   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19837                                     NULL, xcalloc, xfree);
19838   cleanup = make_cleanup_htab_delete (include_hash);
19839   mac_ptr = section->buffer + offset;
19840   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19841   *slot = (void *) mac_ptr;
19842   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19843                             current_file, lh, comp_dir, section,
19844                             section_is_gnu, 0,
19845                             offset_size, objfile, include_hash);
19846   do_cleanups (cleanup);
19847 }
19848
19849 /* Check if the attribute's form is a DW_FORM_block*
19850    if so return true else false.  */
19851
19852 static int
19853 attr_form_is_block (const struct attribute *attr)
19854 {
19855   return (attr == NULL ? 0 :
19856       attr->form == DW_FORM_block1
19857       || attr->form == DW_FORM_block2
19858       || attr->form == DW_FORM_block4
19859       || attr->form == DW_FORM_block
19860       || attr->form == DW_FORM_exprloc);
19861 }
19862
19863 /* Return non-zero if ATTR's value is a section offset --- classes
19864    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19865    You may use DW_UNSND (attr) to retrieve such offsets.
19866
19867    Section 7.5.4, "Attribute Encodings", explains that no attribute
19868    may have a value that belongs to more than one of these classes; it
19869    would be ambiguous if we did, because we use the same forms for all
19870    of them.  */
19871
19872 static int
19873 attr_form_is_section_offset (const struct attribute *attr)
19874 {
19875   return (attr->form == DW_FORM_data4
19876           || attr->form == DW_FORM_data8
19877           || attr->form == DW_FORM_sec_offset);
19878 }
19879
19880 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19881    zero otherwise.  When this function returns true, you can apply
19882    dwarf2_get_attr_constant_value to it.
19883
19884    However, note that for some attributes you must check
19885    attr_form_is_section_offset before using this test.  DW_FORM_data4
19886    and DW_FORM_data8 are members of both the constant class, and of
19887    the classes that contain offsets into other debug sections
19888    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19889    that, if an attribute's can be either a constant or one of the
19890    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19891    taken as section offsets, not constants.  */
19892
19893 static int
19894 attr_form_is_constant (const struct attribute *attr)
19895 {
19896   switch (attr->form)
19897     {
19898     case DW_FORM_sdata:
19899     case DW_FORM_udata:
19900     case DW_FORM_data1:
19901     case DW_FORM_data2:
19902     case DW_FORM_data4:
19903     case DW_FORM_data8:
19904       return 1;
19905     default:
19906       return 0;
19907     }
19908 }
19909
19910
19911 /* DW_ADDR is always stored already as sect_offset; despite for the forms
19912    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
19913
19914 static int
19915 attr_form_is_ref (const struct attribute *attr)
19916 {
19917   switch (attr->form)
19918     {
19919     case DW_FORM_ref_addr:
19920     case DW_FORM_ref1:
19921     case DW_FORM_ref2:
19922     case DW_FORM_ref4:
19923     case DW_FORM_ref8:
19924     case DW_FORM_ref_udata:
19925     case DW_FORM_GNU_ref_alt:
19926       return 1;
19927     default:
19928       return 0;
19929     }
19930 }
19931
19932 /* Return the .debug_loc section to use for CU.
19933    For DWO files use .debug_loc.dwo.  */
19934
19935 static struct dwarf2_section_info *
19936 cu_debug_loc_section (struct dwarf2_cu *cu)
19937 {
19938   if (cu->dwo_unit)
19939     return &cu->dwo_unit->dwo_file->sections.loc;
19940   return &dwarf2_per_objfile->loc;
19941 }
19942
19943 /* A helper function that fills in a dwarf2_loclist_baton.  */
19944
19945 static void
19946 fill_in_loclist_baton (struct dwarf2_cu *cu,
19947                        struct dwarf2_loclist_baton *baton,
19948                        const struct attribute *attr)
19949 {
19950   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19951
19952   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19953
19954   baton->per_cu = cu->per_cu;
19955   gdb_assert (baton->per_cu);
19956   /* We don't know how long the location list is, but make sure we
19957      don't run off the edge of the section.  */
19958   baton->size = section->size - DW_UNSND (attr);
19959   baton->data = section->buffer + DW_UNSND (attr);
19960   baton->base_address = cu->base_address;
19961   baton->from_dwo = cu->dwo_unit != NULL;
19962 }
19963
19964 static void
19965 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
19966                              struct dwarf2_cu *cu, int is_block)
19967 {
19968   struct objfile *objfile = dwarf2_per_objfile->objfile;
19969   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19970
19971   if (attr_form_is_section_offset (attr)
19972       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19973          the section.  If so, fall through to the complaint in the
19974          other branch.  */
19975       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19976     {
19977       struct dwarf2_loclist_baton *baton;
19978
19979       baton = obstack_alloc (&objfile->objfile_obstack,
19980                              sizeof (struct dwarf2_loclist_baton));
19981
19982       fill_in_loclist_baton (cu, baton, attr);
19983
19984       if (cu->base_known == 0)
19985         complaint (&symfile_complaints,
19986                    _("Location list used without "
19987                      "specifying the CU base address."));
19988
19989       SYMBOL_ACLASS_INDEX (sym) = (is_block
19990                                    ? dwarf2_loclist_block_index
19991                                    : dwarf2_loclist_index);
19992       SYMBOL_LOCATION_BATON (sym) = baton;
19993     }
19994   else
19995     {
19996       struct dwarf2_locexpr_baton *baton;
19997
19998       baton = obstack_alloc (&objfile->objfile_obstack,
19999                              sizeof (struct dwarf2_locexpr_baton));
20000       baton->per_cu = cu->per_cu;
20001       gdb_assert (baton->per_cu);
20002
20003       if (attr_form_is_block (attr))
20004         {
20005           /* Note that we're just copying the block's data pointer
20006              here, not the actual data.  We're still pointing into the
20007              info_buffer for SYM's objfile; right now we never release
20008              that buffer, but when we do clean up properly this may
20009              need to change.  */
20010           baton->size = DW_BLOCK (attr)->size;
20011           baton->data = DW_BLOCK (attr)->data;
20012         }
20013       else
20014         {
20015           dwarf2_invalid_attrib_class_complaint ("location description",
20016                                                  SYMBOL_NATURAL_NAME (sym));
20017           baton->size = 0;
20018         }
20019
20020       SYMBOL_ACLASS_INDEX (sym) = (is_block
20021                                    ? dwarf2_locexpr_block_index
20022                                    : dwarf2_locexpr_index);
20023       SYMBOL_LOCATION_BATON (sym) = baton;
20024     }
20025 }
20026
20027 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20028    came from a separate debuginfo file, then the master objfile is
20029    returned.  */
20030
20031 struct objfile *
20032 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20033 {
20034   struct objfile *objfile = per_cu->objfile;
20035
20036   /* Return the master objfile, so that we can report and look up the
20037      correct file containing this variable.  */
20038   if (objfile->separate_debug_objfile_backlink)
20039     objfile = objfile->separate_debug_objfile_backlink;
20040
20041   return objfile;
20042 }
20043
20044 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20045    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20046    CU_HEADERP first.  */
20047
20048 static const struct comp_unit_head *
20049 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20050                        struct dwarf2_per_cu_data *per_cu)
20051 {
20052   const gdb_byte *info_ptr;
20053
20054   if (per_cu->cu)
20055     return &per_cu->cu->header;
20056
20057   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20058
20059   memset (cu_headerp, 0, sizeof (*cu_headerp));
20060   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20061
20062   return cu_headerp;
20063 }
20064
20065 /* Return the address size given in the compilation unit header for CU.  */
20066
20067 int
20068 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20069 {
20070   struct comp_unit_head cu_header_local;
20071   const struct comp_unit_head *cu_headerp;
20072
20073   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20074
20075   return cu_headerp->addr_size;
20076 }
20077
20078 /* Return the offset size given in the compilation unit header for CU.  */
20079
20080 int
20081 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20082 {
20083   struct comp_unit_head cu_header_local;
20084   const struct comp_unit_head *cu_headerp;
20085
20086   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20087
20088   return cu_headerp->offset_size;
20089 }
20090
20091 /* See its dwarf2loc.h declaration.  */
20092
20093 int
20094 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20095 {
20096   struct comp_unit_head cu_header_local;
20097   const struct comp_unit_head *cu_headerp;
20098
20099   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20100
20101   if (cu_headerp->version == 2)
20102     return cu_headerp->addr_size;
20103   else
20104     return cu_headerp->offset_size;
20105 }
20106
20107 /* Return the text offset of the CU.  The returned offset comes from
20108    this CU's objfile.  If this objfile came from a separate debuginfo
20109    file, then the offset may be different from the corresponding
20110    offset in the parent objfile.  */
20111
20112 CORE_ADDR
20113 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20114 {
20115   struct objfile *objfile = per_cu->objfile;
20116
20117   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20118 }
20119
20120 /* Locate the .debug_info compilation unit from CU's objfile which contains
20121    the DIE at OFFSET.  Raises an error on failure.  */
20122
20123 static struct dwarf2_per_cu_data *
20124 dwarf2_find_containing_comp_unit (sect_offset offset,
20125                                   unsigned int offset_in_dwz,
20126                                   struct objfile *objfile)
20127 {
20128   struct dwarf2_per_cu_data *this_cu;
20129   int low, high;
20130   const sect_offset *cu_off;
20131
20132   low = 0;
20133   high = dwarf2_per_objfile->n_comp_units - 1;
20134   while (high > low)
20135     {
20136       struct dwarf2_per_cu_data *mid_cu;
20137       int mid = low + (high - low) / 2;
20138
20139       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20140       cu_off = &mid_cu->offset;
20141       if (mid_cu->is_dwz > offset_in_dwz
20142           || (mid_cu->is_dwz == offset_in_dwz
20143               && cu_off->sect_off >= offset.sect_off))
20144         high = mid;
20145       else
20146         low = mid + 1;
20147     }
20148   gdb_assert (low == high);
20149   this_cu = dwarf2_per_objfile->all_comp_units[low];
20150   cu_off = &this_cu->offset;
20151   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20152     {
20153       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20154         error (_("Dwarf Error: could not find partial DIE containing "
20155                "offset 0x%lx [in module %s]"),
20156                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20157
20158       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20159                   <= offset.sect_off);
20160       return dwarf2_per_objfile->all_comp_units[low-1];
20161     }
20162   else
20163     {
20164       this_cu = dwarf2_per_objfile->all_comp_units[low];
20165       if (low == dwarf2_per_objfile->n_comp_units - 1
20166           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20167         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20168       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20169       return this_cu;
20170     }
20171 }
20172
20173 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20174
20175 static void
20176 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20177 {
20178   memset (cu, 0, sizeof (*cu));
20179   per_cu->cu = cu;
20180   cu->per_cu = per_cu;
20181   cu->objfile = per_cu->objfile;
20182   obstack_init (&cu->comp_unit_obstack);
20183 }
20184
20185 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20186
20187 static void
20188 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20189                        enum language pretend_language)
20190 {
20191   struct attribute *attr;
20192
20193   /* Set the language we're debugging.  */
20194   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20195   if (attr)
20196     set_cu_language (DW_UNSND (attr), cu);
20197   else
20198     {
20199       cu->language = pretend_language;
20200       cu->language_defn = language_def (cu->language);
20201     }
20202
20203   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20204   if (attr)
20205     cu->producer = DW_STRING (attr);
20206 }
20207
20208 /* Release one cached compilation unit, CU.  We unlink it from the tree
20209    of compilation units, but we don't remove it from the read_in_chain;
20210    the caller is responsible for that.
20211    NOTE: DATA is a void * because this function is also used as a
20212    cleanup routine.  */
20213
20214 static void
20215 free_heap_comp_unit (void *data)
20216 {
20217   struct dwarf2_cu *cu = data;
20218
20219   gdb_assert (cu->per_cu != NULL);
20220   cu->per_cu->cu = NULL;
20221   cu->per_cu = NULL;
20222
20223   obstack_free (&cu->comp_unit_obstack, NULL);
20224
20225   xfree (cu);
20226 }
20227
20228 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20229    when we're finished with it.  We can't free the pointer itself, but be
20230    sure to unlink it from the cache.  Also release any associated storage.  */
20231
20232 static void
20233 free_stack_comp_unit (void *data)
20234 {
20235   struct dwarf2_cu *cu = data;
20236
20237   gdb_assert (cu->per_cu != NULL);
20238   cu->per_cu->cu = NULL;
20239   cu->per_cu = NULL;
20240
20241   obstack_free (&cu->comp_unit_obstack, NULL);
20242   cu->partial_dies = NULL;
20243 }
20244
20245 /* Free all cached compilation units.  */
20246
20247 static void
20248 free_cached_comp_units (void *data)
20249 {
20250   struct dwarf2_per_cu_data *per_cu, **last_chain;
20251
20252   per_cu = dwarf2_per_objfile->read_in_chain;
20253   last_chain = &dwarf2_per_objfile->read_in_chain;
20254   while (per_cu != NULL)
20255     {
20256       struct dwarf2_per_cu_data *next_cu;
20257
20258       next_cu = per_cu->cu->read_in_chain;
20259
20260       free_heap_comp_unit (per_cu->cu);
20261       *last_chain = next_cu;
20262
20263       per_cu = next_cu;
20264     }
20265 }
20266
20267 /* Increase the age counter on each cached compilation unit, and free
20268    any that are too old.  */
20269
20270 static void
20271 age_cached_comp_units (void)
20272 {
20273   struct dwarf2_per_cu_data *per_cu, **last_chain;
20274
20275   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20276   per_cu = dwarf2_per_objfile->read_in_chain;
20277   while (per_cu != NULL)
20278     {
20279       per_cu->cu->last_used ++;
20280       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20281         dwarf2_mark (per_cu->cu);
20282       per_cu = per_cu->cu->read_in_chain;
20283     }
20284
20285   per_cu = dwarf2_per_objfile->read_in_chain;
20286   last_chain = &dwarf2_per_objfile->read_in_chain;
20287   while (per_cu != NULL)
20288     {
20289       struct dwarf2_per_cu_data *next_cu;
20290
20291       next_cu = per_cu->cu->read_in_chain;
20292
20293       if (!per_cu->cu->mark)
20294         {
20295           free_heap_comp_unit (per_cu->cu);
20296           *last_chain = next_cu;
20297         }
20298       else
20299         last_chain = &per_cu->cu->read_in_chain;
20300
20301       per_cu = next_cu;
20302     }
20303 }
20304
20305 /* Remove a single compilation unit from the cache.  */
20306
20307 static void
20308 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20309 {
20310   struct dwarf2_per_cu_data *per_cu, **last_chain;
20311
20312   per_cu = dwarf2_per_objfile->read_in_chain;
20313   last_chain = &dwarf2_per_objfile->read_in_chain;
20314   while (per_cu != NULL)
20315     {
20316       struct dwarf2_per_cu_data *next_cu;
20317
20318       next_cu = per_cu->cu->read_in_chain;
20319
20320       if (per_cu == target_per_cu)
20321         {
20322           free_heap_comp_unit (per_cu->cu);
20323           per_cu->cu = NULL;
20324           *last_chain = next_cu;
20325           break;
20326         }
20327       else
20328         last_chain = &per_cu->cu->read_in_chain;
20329
20330       per_cu = next_cu;
20331     }
20332 }
20333
20334 /* Release all extra memory associated with OBJFILE.  */
20335
20336 void
20337 dwarf2_free_objfile (struct objfile *objfile)
20338 {
20339   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20340
20341   if (dwarf2_per_objfile == NULL)
20342     return;
20343
20344   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20345   free_cached_comp_units (NULL);
20346
20347   if (dwarf2_per_objfile->quick_file_names_table)
20348     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20349
20350   /* Everything else should be on the objfile obstack.  */
20351 }
20352
20353 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20354    We store these in a hash table separate from the DIEs, and preserve them
20355    when the DIEs are flushed out of cache.
20356
20357    The CU "per_cu" pointer is needed because offset alone is not enough to
20358    uniquely identify the type.  A file may have multiple .debug_types sections,
20359    or the type may come from a DWO file.  Furthermore, while it's more logical
20360    to use per_cu->section+offset, with Fission the section with the data is in
20361    the DWO file but we don't know that section at the point we need it.
20362    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20363    because we can enter the lookup routine, get_die_type_at_offset, from
20364    outside this file, and thus won't necessarily have PER_CU->cu.
20365    Fortunately, PER_CU is stable for the life of the objfile.  */
20366
20367 struct dwarf2_per_cu_offset_and_type
20368 {
20369   const struct dwarf2_per_cu_data *per_cu;
20370   sect_offset offset;
20371   struct type *type;
20372 };
20373
20374 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20375
20376 static hashval_t
20377 per_cu_offset_and_type_hash (const void *item)
20378 {
20379   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20380
20381   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20382 }
20383
20384 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20385
20386 static int
20387 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20388 {
20389   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20390   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20391
20392   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20393           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20394 }
20395
20396 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20397    table if necessary.  For convenience, return TYPE.
20398
20399    The DIEs reading must have careful ordering to:
20400     * Not cause infite loops trying to read in DIEs as a prerequisite for
20401       reading current DIE.
20402     * Not trying to dereference contents of still incompletely read in types
20403       while reading in other DIEs.
20404     * Enable referencing still incompletely read in types just by a pointer to
20405       the type without accessing its fields.
20406
20407    Therefore caller should follow these rules:
20408      * Try to fetch any prerequisite types we may need to build this DIE type
20409        before building the type and calling set_die_type.
20410      * After building type call set_die_type for current DIE as soon as
20411        possible before fetching more types to complete the current type.
20412      * Make the type as complete as possible before fetching more types.  */
20413
20414 static struct type *
20415 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20416 {
20417   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20418   struct objfile *objfile = cu->objfile;
20419
20420   /* For Ada types, make sure that the gnat-specific data is always
20421      initialized (if not already set).  There are a few types where
20422      we should not be doing so, because the type-specific area is
20423      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20424      where the type-specific area is used to store the floatformat).
20425      But this is not a problem, because the gnat-specific information
20426      is actually not needed for these types.  */
20427   if (need_gnat_info (cu)
20428       && TYPE_CODE (type) != TYPE_CODE_FUNC
20429       && TYPE_CODE (type) != TYPE_CODE_FLT
20430       && !HAVE_GNAT_AUX_INFO (type))
20431     INIT_GNAT_SPECIFIC (type);
20432
20433   if (dwarf2_per_objfile->die_type_hash == NULL)
20434     {
20435       dwarf2_per_objfile->die_type_hash =
20436         htab_create_alloc_ex (127,
20437                               per_cu_offset_and_type_hash,
20438                               per_cu_offset_and_type_eq,
20439                               NULL,
20440                               &objfile->objfile_obstack,
20441                               hashtab_obstack_allocate,
20442                               dummy_obstack_deallocate);
20443     }
20444
20445   ofs.per_cu = cu->per_cu;
20446   ofs.offset = die->offset;
20447   ofs.type = type;
20448   slot = (struct dwarf2_per_cu_offset_and_type **)
20449     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20450   if (*slot)
20451     complaint (&symfile_complaints,
20452                _("A problem internal to GDB: DIE 0x%x has type already set"),
20453                die->offset.sect_off);
20454   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20455   **slot = ofs;
20456   return type;
20457 }
20458
20459 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20460    or return NULL if the die does not have a saved type.  */
20461
20462 static struct type *
20463 get_die_type_at_offset (sect_offset offset,
20464                         struct dwarf2_per_cu_data *per_cu)
20465 {
20466   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20467
20468   if (dwarf2_per_objfile->die_type_hash == NULL)
20469     return NULL;
20470
20471   ofs.per_cu = per_cu;
20472   ofs.offset = offset;
20473   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20474   if (slot)
20475     return slot->type;
20476   else
20477     return NULL;
20478 }
20479
20480 /* Look up the type for DIE in CU in die_type_hash,
20481    or return NULL if DIE does not have a saved type.  */
20482
20483 static struct type *
20484 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20485 {
20486   return get_die_type_at_offset (die->offset, cu->per_cu);
20487 }
20488
20489 /* Add a dependence relationship from CU to REF_PER_CU.  */
20490
20491 static void
20492 dwarf2_add_dependence (struct dwarf2_cu *cu,
20493                        struct dwarf2_per_cu_data *ref_per_cu)
20494 {
20495   void **slot;
20496
20497   if (cu->dependencies == NULL)
20498     cu->dependencies
20499       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20500                               NULL, &cu->comp_unit_obstack,
20501                               hashtab_obstack_allocate,
20502                               dummy_obstack_deallocate);
20503
20504   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20505   if (*slot == NULL)
20506     *slot = ref_per_cu;
20507 }
20508
20509 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20510    Set the mark field in every compilation unit in the
20511    cache that we must keep because we are keeping CU.  */
20512
20513 static int
20514 dwarf2_mark_helper (void **slot, void *data)
20515 {
20516   struct dwarf2_per_cu_data *per_cu;
20517
20518   per_cu = (struct dwarf2_per_cu_data *) *slot;
20519
20520   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20521      reading of the chain.  As such dependencies remain valid it is not much
20522      useful to track and undo them during QUIT cleanups.  */
20523   if (per_cu->cu == NULL)
20524     return 1;
20525
20526   if (per_cu->cu->mark)
20527     return 1;
20528   per_cu->cu->mark = 1;
20529
20530   if (per_cu->cu->dependencies != NULL)
20531     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20532
20533   return 1;
20534 }
20535
20536 /* Set the mark field in CU and in every other compilation unit in the
20537    cache that we must keep because we are keeping CU.  */
20538
20539 static void
20540 dwarf2_mark (struct dwarf2_cu *cu)
20541 {
20542   if (cu->mark)
20543     return;
20544   cu->mark = 1;
20545   if (cu->dependencies != NULL)
20546     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20547 }
20548
20549 static void
20550 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20551 {
20552   while (per_cu)
20553     {
20554       per_cu->cu->mark = 0;
20555       per_cu = per_cu->cu->read_in_chain;
20556     }
20557 }
20558
20559 /* Trivial hash function for partial_die_info: the hash value of a DIE
20560    is its offset in .debug_info for this objfile.  */
20561
20562 static hashval_t
20563 partial_die_hash (const void *item)
20564 {
20565   const struct partial_die_info *part_die = item;
20566
20567   return part_die->offset.sect_off;
20568 }
20569
20570 /* Trivial comparison function for partial_die_info structures: two DIEs
20571    are equal if they have the same offset.  */
20572
20573 static int
20574 partial_die_eq (const void *item_lhs, const void *item_rhs)
20575 {
20576   const struct partial_die_info *part_die_lhs = item_lhs;
20577   const struct partial_die_info *part_die_rhs = item_rhs;
20578
20579   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20580 }
20581
20582 static struct cmd_list_element *set_dwarf2_cmdlist;
20583 static struct cmd_list_element *show_dwarf2_cmdlist;
20584
20585 static void
20586 set_dwarf2_cmd (char *args, int from_tty)
20587 {
20588   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20589 }
20590
20591 static void
20592 show_dwarf2_cmd (char *args, int from_tty)
20593 {
20594   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20595 }
20596
20597 /* Free data associated with OBJFILE, if necessary.  */
20598
20599 static void
20600 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20601 {
20602   struct dwarf2_per_objfile *data = d;
20603   int ix;
20604
20605   /* Make sure we don't accidentally use dwarf2_per_objfile while
20606      cleaning up.  */
20607   dwarf2_per_objfile = NULL;
20608
20609   for (ix = 0; ix < data->n_comp_units; ++ix)
20610    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20611
20612   for (ix = 0; ix < data->n_type_units; ++ix)
20613     VEC_free (dwarf2_per_cu_ptr,
20614               data->all_type_units[ix]->per_cu.imported_symtabs);
20615   xfree (data->all_type_units);
20616
20617   VEC_free (dwarf2_section_info_def, data->types);
20618
20619   if (data->dwo_files)
20620     free_dwo_files (data->dwo_files, objfile);
20621   if (data->dwp_file)
20622     gdb_bfd_unref (data->dwp_file->dbfd);
20623
20624   if (data->dwz_file && data->dwz_file->dwz_bfd)
20625     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20626 }
20627
20628 \f
20629 /* The "save gdb-index" command.  */
20630
20631 /* The contents of the hash table we create when building the string
20632    table.  */
20633 struct strtab_entry
20634 {
20635   offset_type offset;
20636   const char *str;
20637 };
20638
20639 /* Hash function for a strtab_entry.
20640
20641    Function is used only during write_hash_table so no index format backward
20642    compatibility is needed.  */
20643
20644 static hashval_t
20645 hash_strtab_entry (const void *e)
20646 {
20647   const struct strtab_entry *entry = e;
20648   return mapped_index_string_hash (INT_MAX, entry->str);
20649 }
20650
20651 /* Equality function for a strtab_entry.  */
20652
20653 static int
20654 eq_strtab_entry (const void *a, const void *b)
20655 {
20656   const struct strtab_entry *ea = a;
20657   const struct strtab_entry *eb = b;
20658   return !strcmp (ea->str, eb->str);
20659 }
20660
20661 /* Create a strtab_entry hash table.  */
20662
20663 static htab_t
20664 create_strtab (void)
20665 {
20666   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20667                             xfree, xcalloc, xfree);
20668 }
20669
20670 /* Add a string to the constant pool.  Return the string's offset in
20671    host order.  */
20672
20673 static offset_type
20674 add_string (htab_t table, struct obstack *cpool, const char *str)
20675 {
20676   void **slot;
20677   struct strtab_entry entry;
20678   struct strtab_entry *result;
20679
20680   entry.str = str;
20681   slot = htab_find_slot (table, &entry, INSERT);
20682   if (*slot)
20683     result = *slot;
20684   else
20685     {
20686       result = XNEW (struct strtab_entry);
20687       result->offset = obstack_object_size (cpool);
20688       result->str = str;
20689       obstack_grow_str0 (cpool, str);
20690       *slot = result;
20691     }
20692   return result->offset;
20693 }
20694
20695 /* An entry in the symbol table.  */
20696 struct symtab_index_entry
20697 {
20698   /* The name of the symbol.  */
20699   const char *name;
20700   /* The offset of the name in the constant pool.  */
20701   offset_type index_offset;
20702   /* A sorted vector of the indices of all the CUs that hold an object
20703      of this name.  */
20704   VEC (offset_type) *cu_indices;
20705 };
20706
20707 /* The symbol table.  This is a power-of-2-sized hash table.  */
20708 struct mapped_symtab
20709 {
20710   offset_type n_elements;
20711   offset_type size;
20712   struct symtab_index_entry **data;
20713 };
20714
20715 /* Hash function for a symtab_index_entry.  */
20716
20717 static hashval_t
20718 hash_symtab_entry (const void *e)
20719 {
20720   const struct symtab_index_entry *entry = e;
20721   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20722                          sizeof (offset_type) * VEC_length (offset_type,
20723                                                             entry->cu_indices),
20724                          0);
20725 }
20726
20727 /* Equality function for a symtab_index_entry.  */
20728
20729 static int
20730 eq_symtab_entry (const void *a, const void *b)
20731 {
20732   const struct symtab_index_entry *ea = a;
20733   const struct symtab_index_entry *eb = b;
20734   int len = VEC_length (offset_type, ea->cu_indices);
20735   if (len != VEC_length (offset_type, eb->cu_indices))
20736     return 0;
20737   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20738                   VEC_address (offset_type, eb->cu_indices),
20739                   sizeof (offset_type) * len);
20740 }
20741
20742 /* Destroy a symtab_index_entry.  */
20743
20744 static void
20745 delete_symtab_entry (void *p)
20746 {
20747   struct symtab_index_entry *entry = p;
20748   VEC_free (offset_type, entry->cu_indices);
20749   xfree (entry);
20750 }
20751
20752 /* Create a hash table holding symtab_index_entry objects.  */
20753
20754 static htab_t
20755 create_symbol_hash_table (void)
20756 {
20757   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20758                             delete_symtab_entry, xcalloc, xfree);
20759 }
20760
20761 /* Create a new mapped symtab object.  */
20762
20763 static struct mapped_symtab *
20764 create_mapped_symtab (void)
20765 {
20766   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20767   symtab->n_elements = 0;
20768   symtab->size = 1024;
20769   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20770   return symtab;
20771 }
20772
20773 /* Destroy a mapped_symtab.  */
20774
20775 static void
20776 cleanup_mapped_symtab (void *p)
20777 {
20778   struct mapped_symtab *symtab = p;
20779   /* The contents of the array are freed when the other hash table is
20780      destroyed.  */
20781   xfree (symtab->data);
20782   xfree (symtab);
20783 }
20784
20785 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20786    the slot.
20787    
20788    Function is used only during write_hash_table so no index format backward
20789    compatibility is needed.  */
20790
20791 static struct symtab_index_entry **
20792 find_slot (struct mapped_symtab *symtab, const char *name)
20793 {
20794   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20795
20796   index = hash & (symtab->size - 1);
20797   step = ((hash * 17) & (symtab->size - 1)) | 1;
20798
20799   for (;;)
20800     {
20801       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20802         return &symtab->data[index];
20803       index = (index + step) & (symtab->size - 1);
20804     }
20805 }
20806
20807 /* Expand SYMTAB's hash table.  */
20808
20809 static void
20810 hash_expand (struct mapped_symtab *symtab)
20811 {
20812   offset_type old_size = symtab->size;
20813   offset_type i;
20814   struct symtab_index_entry **old_entries = symtab->data;
20815
20816   symtab->size *= 2;
20817   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20818
20819   for (i = 0; i < old_size; ++i)
20820     {
20821       if (old_entries[i])
20822         {
20823           struct symtab_index_entry **slot = find_slot (symtab,
20824                                                         old_entries[i]->name);
20825           *slot = old_entries[i];
20826         }
20827     }
20828
20829   xfree (old_entries);
20830 }
20831
20832 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20833    CU_INDEX is the index of the CU in which the symbol appears.
20834    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20835
20836 static void
20837 add_index_entry (struct mapped_symtab *symtab, const char *name,
20838                  int is_static, gdb_index_symbol_kind kind,
20839                  offset_type cu_index)
20840 {
20841   struct symtab_index_entry **slot;
20842   offset_type cu_index_and_attrs;
20843
20844   ++symtab->n_elements;
20845   if (4 * symtab->n_elements / 3 >= symtab->size)
20846     hash_expand (symtab);
20847
20848   slot = find_slot (symtab, name);
20849   if (!*slot)
20850     {
20851       *slot = XNEW (struct symtab_index_entry);
20852       (*slot)->name = name;
20853       /* index_offset is set later.  */
20854       (*slot)->cu_indices = NULL;
20855     }
20856
20857   cu_index_and_attrs = 0;
20858   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20859   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20860   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20861
20862   /* We don't want to record an index value twice as we want to avoid the
20863      duplication.
20864      We process all global symbols and then all static symbols
20865      (which would allow us to avoid the duplication by only having to check
20866      the last entry pushed), but a symbol could have multiple kinds in one CU.
20867      To keep things simple we don't worry about the duplication here and
20868      sort and uniqufy the list after we've processed all symbols.  */
20869   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20870 }
20871
20872 /* qsort helper routine for uniquify_cu_indices.  */
20873
20874 static int
20875 offset_type_compare (const void *ap, const void *bp)
20876 {
20877   offset_type a = *(offset_type *) ap;
20878   offset_type b = *(offset_type *) bp;
20879
20880   return (a > b) - (b > a);
20881 }
20882
20883 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20884
20885 static void
20886 uniquify_cu_indices (struct mapped_symtab *symtab)
20887 {
20888   int i;
20889
20890   for (i = 0; i < symtab->size; ++i)
20891     {
20892       struct symtab_index_entry *entry = symtab->data[i];
20893
20894       if (entry
20895           && entry->cu_indices != NULL)
20896         {
20897           unsigned int next_to_insert, next_to_check;
20898           offset_type last_value;
20899
20900           qsort (VEC_address (offset_type, entry->cu_indices),
20901                  VEC_length (offset_type, entry->cu_indices),
20902                  sizeof (offset_type), offset_type_compare);
20903
20904           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20905           next_to_insert = 1;
20906           for (next_to_check = 1;
20907                next_to_check < VEC_length (offset_type, entry->cu_indices);
20908                ++next_to_check)
20909             {
20910               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20911                   != last_value)
20912                 {
20913                   last_value = VEC_index (offset_type, entry->cu_indices,
20914                                           next_to_check);
20915                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20916                                last_value);
20917                   ++next_to_insert;
20918                 }
20919             }
20920           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20921         }
20922     }
20923 }
20924
20925 /* Add a vector of indices to the constant pool.  */
20926
20927 static offset_type
20928 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20929                       struct symtab_index_entry *entry)
20930 {
20931   void **slot;
20932
20933   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20934   if (!*slot)
20935     {
20936       offset_type len = VEC_length (offset_type, entry->cu_indices);
20937       offset_type val = MAYBE_SWAP (len);
20938       offset_type iter;
20939       int i;
20940
20941       *slot = entry;
20942       entry->index_offset = obstack_object_size (cpool);
20943
20944       obstack_grow (cpool, &val, sizeof (val));
20945       for (i = 0;
20946            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20947            ++i)
20948         {
20949           val = MAYBE_SWAP (iter);
20950           obstack_grow (cpool, &val, sizeof (val));
20951         }
20952     }
20953   else
20954     {
20955       struct symtab_index_entry *old_entry = *slot;
20956       entry->index_offset = old_entry->index_offset;
20957       entry = old_entry;
20958     }
20959   return entry->index_offset;
20960 }
20961
20962 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20963    constant pool entries going into the obstack CPOOL.  */
20964
20965 static void
20966 write_hash_table (struct mapped_symtab *symtab,
20967                   struct obstack *output, struct obstack *cpool)
20968 {
20969   offset_type i;
20970   htab_t symbol_hash_table;
20971   htab_t str_table;
20972
20973   symbol_hash_table = create_symbol_hash_table ();
20974   str_table = create_strtab ();
20975
20976   /* We add all the index vectors to the constant pool first, to
20977      ensure alignment is ok.  */
20978   for (i = 0; i < symtab->size; ++i)
20979     {
20980       if (symtab->data[i])
20981         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20982     }
20983
20984   /* Now write out the hash table.  */
20985   for (i = 0; i < symtab->size; ++i)
20986     {
20987       offset_type str_off, vec_off;
20988
20989       if (symtab->data[i])
20990         {
20991           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20992           vec_off = symtab->data[i]->index_offset;
20993         }
20994       else
20995         {
20996           /* While 0 is a valid constant pool index, it is not valid
20997              to have 0 for both offsets.  */
20998           str_off = 0;
20999           vec_off = 0;
21000         }
21001
21002       str_off = MAYBE_SWAP (str_off);
21003       vec_off = MAYBE_SWAP (vec_off);
21004
21005       obstack_grow (output, &str_off, sizeof (str_off));
21006       obstack_grow (output, &vec_off, sizeof (vec_off));
21007     }
21008
21009   htab_delete (str_table);
21010   htab_delete (symbol_hash_table);
21011 }
21012
21013 /* Struct to map psymtab to CU index in the index file.  */
21014 struct psymtab_cu_index_map
21015 {
21016   struct partial_symtab *psymtab;
21017   unsigned int cu_index;
21018 };
21019
21020 static hashval_t
21021 hash_psymtab_cu_index (const void *item)
21022 {
21023   const struct psymtab_cu_index_map *map = item;
21024
21025   return htab_hash_pointer (map->psymtab);
21026 }
21027
21028 static int
21029 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21030 {
21031   const struct psymtab_cu_index_map *lhs = item_lhs;
21032   const struct psymtab_cu_index_map *rhs = item_rhs;
21033
21034   return lhs->psymtab == rhs->psymtab;
21035 }
21036
21037 /* Helper struct for building the address table.  */
21038 struct addrmap_index_data
21039 {
21040   struct objfile *objfile;
21041   struct obstack *addr_obstack;
21042   htab_t cu_index_htab;
21043
21044   /* Non-zero if the previous_* fields are valid.
21045      We can't write an entry until we see the next entry (since it is only then
21046      that we know the end of the entry).  */
21047   int previous_valid;
21048   /* Index of the CU in the table of all CUs in the index file.  */
21049   unsigned int previous_cu_index;
21050   /* Start address of the CU.  */
21051   CORE_ADDR previous_cu_start;
21052 };
21053
21054 /* Write an address entry to OBSTACK.  */
21055
21056 static void
21057 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21058                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21059 {
21060   offset_type cu_index_to_write;
21061   gdb_byte addr[8];
21062   CORE_ADDR baseaddr;
21063
21064   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21065
21066   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21067   obstack_grow (obstack, addr, 8);
21068   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21069   obstack_grow (obstack, addr, 8);
21070   cu_index_to_write = MAYBE_SWAP (cu_index);
21071   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21072 }
21073
21074 /* Worker function for traversing an addrmap to build the address table.  */
21075
21076 static int
21077 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21078 {
21079   struct addrmap_index_data *data = datap;
21080   struct partial_symtab *pst = obj;
21081
21082   if (data->previous_valid)
21083     add_address_entry (data->objfile, data->addr_obstack,
21084                        data->previous_cu_start, start_addr,
21085                        data->previous_cu_index);
21086
21087   data->previous_cu_start = start_addr;
21088   if (pst != NULL)
21089     {
21090       struct psymtab_cu_index_map find_map, *map;
21091       find_map.psymtab = pst;
21092       map = htab_find (data->cu_index_htab, &find_map);
21093       gdb_assert (map != NULL);
21094       data->previous_cu_index = map->cu_index;
21095       data->previous_valid = 1;
21096     }
21097   else
21098       data->previous_valid = 0;
21099
21100   return 0;
21101 }
21102
21103 /* Write OBJFILE's address map to OBSTACK.
21104    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21105    in the index file.  */
21106
21107 static void
21108 write_address_map (struct objfile *objfile, struct obstack *obstack,
21109                    htab_t cu_index_htab)
21110 {
21111   struct addrmap_index_data addrmap_index_data;
21112
21113   /* When writing the address table, we have to cope with the fact that
21114      the addrmap iterator only provides the start of a region; we have to
21115      wait until the next invocation to get the start of the next region.  */
21116
21117   addrmap_index_data.objfile = objfile;
21118   addrmap_index_data.addr_obstack = obstack;
21119   addrmap_index_data.cu_index_htab = cu_index_htab;
21120   addrmap_index_data.previous_valid = 0;
21121
21122   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21123                    &addrmap_index_data);
21124
21125   /* It's highly unlikely the last entry (end address = 0xff...ff)
21126      is valid, but we should still handle it.
21127      The end address is recorded as the start of the next region, but that
21128      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21129      anyway.  */
21130   if (addrmap_index_data.previous_valid)
21131     add_address_entry (objfile, obstack,
21132                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21133                        addrmap_index_data.previous_cu_index);
21134 }
21135
21136 /* Return the symbol kind of PSYM.  */
21137
21138 static gdb_index_symbol_kind
21139 symbol_kind (struct partial_symbol *psym)
21140 {
21141   domain_enum domain = PSYMBOL_DOMAIN (psym);
21142   enum address_class aclass = PSYMBOL_CLASS (psym);
21143
21144   switch (domain)
21145     {
21146     case VAR_DOMAIN:
21147       switch (aclass)
21148         {
21149         case LOC_BLOCK:
21150           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21151         case LOC_TYPEDEF:
21152           return GDB_INDEX_SYMBOL_KIND_TYPE;
21153         case LOC_COMPUTED:
21154         case LOC_CONST_BYTES:
21155         case LOC_OPTIMIZED_OUT:
21156         case LOC_STATIC:
21157           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21158         case LOC_CONST:
21159           /* Note: It's currently impossible to recognize psyms as enum values
21160              short of reading the type info.  For now punt.  */
21161           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21162         default:
21163           /* There are other LOC_FOO values that one might want to classify
21164              as variables, but dwarf2read.c doesn't currently use them.  */
21165           return GDB_INDEX_SYMBOL_KIND_OTHER;
21166         }
21167     case STRUCT_DOMAIN:
21168       return GDB_INDEX_SYMBOL_KIND_TYPE;
21169     default:
21170       return GDB_INDEX_SYMBOL_KIND_OTHER;
21171     }
21172 }
21173
21174 /* Add a list of partial symbols to SYMTAB.  */
21175
21176 static void
21177 write_psymbols (struct mapped_symtab *symtab,
21178                 htab_t psyms_seen,
21179                 struct partial_symbol **psymp,
21180                 int count,
21181                 offset_type cu_index,
21182                 int is_static)
21183 {
21184   for (; count-- > 0; ++psymp)
21185     {
21186       struct partial_symbol *psym = *psymp;
21187       void **slot;
21188
21189       if (SYMBOL_LANGUAGE (psym) == language_ada)
21190         error (_("Ada is not currently supported by the index"));
21191
21192       /* Only add a given psymbol once.  */
21193       slot = htab_find_slot (psyms_seen, psym, INSERT);
21194       if (!*slot)
21195         {
21196           gdb_index_symbol_kind kind = symbol_kind (psym);
21197
21198           *slot = psym;
21199           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21200                            is_static, kind, cu_index);
21201         }
21202     }
21203 }
21204
21205 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21206    exception if there is an error.  */
21207
21208 static void
21209 write_obstack (FILE *file, struct obstack *obstack)
21210 {
21211   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21212               file)
21213       != obstack_object_size (obstack))
21214     error (_("couldn't data write to file"));
21215 }
21216
21217 /* Unlink a file if the argument is not NULL.  */
21218
21219 static void
21220 unlink_if_set (void *p)
21221 {
21222   char **filename = p;
21223   if (*filename)
21224     unlink (*filename);
21225 }
21226
21227 /* A helper struct used when iterating over debug_types.  */
21228 struct signatured_type_index_data
21229 {
21230   struct objfile *objfile;
21231   struct mapped_symtab *symtab;
21232   struct obstack *types_list;
21233   htab_t psyms_seen;
21234   int cu_index;
21235 };
21236
21237 /* A helper function that writes a single signatured_type to an
21238    obstack.  */
21239
21240 static int
21241 write_one_signatured_type (void **slot, void *d)
21242 {
21243   struct signatured_type_index_data *info = d;
21244   struct signatured_type *entry = (struct signatured_type *) *slot;
21245   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21246   gdb_byte val[8];
21247
21248   write_psymbols (info->symtab,
21249                   info->psyms_seen,
21250                   info->objfile->global_psymbols.list
21251                   + psymtab->globals_offset,
21252                   psymtab->n_global_syms, info->cu_index,
21253                   0);
21254   write_psymbols (info->symtab,
21255                   info->psyms_seen,
21256                   info->objfile->static_psymbols.list
21257                   + psymtab->statics_offset,
21258                   psymtab->n_static_syms, info->cu_index,
21259                   1);
21260
21261   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21262                           entry->per_cu.offset.sect_off);
21263   obstack_grow (info->types_list, val, 8);
21264   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21265                           entry->type_offset_in_tu.cu_off);
21266   obstack_grow (info->types_list, val, 8);
21267   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21268   obstack_grow (info->types_list, val, 8);
21269
21270   ++info->cu_index;
21271
21272   return 1;
21273 }
21274
21275 /* Recurse into all "included" dependencies and write their symbols as
21276    if they appeared in this psymtab.  */
21277
21278 static void
21279 recursively_write_psymbols (struct objfile *objfile,
21280                             struct partial_symtab *psymtab,
21281                             struct mapped_symtab *symtab,
21282                             htab_t psyms_seen,
21283                             offset_type cu_index)
21284 {
21285   int i;
21286
21287   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21288     if (psymtab->dependencies[i]->user != NULL)
21289       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21290                                   symtab, psyms_seen, cu_index);
21291
21292   write_psymbols (symtab,
21293                   psyms_seen,
21294                   objfile->global_psymbols.list + psymtab->globals_offset,
21295                   psymtab->n_global_syms, cu_index,
21296                   0);
21297   write_psymbols (symtab,
21298                   psyms_seen,
21299                   objfile->static_psymbols.list + psymtab->statics_offset,
21300                   psymtab->n_static_syms, cu_index,
21301                   1);
21302 }
21303
21304 /* Create an index file for OBJFILE in the directory DIR.  */
21305
21306 static void
21307 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21308 {
21309   struct cleanup *cleanup;
21310   char *filename, *cleanup_filename;
21311   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21312   struct obstack cu_list, types_cu_list;
21313   int i;
21314   FILE *out_file;
21315   struct mapped_symtab *symtab;
21316   offset_type val, size_of_contents, total_len;
21317   struct stat st;
21318   htab_t psyms_seen;
21319   htab_t cu_index_htab;
21320   struct psymtab_cu_index_map *psymtab_cu_index_map;
21321
21322   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21323     return;
21324
21325   if (dwarf2_per_objfile->using_index)
21326     error (_("Cannot use an index to create the index"));
21327
21328   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21329     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21330
21331   if (stat (objfile->name, &st) < 0)
21332     perror_with_name (objfile->name);
21333
21334   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
21335                      INDEX_SUFFIX, (char *) NULL);
21336   cleanup = make_cleanup (xfree, filename);
21337
21338   out_file = gdb_fopen_cloexec (filename, "wb");
21339   if (!out_file)
21340     error (_("Can't open `%s' for writing"), filename);
21341
21342   cleanup_filename = filename;
21343   make_cleanup (unlink_if_set, &cleanup_filename);
21344
21345   symtab = create_mapped_symtab ();
21346   make_cleanup (cleanup_mapped_symtab, symtab);
21347
21348   obstack_init (&addr_obstack);
21349   make_cleanup_obstack_free (&addr_obstack);
21350
21351   obstack_init (&cu_list);
21352   make_cleanup_obstack_free (&cu_list);
21353
21354   obstack_init (&types_cu_list);
21355   make_cleanup_obstack_free (&types_cu_list);
21356
21357   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21358                                   NULL, xcalloc, xfree);
21359   make_cleanup_htab_delete (psyms_seen);
21360
21361   /* While we're scanning CU's create a table that maps a psymtab pointer
21362      (which is what addrmap records) to its index (which is what is recorded
21363      in the index file).  This will later be needed to write the address
21364      table.  */
21365   cu_index_htab = htab_create_alloc (100,
21366                                      hash_psymtab_cu_index,
21367                                      eq_psymtab_cu_index,
21368                                      NULL, xcalloc, xfree);
21369   make_cleanup_htab_delete (cu_index_htab);
21370   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21371     xmalloc (sizeof (struct psymtab_cu_index_map)
21372              * dwarf2_per_objfile->n_comp_units);
21373   make_cleanup (xfree, psymtab_cu_index_map);
21374
21375   /* The CU list is already sorted, so we don't need to do additional
21376      work here.  Also, the debug_types entries do not appear in
21377      all_comp_units, but only in their own hash table.  */
21378   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21379     {
21380       struct dwarf2_per_cu_data *per_cu
21381         = dwarf2_per_objfile->all_comp_units[i];
21382       struct partial_symtab *psymtab = per_cu->v.psymtab;
21383       gdb_byte val[8];
21384       struct psymtab_cu_index_map *map;
21385       void **slot;
21386
21387       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21388          It may be referenced from a local scope but in such case it does not
21389          need to be present in .gdb_index.  */
21390       if (psymtab == NULL)
21391         continue;
21392
21393       if (psymtab->user == NULL)
21394         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21395
21396       map = &psymtab_cu_index_map[i];
21397       map->psymtab = psymtab;
21398       map->cu_index = i;
21399       slot = htab_find_slot (cu_index_htab, map, INSERT);
21400       gdb_assert (slot != NULL);
21401       gdb_assert (*slot == NULL);
21402       *slot = map;
21403
21404       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21405                               per_cu->offset.sect_off);
21406       obstack_grow (&cu_list, val, 8);
21407       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21408       obstack_grow (&cu_list, val, 8);
21409     }
21410
21411   /* Dump the address map.  */
21412   write_address_map (objfile, &addr_obstack, cu_index_htab);
21413
21414   /* Write out the .debug_type entries, if any.  */
21415   if (dwarf2_per_objfile->signatured_types)
21416     {
21417       struct signatured_type_index_data sig_data;
21418
21419       sig_data.objfile = objfile;
21420       sig_data.symtab = symtab;
21421       sig_data.types_list = &types_cu_list;
21422       sig_data.psyms_seen = psyms_seen;
21423       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21424       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21425                               write_one_signatured_type, &sig_data);
21426     }
21427
21428   /* Now that we've processed all symbols we can shrink their cu_indices
21429      lists.  */
21430   uniquify_cu_indices (symtab);
21431
21432   obstack_init (&constant_pool);
21433   make_cleanup_obstack_free (&constant_pool);
21434   obstack_init (&symtab_obstack);
21435   make_cleanup_obstack_free (&symtab_obstack);
21436   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21437
21438   obstack_init (&contents);
21439   make_cleanup_obstack_free (&contents);
21440   size_of_contents = 6 * sizeof (offset_type);
21441   total_len = size_of_contents;
21442
21443   /* The version number.  */
21444   val = MAYBE_SWAP (8);
21445   obstack_grow (&contents, &val, sizeof (val));
21446
21447   /* The offset of the CU list from the start of the file.  */
21448   val = MAYBE_SWAP (total_len);
21449   obstack_grow (&contents, &val, sizeof (val));
21450   total_len += obstack_object_size (&cu_list);
21451
21452   /* The offset of the types CU list from the start of the file.  */
21453   val = MAYBE_SWAP (total_len);
21454   obstack_grow (&contents, &val, sizeof (val));
21455   total_len += obstack_object_size (&types_cu_list);
21456
21457   /* The offset of the address table from the start of the file.  */
21458   val = MAYBE_SWAP (total_len);
21459   obstack_grow (&contents, &val, sizeof (val));
21460   total_len += obstack_object_size (&addr_obstack);
21461
21462   /* The offset of the symbol table from the start of the file.  */
21463   val = MAYBE_SWAP (total_len);
21464   obstack_grow (&contents, &val, sizeof (val));
21465   total_len += obstack_object_size (&symtab_obstack);
21466
21467   /* The offset of the constant pool from the start of the file.  */
21468   val = MAYBE_SWAP (total_len);
21469   obstack_grow (&contents, &val, sizeof (val));
21470   total_len += obstack_object_size (&constant_pool);
21471
21472   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21473
21474   write_obstack (out_file, &contents);
21475   write_obstack (out_file, &cu_list);
21476   write_obstack (out_file, &types_cu_list);
21477   write_obstack (out_file, &addr_obstack);
21478   write_obstack (out_file, &symtab_obstack);
21479   write_obstack (out_file, &constant_pool);
21480
21481   fclose (out_file);
21482
21483   /* We want to keep the file, so we set cleanup_filename to NULL
21484      here.  See unlink_if_set.  */
21485   cleanup_filename = NULL;
21486
21487   do_cleanups (cleanup);
21488 }
21489
21490 /* Implementation of the `save gdb-index' command.
21491    
21492    Note that the file format used by this command is documented in the
21493    GDB manual.  Any changes here must be documented there.  */
21494
21495 static void
21496 save_gdb_index_command (char *arg, int from_tty)
21497 {
21498   struct objfile *objfile;
21499
21500   if (!arg || !*arg)
21501     error (_("usage: save gdb-index DIRECTORY"));
21502
21503   ALL_OBJFILES (objfile)
21504   {
21505     struct stat st;
21506
21507     /* If the objfile does not correspond to an actual file, skip it.  */
21508     if (stat (objfile->name, &st) < 0)
21509       continue;
21510
21511     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21512     if (dwarf2_per_objfile)
21513       {
21514         volatile struct gdb_exception except;
21515
21516         TRY_CATCH (except, RETURN_MASK_ERROR)
21517           {
21518             write_psymtabs_to_index (objfile, arg);
21519           }
21520         if (except.reason < 0)
21521           exception_fprintf (gdb_stderr, except,
21522                              _("Error while writing index for `%s': "),
21523                              objfile->name);
21524       }
21525   }
21526 }
21527
21528 \f
21529
21530 int dwarf2_always_disassemble;
21531
21532 static void
21533 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21534                                 struct cmd_list_element *c, const char *value)
21535 {
21536   fprintf_filtered (file,
21537                     _("Whether to always disassemble "
21538                       "DWARF expressions is %s.\n"),
21539                     value);
21540 }
21541
21542 static void
21543 show_check_physname (struct ui_file *file, int from_tty,
21544                      struct cmd_list_element *c, const char *value)
21545 {
21546   fprintf_filtered (file,
21547                     _("Whether to check \"physname\" is %s.\n"),
21548                     value);
21549 }
21550
21551 void _initialize_dwarf2_read (void);
21552
21553 void
21554 _initialize_dwarf2_read (void)
21555 {
21556   struct cmd_list_element *c;
21557
21558   dwarf2_objfile_data_key
21559     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21560
21561   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21562 Set DWARF 2 specific variables.\n\
21563 Configure DWARF 2 variables such as the cache size"),
21564                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21565                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21566
21567   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21568 Show DWARF 2 specific variables\n\
21569 Show DWARF 2 variables such as the cache size"),
21570                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21571                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21572
21573   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21574                             &dwarf2_max_cache_age, _("\
21575 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21576 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21577 A higher limit means that cached compilation units will be stored\n\
21578 in memory longer, and more total memory will be used.  Zero disables\n\
21579 caching, which can slow down startup."),
21580                             NULL,
21581                             show_dwarf2_max_cache_age,
21582                             &set_dwarf2_cmdlist,
21583                             &show_dwarf2_cmdlist);
21584
21585   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21586                            &dwarf2_always_disassemble, _("\
21587 Set whether `info address' always disassembles DWARF expressions."), _("\
21588 Show whether `info address' always disassembles DWARF expressions."), _("\
21589 When enabled, DWARF expressions are always printed in an assembly-like\n\
21590 syntax.  When disabled, expressions will be printed in a more\n\
21591 conversational style, when possible."),
21592                            NULL,
21593                            show_dwarf2_always_disassemble,
21594                            &set_dwarf2_cmdlist,
21595                            &show_dwarf2_cmdlist);
21596
21597   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21598 Set debugging of the dwarf2 reader."), _("\
21599 Show debugging of the dwarf2 reader."), _("\
21600 When enabled, debugging messages are printed during dwarf2 reading\n\
21601 and symtab expansion."),
21602                             NULL,
21603                             NULL,
21604                             &setdebuglist, &showdebuglist);
21605
21606   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21607 Set debugging of the dwarf2 DIE reader."), _("\
21608 Show debugging of the dwarf2 DIE reader."), _("\
21609 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21610 The value is the maximum depth to print."),
21611                              NULL,
21612                              NULL,
21613                              &setdebuglist, &showdebuglist);
21614
21615   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21616 Set cross-checking of \"physname\" code against demangler."), _("\
21617 Show cross-checking of \"physname\" code against demangler."), _("\
21618 When enabled, GDB's internal \"physname\" code is checked against\n\
21619 the demangler."),
21620                            NULL, show_check_physname,
21621                            &setdebuglist, &showdebuglist);
21622
21623   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21624                            no_class, &use_deprecated_index_sections, _("\
21625 Set whether to use deprecated gdb_index sections."), _("\
21626 Show whether to use deprecated gdb_index sections."), _("\
21627 When enabled, deprecated .gdb_index sections are used anyway.\n\
21628 Normally they are ignored either because of a missing feature or\n\
21629 performance issue.\n\
21630 Warning: This option must be enabled before gdb reads the file."),
21631                            NULL,
21632                            NULL,
21633                            &setlist, &showlist);
21634
21635   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21636                _("\
21637 Save a gdb-index file.\n\
21638 Usage: save gdb-index DIRECTORY"),
21639                &save_cmdlist);
21640   set_cmd_completer (c, filename_completer);
21641
21642   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21643                                                         &dwarf2_locexpr_funcs);
21644   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21645                                                         &dwarf2_loclist_funcs);
21646
21647   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21648                                         &dwarf2_block_frame_base_locexpr_funcs);
21649   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21650                                         &dwarf2_block_frame_base_loclist_funcs);
21651 }