remove unused qf method
[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 static void
3449 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3450                           struct objfile *objfile, int global,
3451                           int (*callback) (struct block *,
3452                                            struct symbol *, void *),
3453                           void *data, symbol_compare_ftype *match,
3454                           symbol_compare_ftype *ordered_compare)
3455 {
3456   /* Currently unimplemented; used for Ada.  The function can be called if the
3457      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3458      does not look for non-Ada symbols this function should just return.  */
3459 }
3460
3461 static void
3462 dw2_expand_symtabs_matching
3463   (struct objfile *objfile,
3464    int (*file_matcher) (const char *, void *, int basenames),
3465    int (*name_matcher) (const char *, void *),
3466    enum search_domain kind,
3467    void *data)
3468 {
3469   int i;
3470   offset_type iter;
3471   struct mapped_index *index;
3472
3473   dw2_setup (objfile);
3474
3475   /* index_table is NULL if OBJF_READNOW.  */
3476   if (!dwarf2_per_objfile->index_table)
3477     return;
3478   index = dwarf2_per_objfile->index_table;
3479
3480   if (file_matcher != NULL)
3481     {
3482       struct cleanup *cleanup;
3483       htab_t visited_found, visited_not_found;
3484
3485       visited_found = htab_create_alloc (10,
3486                                          htab_hash_pointer, htab_eq_pointer,
3487                                          NULL, xcalloc, xfree);
3488       cleanup = make_cleanup_htab_delete (visited_found);
3489       visited_not_found = htab_create_alloc (10,
3490                                              htab_hash_pointer, htab_eq_pointer,
3491                                              NULL, xcalloc, xfree);
3492       make_cleanup_htab_delete (visited_not_found);
3493
3494       /* The rule is CUs specify all the files, including those used by
3495          any TU, so there's no need to scan TUs here.  */
3496
3497       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3498         {
3499           int j;
3500           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3501           struct quick_file_names *file_data;
3502           void **slot;
3503
3504           per_cu->v.quick->mark = 0;
3505
3506           /* We only need to look at symtabs not already expanded.  */
3507           if (per_cu->v.quick->symtab)
3508             continue;
3509
3510           file_data = dw2_get_file_names (per_cu);
3511           if (file_data == NULL)
3512             continue;
3513
3514           if (htab_find (visited_not_found, file_data) != NULL)
3515             continue;
3516           else if (htab_find (visited_found, file_data) != NULL)
3517             {
3518               per_cu->v.quick->mark = 1;
3519               continue;
3520             }
3521
3522           for (j = 0; j < file_data->num_file_names; ++j)
3523             {
3524               const char *this_real_name;
3525
3526               if (file_matcher (file_data->file_names[j], data, 0))
3527                 {
3528                   per_cu->v.quick->mark = 1;
3529                   break;
3530                 }
3531
3532               /* Before we invoke realpath, which can get expensive when many
3533                  files are involved, do a quick comparison of the basenames.  */
3534               if (!basenames_may_differ
3535                   && !file_matcher (lbasename (file_data->file_names[j]),
3536                                     data, 1))
3537                 continue;
3538
3539               this_real_name = dw2_get_real_path (objfile, file_data, j);
3540               if (file_matcher (this_real_name, data, 0))
3541                 {
3542                   per_cu->v.quick->mark = 1;
3543                   break;
3544                 }
3545             }
3546
3547           slot = htab_find_slot (per_cu->v.quick->mark
3548                                  ? visited_found
3549                                  : visited_not_found,
3550                                  file_data, INSERT);
3551           *slot = file_data;
3552         }
3553
3554       do_cleanups (cleanup);
3555     }
3556
3557   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3558     {
3559       offset_type idx = 2 * iter;
3560       const char *name;
3561       offset_type *vec, vec_len, vec_idx;
3562
3563       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3564         continue;
3565
3566       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3567
3568       if (! (*name_matcher) (name, data))
3569         continue;
3570
3571       /* The name was matched, now expand corresponding CUs that were
3572          marked.  */
3573       vec = (offset_type *) (index->constant_pool
3574                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3575       vec_len = MAYBE_SWAP (vec[0]);
3576       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3577         {
3578           struct dwarf2_per_cu_data *per_cu;
3579           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3580           gdb_index_symbol_kind symbol_kind =
3581             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3582           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3583           /* Only check the symbol attributes if they're present.
3584              Indices prior to version 7 don't record them,
3585              and indices >= 7 may elide them for certain symbols
3586              (gold does this).  */
3587           int attrs_valid =
3588             (index->version >= 7
3589              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3590
3591           /* Only check the symbol's kind if it has one.  */
3592           if (attrs_valid)
3593             {
3594               switch (kind)
3595                 {
3596                 case VARIABLES_DOMAIN:
3597                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3598                     continue;
3599                   break;
3600                 case FUNCTIONS_DOMAIN:
3601                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3602                     continue;
3603                   break;
3604                 case TYPES_DOMAIN:
3605                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3606                     continue;
3607                   break;
3608                 default:
3609                   break;
3610                 }
3611             }
3612
3613           /* Don't crash on bad data.  */
3614           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3615                            + dwarf2_per_objfile->n_type_units))
3616             {
3617               complaint (&symfile_complaints,
3618                          _(".gdb_index entry has bad CU index"
3619                            " [in module %s]"), objfile->name);
3620               continue;
3621             }
3622
3623           per_cu = dw2_get_cu (cu_index);
3624           if (file_matcher == NULL || per_cu->v.quick->mark)
3625             dw2_instantiate_symtab (per_cu);
3626         }
3627     }
3628 }
3629
3630 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3631    symtab.  */
3632
3633 static struct symtab *
3634 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3635 {
3636   int i;
3637
3638   if (BLOCKVECTOR (symtab) != NULL
3639       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3640     return symtab;
3641
3642   if (symtab->includes == NULL)
3643     return NULL;
3644
3645   for (i = 0; symtab->includes[i]; ++i)
3646     {
3647       struct symtab *s = symtab->includes[i];
3648
3649       s = recursively_find_pc_sect_symtab (s, pc);
3650       if (s != NULL)
3651         return s;
3652     }
3653
3654   return NULL;
3655 }
3656
3657 static struct symtab *
3658 dw2_find_pc_sect_symtab (struct objfile *objfile,
3659                          struct minimal_symbol *msymbol,
3660                          CORE_ADDR pc,
3661                          struct obj_section *section,
3662                          int warn_if_readin)
3663 {
3664   struct dwarf2_per_cu_data *data;
3665   struct symtab *result;
3666
3667   dw2_setup (objfile);
3668
3669   if (!objfile->psymtabs_addrmap)
3670     return NULL;
3671
3672   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3673   if (!data)
3674     return NULL;
3675
3676   if (warn_if_readin && data->v.quick->symtab)
3677     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3678              paddress (get_objfile_arch (objfile), pc));
3679
3680   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3681   gdb_assert (result != NULL);
3682   return result;
3683 }
3684
3685 static void
3686 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3687                           void *data, int need_fullname)
3688 {
3689   int i;
3690   struct cleanup *cleanup;
3691   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3692                                       NULL, xcalloc, xfree);
3693
3694   cleanup = make_cleanup_htab_delete (visited);
3695   dw2_setup (objfile);
3696
3697   /* The rule is CUs specify all the files, including those used by
3698      any TU, so there's no need to scan TUs here.
3699      We can ignore file names coming from already-expanded CUs.  */
3700
3701   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3702     {
3703       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3704
3705       if (per_cu->v.quick->symtab)
3706         {
3707           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3708                                         INSERT);
3709
3710           *slot = per_cu->v.quick->file_names;
3711         }
3712     }
3713
3714   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3715     {
3716       int j;
3717       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3718       struct quick_file_names *file_data;
3719       void **slot;
3720
3721       /* We only need to look at symtabs not already expanded.  */
3722       if (per_cu->v.quick->symtab)
3723         continue;
3724
3725       file_data = dw2_get_file_names (per_cu);
3726       if (file_data == NULL)
3727         continue;
3728
3729       slot = htab_find_slot (visited, file_data, INSERT);
3730       if (*slot)
3731         {
3732           /* Already visited.  */
3733           continue;
3734         }
3735       *slot = file_data;
3736
3737       for (j = 0; j < file_data->num_file_names; ++j)
3738         {
3739           const char *this_real_name;
3740
3741           if (need_fullname)
3742             this_real_name = dw2_get_real_path (objfile, file_data, j);
3743           else
3744             this_real_name = NULL;
3745           (*fun) (file_data->file_names[j], this_real_name, data);
3746         }
3747     }
3748
3749   do_cleanups (cleanup);
3750 }
3751
3752 static int
3753 dw2_has_symbols (struct objfile *objfile)
3754 {
3755   return 1;
3756 }
3757
3758 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3759 {
3760   dw2_has_symbols,
3761   dw2_find_last_source_symtab,
3762   dw2_forget_cached_source_info,
3763   dw2_map_symtabs_matching_filename,
3764   dw2_lookup_symbol,
3765   dw2_print_stats,
3766   dw2_dump,
3767   dw2_relocate,
3768   dw2_expand_symtabs_for_function,
3769   dw2_expand_all_symtabs,
3770   dw2_expand_symtabs_with_fullname,
3771   dw2_map_matching_symbols,
3772   dw2_expand_symtabs_matching,
3773   dw2_find_pc_sect_symtab,
3774   dw2_map_symbol_filenames
3775 };
3776
3777 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3778    file will use psymtabs, or 1 if using the GNU index.  */
3779
3780 int
3781 dwarf2_initialize_objfile (struct objfile *objfile)
3782 {
3783   /* If we're about to read full symbols, don't bother with the
3784      indices.  In this case we also don't care if some other debug
3785      format is making psymtabs, because they are all about to be
3786      expanded anyway.  */
3787   if ((objfile->flags & OBJF_READNOW))
3788     {
3789       int i;
3790
3791       dwarf2_per_objfile->using_index = 1;
3792       create_all_comp_units (objfile);
3793       create_all_type_units (objfile);
3794       dwarf2_per_objfile->quick_file_names_table =
3795         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3796
3797       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3798                        + dwarf2_per_objfile->n_type_units); ++i)
3799         {
3800           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3801
3802           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3803                                             struct dwarf2_per_cu_quick_data);
3804         }
3805
3806       /* Return 1 so that gdb sees the "quick" functions.  However,
3807          these functions will be no-ops because we will have expanded
3808          all symtabs.  */
3809       return 1;
3810     }
3811
3812   if (dwarf2_read_index (objfile))
3813     return 1;
3814
3815   return 0;
3816 }
3817
3818 \f
3819
3820 /* Build a partial symbol table.  */
3821
3822 void
3823 dwarf2_build_psymtabs (struct objfile *objfile)
3824 {
3825   volatile struct gdb_exception except;
3826
3827   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3828     {
3829       init_psymbol_list (objfile, 1024);
3830     }
3831
3832   TRY_CATCH (except, RETURN_MASK_ERROR)
3833     {
3834       /* This isn't really ideal: all the data we allocate on the
3835          objfile's obstack is still uselessly kept around.  However,
3836          freeing it seems unsafe.  */
3837       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3838
3839       dwarf2_build_psymtabs_hard (objfile);
3840       discard_cleanups (cleanups);
3841     }
3842   if (except.reason < 0)
3843     exception_print (gdb_stderr, except);
3844 }
3845
3846 /* Return the total length of the CU described by HEADER.  */
3847
3848 static unsigned int
3849 get_cu_length (const struct comp_unit_head *header)
3850 {
3851   return header->initial_length_size + header->length;
3852 }
3853
3854 /* Return TRUE if OFFSET is within CU_HEADER.  */
3855
3856 static inline int
3857 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3858 {
3859   sect_offset bottom = { cu_header->offset.sect_off };
3860   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3861
3862   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3863 }
3864
3865 /* Find the base address of the compilation unit for range lists and
3866    location lists.  It will normally be specified by DW_AT_low_pc.
3867    In DWARF-3 draft 4, the base address could be overridden by
3868    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3869    compilation units with discontinuous ranges.  */
3870
3871 static void
3872 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3873 {
3874   struct attribute *attr;
3875
3876   cu->base_known = 0;
3877   cu->base_address = 0;
3878
3879   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3880   if (attr)
3881     {
3882       cu->base_address = DW_ADDR (attr);
3883       cu->base_known = 1;
3884     }
3885   else
3886     {
3887       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3888       if (attr)
3889         {
3890           cu->base_address = DW_ADDR (attr);
3891           cu->base_known = 1;
3892         }
3893     }
3894 }
3895
3896 /* Read in the comp unit header information from the debug_info at info_ptr.
3897    NOTE: This leaves members offset, first_die_offset to be filled in
3898    by the caller.  */
3899
3900 static const gdb_byte *
3901 read_comp_unit_head (struct comp_unit_head *cu_header,
3902                      const gdb_byte *info_ptr, bfd *abfd)
3903 {
3904   int signed_addr;
3905   unsigned int bytes_read;
3906
3907   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3908   cu_header->initial_length_size = bytes_read;
3909   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3910   info_ptr += bytes_read;
3911   cu_header->version = read_2_bytes (abfd, info_ptr);
3912   info_ptr += 2;
3913   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3914                                              &bytes_read);
3915   info_ptr += bytes_read;
3916   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3917   info_ptr += 1;
3918   signed_addr = bfd_get_sign_extend_vma (abfd);
3919   if (signed_addr < 0)
3920     internal_error (__FILE__, __LINE__,
3921                     _("read_comp_unit_head: dwarf from non elf file"));
3922   cu_header->signed_addr_p = signed_addr;
3923
3924   return info_ptr;
3925 }
3926
3927 /* Helper function that returns the proper abbrev section for
3928    THIS_CU.  */
3929
3930 static struct dwarf2_section_info *
3931 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3932 {
3933   struct dwarf2_section_info *abbrev;
3934
3935   if (this_cu->is_dwz)
3936     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3937   else
3938     abbrev = &dwarf2_per_objfile->abbrev;
3939
3940   return abbrev;
3941 }
3942
3943 /* Subroutine of read_and_check_comp_unit_head and
3944    read_and_check_type_unit_head to simplify them.
3945    Perform various error checking on the header.  */
3946
3947 static void
3948 error_check_comp_unit_head (struct comp_unit_head *header,
3949                             struct dwarf2_section_info *section,
3950                             struct dwarf2_section_info *abbrev_section)
3951 {
3952   bfd *abfd = section->asection->owner;
3953   const char *filename = bfd_get_filename (abfd);
3954
3955   if (header->version != 2 && header->version != 3 && header->version != 4)
3956     error (_("Dwarf Error: wrong version in compilation unit header "
3957            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3958            filename);
3959
3960   if (header->abbrev_offset.sect_off
3961       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3962     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3963            "(offset 0x%lx + 6) [in module %s]"),
3964            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3965            filename);
3966
3967   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3968      avoid potential 32-bit overflow.  */
3969   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3970       > section->size)
3971     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3972            "(offset 0x%lx + 0) [in module %s]"),
3973            (long) header->length, (long) header->offset.sect_off,
3974            filename);
3975 }
3976
3977 /* Read in a CU/TU header and perform some basic error checking.
3978    The contents of the header are stored in HEADER.
3979    The result is a pointer to the start of the first DIE.  */
3980
3981 static const gdb_byte *
3982 read_and_check_comp_unit_head (struct comp_unit_head *header,
3983                                struct dwarf2_section_info *section,
3984                                struct dwarf2_section_info *abbrev_section,
3985                                const gdb_byte *info_ptr,
3986                                int is_debug_types_section)
3987 {
3988   const gdb_byte *beg_of_comp_unit = info_ptr;
3989   bfd *abfd = section->asection->owner;
3990
3991   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3992
3993   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3994
3995   /* If we're reading a type unit, skip over the signature and
3996      type_offset fields.  */
3997   if (is_debug_types_section)
3998     info_ptr += 8 /*signature*/ + header->offset_size;
3999
4000   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4001
4002   error_check_comp_unit_head (header, section, abbrev_section);
4003
4004   return info_ptr;
4005 }
4006
4007 /* Read in the types comp unit header information from .debug_types entry at
4008    types_ptr.  The result is a pointer to one past the end of the header.  */
4009
4010 static const gdb_byte *
4011 read_and_check_type_unit_head (struct comp_unit_head *header,
4012                                struct dwarf2_section_info *section,
4013                                struct dwarf2_section_info *abbrev_section,
4014                                const gdb_byte *info_ptr,
4015                                ULONGEST *signature,
4016                                cu_offset *type_offset_in_tu)
4017 {
4018   const gdb_byte *beg_of_comp_unit = info_ptr;
4019   bfd *abfd = section->asection->owner;
4020
4021   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4022
4023   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4024
4025   /* If we're reading a type unit, skip over the signature and
4026      type_offset fields.  */
4027   if (signature != NULL)
4028     *signature = read_8_bytes (abfd, info_ptr);
4029   info_ptr += 8;
4030   if (type_offset_in_tu != NULL)
4031     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4032                                                header->offset_size);
4033   info_ptr += header->offset_size;
4034
4035   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4036
4037   error_check_comp_unit_head (header, section, abbrev_section);
4038
4039   return info_ptr;
4040 }
4041
4042 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4043
4044 static sect_offset
4045 read_abbrev_offset (struct dwarf2_section_info *section,
4046                     sect_offset offset)
4047 {
4048   bfd *abfd = section->asection->owner;
4049   const gdb_byte *info_ptr;
4050   unsigned int length, initial_length_size, offset_size;
4051   sect_offset abbrev_offset;
4052
4053   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4054   info_ptr = section->buffer + offset.sect_off;
4055   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4056   offset_size = initial_length_size == 4 ? 4 : 8;
4057   info_ptr += initial_length_size + 2 /*version*/;
4058   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4059   return abbrev_offset;
4060 }
4061
4062 /* Allocate a new partial symtab for file named NAME and mark this new
4063    partial symtab as being an include of PST.  */
4064
4065 static void
4066 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4067                                struct objfile *objfile)
4068 {
4069   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4070
4071   if (!IS_ABSOLUTE_PATH (subpst->filename))
4072     {
4073       /* It shares objfile->objfile_obstack.  */
4074       subpst->dirname = pst->dirname;
4075     }
4076
4077   subpst->section_offsets = pst->section_offsets;
4078   subpst->textlow = 0;
4079   subpst->texthigh = 0;
4080
4081   subpst->dependencies = (struct partial_symtab **)
4082     obstack_alloc (&objfile->objfile_obstack,
4083                    sizeof (struct partial_symtab *));
4084   subpst->dependencies[0] = pst;
4085   subpst->number_of_dependencies = 1;
4086
4087   subpst->globals_offset = 0;
4088   subpst->n_global_syms = 0;
4089   subpst->statics_offset = 0;
4090   subpst->n_static_syms = 0;
4091   subpst->symtab = NULL;
4092   subpst->read_symtab = pst->read_symtab;
4093   subpst->readin = 0;
4094
4095   /* No private part is necessary for include psymtabs.  This property
4096      can be used to differentiate between such include psymtabs and
4097      the regular ones.  */
4098   subpst->read_symtab_private = NULL;
4099 }
4100
4101 /* Read the Line Number Program data and extract the list of files
4102    included by the source file represented by PST.  Build an include
4103    partial symtab for each of these included files.  */
4104
4105 static void
4106 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4107                                struct die_info *die,
4108                                struct partial_symtab *pst)
4109 {
4110   struct line_header *lh = NULL;
4111   struct attribute *attr;
4112
4113   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4114   if (attr)
4115     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4116   if (lh == NULL)
4117     return;  /* No linetable, so no includes.  */
4118
4119   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4120   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4121
4122   free_line_header (lh);
4123 }
4124
4125 static hashval_t
4126 hash_signatured_type (const void *item)
4127 {
4128   const struct signatured_type *sig_type = item;
4129
4130   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4131   return sig_type->signature;
4132 }
4133
4134 static int
4135 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4136 {
4137   const struct signatured_type *lhs = item_lhs;
4138   const struct signatured_type *rhs = item_rhs;
4139
4140   return lhs->signature == rhs->signature;
4141 }
4142
4143 /* Allocate a hash table for signatured types.  */
4144
4145 static htab_t
4146 allocate_signatured_type_table (struct objfile *objfile)
4147 {
4148   return htab_create_alloc_ex (41,
4149                                hash_signatured_type,
4150                                eq_signatured_type,
4151                                NULL,
4152                                &objfile->objfile_obstack,
4153                                hashtab_obstack_allocate,
4154                                dummy_obstack_deallocate);
4155 }
4156
4157 /* A helper function to add a signatured type CU to a table.  */
4158
4159 static int
4160 add_signatured_type_cu_to_table (void **slot, void *datum)
4161 {
4162   struct signatured_type *sigt = *slot;
4163   struct signatured_type ***datap = datum;
4164
4165   **datap = sigt;
4166   ++*datap;
4167
4168   return 1;
4169 }
4170
4171 /* Create the hash table of all entries in the .debug_types
4172    (or .debug_types.dwo) section(s).
4173    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4174    otherwise it is NULL.
4175
4176    The result is a pointer to the hash table or NULL if there are no types.
4177
4178    Note: This function processes DWO files only, not DWP files.  */
4179
4180 static htab_t
4181 create_debug_types_hash_table (struct dwo_file *dwo_file,
4182                                VEC (dwarf2_section_info_def) *types)
4183 {
4184   struct objfile *objfile = dwarf2_per_objfile->objfile;
4185   htab_t types_htab = NULL;
4186   int ix;
4187   struct dwarf2_section_info *section;
4188   struct dwarf2_section_info *abbrev_section;
4189
4190   if (VEC_empty (dwarf2_section_info_def, types))
4191     return NULL;
4192
4193   abbrev_section = (dwo_file != NULL
4194                     ? &dwo_file->sections.abbrev
4195                     : &dwarf2_per_objfile->abbrev);
4196
4197   if (dwarf2_read_debug)
4198     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4199                         dwo_file ? ".dwo" : "",
4200                         bfd_get_filename (abbrev_section->asection->owner));
4201
4202   for (ix = 0;
4203        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4204        ++ix)
4205     {
4206       bfd *abfd;
4207       const gdb_byte *info_ptr, *end_ptr;
4208       struct dwarf2_section_info *abbrev_section;
4209
4210       dwarf2_read_section (objfile, section);
4211       info_ptr = section->buffer;
4212
4213       if (info_ptr == NULL)
4214         continue;
4215
4216       /* We can't set abfd until now because the section may be empty or
4217          not present, in which case section->asection will be NULL.  */
4218       abfd = section->asection->owner;
4219
4220       if (dwo_file)
4221         abbrev_section = &dwo_file->sections.abbrev;
4222       else
4223         abbrev_section = &dwarf2_per_objfile->abbrev;
4224
4225       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4226          because we don't need to read any dies: the signature is in the
4227          header.  */
4228
4229       end_ptr = info_ptr + section->size;
4230       while (info_ptr < end_ptr)
4231         {
4232           sect_offset offset;
4233           cu_offset type_offset_in_tu;
4234           ULONGEST signature;
4235           struct signatured_type *sig_type;
4236           struct dwo_unit *dwo_tu;
4237           void **slot;
4238           const gdb_byte *ptr = info_ptr;
4239           struct comp_unit_head header;
4240           unsigned int length;
4241
4242           offset.sect_off = ptr - section->buffer;
4243
4244           /* We need to read the type's signature in order to build the hash
4245              table, but we don't need anything else just yet.  */
4246
4247           ptr = read_and_check_type_unit_head (&header, section,
4248                                                abbrev_section, ptr,
4249                                                &signature, &type_offset_in_tu);
4250
4251           length = get_cu_length (&header);
4252
4253           /* Skip dummy type units.  */
4254           if (ptr >= info_ptr + length
4255               || peek_abbrev_code (abfd, ptr) == 0)
4256             {
4257               info_ptr += length;
4258               continue;
4259             }
4260
4261           if (types_htab == NULL)
4262             {
4263               if (dwo_file)
4264                 types_htab = allocate_dwo_unit_table (objfile);
4265               else
4266                 types_htab = allocate_signatured_type_table (objfile);
4267             }
4268
4269           if (dwo_file)
4270             {
4271               sig_type = NULL;
4272               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4273                                        struct dwo_unit);
4274               dwo_tu->dwo_file = dwo_file;
4275               dwo_tu->signature = signature;
4276               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4277               dwo_tu->section = section;
4278               dwo_tu->offset = offset;
4279               dwo_tu->length = length;
4280             }
4281           else
4282             {
4283               /* N.B.: type_offset is not usable if this type uses a DWO file.
4284                  The real type_offset is in the DWO file.  */
4285               dwo_tu = NULL;
4286               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4287                                          struct signatured_type);
4288               sig_type->signature = signature;
4289               sig_type->type_offset_in_tu = type_offset_in_tu;
4290               sig_type->per_cu.objfile = objfile;
4291               sig_type->per_cu.is_debug_types = 1;
4292               sig_type->per_cu.section = section;
4293               sig_type->per_cu.offset = offset;
4294               sig_type->per_cu.length = length;
4295             }
4296
4297           slot = htab_find_slot (types_htab,
4298                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4299                                  INSERT);
4300           gdb_assert (slot != NULL);
4301           if (*slot != NULL)
4302             {
4303               sect_offset dup_offset;
4304
4305               if (dwo_file)
4306                 {
4307                   const struct dwo_unit *dup_tu = *slot;
4308
4309                   dup_offset = dup_tu->offset;
4310                 }
4311               else
4312                 {
4313                   const struct signatured_type *dup_tu = *slot;
4314
4315                   dup_offset = dup_tu->per_cu.offset;
4316                 }
4317
4318               complaint (&symfile_complaints,
4319                          _("debug type entry at offset 0x%x is duplicate to"
4320                            " the entry at offset 0x%x, signature %s"),
4321                          offset.sect_off, dup_offset.sect_off,
4322                          hex_string (signature));
4323             }
4324           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4325
4326           if (dwarf2_read_debug)
4327             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4328                                 offset.sect_off,
4329                                 hex_string (signature));
4330
4331           info_ptr += length;
4332         }
4333     }
4334
4335   return types_htab;
4336 }
4337
4338 /* Create the hash table of all entries in the .debug_types section,
4339    and initialize all_type_units.
4340    The result is zero if there is an error (e.g. missing .debug_types section),
4341    otherwise non-zero.  */
4342
4343 static int
4344 create_all_type_units (struct objfile *objfile)
4345 {
4346   htab_t types_htab;
4347   struct signatured_type **iter;
4348
4349   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4350   if (types_htab == NULL)
4351     {
4352       dwarf2_per_objfile->signatured_types = NULL;
4353       return 0;
4354     }
4355
4356   dwarf2_per_objfile->signatured_types = types_htab;
4357
4358   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4359   dwarf2_per_objfile->all_type_units
4360     = xmalloc (dwarf2_per_objfile->n_type_units
4361                * sizeof (struct signatured_type *));
4362   iter = &dwarf2_per_objfile->all_type_units[0];
4363   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4364   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4365               == dwarf2_per_objfile->n_type_units);
4366
4367   return 1;
4368 }
4369
4370 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4371    Fill in SIG_ENTRY with DWO_ENTRY.  */
4372
4373 static void
4374 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4375                                   struct signatured_type *sig_entry,
4376                                   struct dwo_unit *dwo_entry)
4377 {
4378   /* Make sure we're not clobbering something we don't expect to.  */
4379   gdb_assert (! sig_entry->per_cu.queued);
4380   gdb_assert (sig_entry->per_cu.cu == NULL);
4381   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4382   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4383   gdb_assert (sig_entry->signature == dwo_entry->signature);
4384   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4385   gdb_assert (sig_entry->type_unit_group == NULL);
4386   gdb_assert (sig_entry->dwo_unit == NULL);
4387
4388   sig_entry->per_cu.section = dwo_entry->section;
4389   sig_entry->per_cu.offset = dwo_entry->offset;
4390   sig_entry->per_cu.length = dwo_entry->length;
4391   sig_entry->per_cu.reading_dwo_directly = 1;
4392   sig_entry->per_cu.objfile = objfile;
4393   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4394   sig_entry->dwo_unit = dwo_entry;
4395 }
4396
4397 /* Subroutine of lookup_signatured_type.
4398    If we haven't read the TU yet, create the signatured_type data structure
4399    for a TU to be read in directly from a DWO file, bypassing the stub.
4400    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4401    using .gdb_index, then when reading a CU we want to stay in the DWO file
4402    containing that CU.  Otherwise we could end up reading several other DWO
4403    files (due to comdat folding) to process the transitive closure of all the
4404    mentioned TUs, and that can be slow.  The current DWO file will have every
4405    type signature that it needs.
4406    We only do this for .gdb_index because in the psymtab case we already have
4407    to read all the DWOs to build the type unit groups.  */
4408
4409 static struct signatured_type *
4410 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4411 {
4412   struct objfile *objfile = dwarf2_per_objfile->objfile;
4413   struct dwo_file *dwo_file;
4414   struct dwo_unit find_dwo_entry, *dwo_entry;
4415   struct signatured_type find_sig_entry, *sig_entry;
4416
4417   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4418
4419   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4420      dwo_unit of the TU itself.  */
4421   dwo_file = cu->dwo_unit->dwo_file;
4422
4423   /* We only ever need to read in one copy of a signatured type.
4424      Just use the global signatured_types array.  If this is the first time
4425      we're reading this type, replace the recorded data from .gdb_index with
4426      this TU.  */
4427
4428   if (dwarf2_per_objfile->signatured_types == NULL)
4429     return NULL;
4430   find_sig_entry.signature = sig;
4431   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4432   if (sig_entry == NULL)
4433     return NULL;
4434
4435   /* We can get here with the TU already read, *or* in the process of being
4436      read.  Don't reassign it if that's the case.  Also note that if the TU is
4437      already being read, it may not have come from a DWO, the program may be
4438      a mix of Fission-compiled code and non-Fission-compiled code.  */
4439   /* Have we already tried to read this TU?  */
4440   if (sig_entry->per_cu.tu_read)
4441     return sig_entry;
4442
4443   /* Ok, this is the first time we're reading this TU.  */
4444   if (dwo_file->tus == NULL)
4445     return NULL;
4446   find_dwo_entry.signature = sig;
4447   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4448   if (dwo_entry == NULL)
4449     return NULL;
4450
4451   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4452   return sig_entry;
4453 }
4454
4455 /* Subroutine of lookup_dwp_signatured_type.
4456    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4457
4458 static struct signatured_type *
4459 add_type_unit (ULONGEST sig)
4460 {
4461   struct objfile *objfile = dwarf2_per_objfile->objfile;
4462   int n_type_units = dwarf2_per_objfile->n_type_units;
4463   struct signatured_type *sig_type;
4464   void **slot;
4465
4466   ++n_type_units;
4467   dwarf2_per_objfile->all_type_units =
4468     xrealloc (dwarf2_per_objfile->all_type_units,
4469               n_type_units * sizeof (struct signatured_type *));
4470   dwarf2_per_objfile->n_type_units = n_type_units;
4471   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4472                              struct signatured_type);
4473   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4474   sig_type->signature = sig;
4475   sig_type->per_cu.is_debug_types = 1;
4476   sig_type->per_cu.v.quick =
4477     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4478                     struct dwarf2_per_cu_quick_data);
4479   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4480                          sig_type, INSERT);
4481   gdb_assert (*slot == NULL);
4482   *slot = sig_type;
4483   /* The rest of sig_type must be filled in by the caller.  */
4484   return sig_type;
4485 }
4486
4487 /* Subroutine of lookup_signatured_type.
4488    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4489    then try the DWP file.
4490    Normally this "can't happen", but if there's a bug in signature
4491    generation and/or the DWP file is built incorrectly, it can happen.
4492    Using the type directly from the DWP file means we don't have the stub
4493    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4494    not critical.  [Eventually the stub may go away for type units anyway.]  */
4495
4496 static struct signatured_type *
4497 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4498 {
4499   struct objfile *objfile = dwarf2_per_objfile->objfile;
4500   struct dwp_file *dwp_file = get_dwp_file ();
4501   struct dwo_unit *dwo_entry;
4502   struct signatured_type find_sig_entry, *sig_entry;
4503
4504   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4505   gdb_assert (dwp_file != NULL);
4506
4507   if (dwarf2_per_objfile->signatured_types != NULL)
4508     {
4509       find_sig_entry.signature = sig;
4510       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4511                              &find_sig_entry);
4512       if (sig_entry != NULL)
4513         return sig_entry;
4514     }
4515
4516   /* This is the "shouldn't happen" case.
4517      Try the DWP file and hope for the best.  */
4518   if (dwp_file->tus == NULL)
4519     return NULL;
4520   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4521                                  sig, 1 /* is_debug_types */);
4522   if (dwo_entry == NULL)
4523     return NULL;
4524
4525   sig_entry = add_type_unit (sig);
4526   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4527
4528   /* The caller will signal a complaint if we return NULL.
4529      Here we don't return NULL but we still want to complain.  */
4530   complaint (&symfile_complaints,
4531              _("Bad type signature %s referenced by %s at 0x%x,"
4532                " coping by using copy in DWP [in module %s]"),
4533              hex_string (sig),
4534              cu->per_cu->is_debug_types ? "TU" : "CU",
4535              cu->per_cu->offset.sect_off,
4536              objfile->name);
4537
4538   return sig_entry;
4539 }
4540
4541 /* Lookup a signature based type for DW_FORM_ref_sig8.
4542    Returns NULL if signature SIG is not present in the table.
4543    It is up to the caller to complain about this.  */
4544
4545 static struct signatured_type *
4546 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4547 {
4548   if (cu->dwo_unit
4549       && dwarf2_per_objfile->using_index)
4550     {
4551       /* We're in a DWO/DWP file, and we're using .gdb_index.
4552          These cases require special processing.  */
4553       if (get_dwp_file () == NULL)
4554         return lookup_dwo_signatured_type (cu, sig);
4555       else
4556         return lookup_dwp_signatured_type (cu, sig);
4557     }
4558   else
4559     {
4560       struct signatured_type find_entry, *entry;
4561
4562       if (dwarf2_per_objfile->signatured_types == NULL)
4563         return NULL;
4564       find_entry.signature = sig;
4565       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4566       return entry;
4567     }
4568 }
4569 \f
4570 /* Low level DIE reading support.  */
4571
4572 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4573
4574 static void
4575 init_cu_die_reader (struct die_reader_specs *reader,
4576                     struct dwarf2_cu *cu,
4577                     struct dwarf2_section_info *section,
4578                     struct dwo_file *dwo_file)
4579 {
4580   gdb_assert (section->readin && section->buffer != NULL);
4581   reader->abfd = section->asection->owner;
4582   reader->cu = cu;
4583   reader->dwo_file = dwo_file;
4584   reader->die_section = section;
4585   reader->buffer = section->buffer;
4586   reader->buffer_end = section->buffer + section->size;
4587   reader->comp_dir = NULL;
4588 }
4589
4590 /* Subroutine of init_cutu_and_read_dies to simplify it.
4591    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4592    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4593    already.
4594
4595    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4596    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4597    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4598    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4599    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4600    COMP_DIR must be non-NULL.
4601    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4602    are filled in with the info of the DIE from the DWO file.
4603    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4604    provided an abbrev table to use.
4605    The result is non-zero if a valid (non-dummy) DIE was found.  */
4606
4607 static int
4608 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4609                         struct dwo_unit *dwo_unit,
4610                         int abbrev_table_provided,
4611                         struct die_info *stub_comp_unit_die,
4612                         const char *stub_comp_dir,
4613                         struct die_reader_specs *result_reader,
4614                         const gdb_byte **result_info_ptr,
4615                         struct die_info **result_comp_unit_die,
4616                         int *result_has_children)
4617 {
4618   struct objfile *objfile = dwarf2_per_objfile->objfile;
4619   struct dwarf2_cu *cu = this_cu->cu;
4620   struct dwarf2_section_info *section;
4621   bfd *abfd;
4622   const gdb_byte *begin_info_ptr, *info_ptr;
4623   const char *comp_dir_string;
4624   ULONGEST signature; /* Or dwo_id.  */
4625   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4626   int i,num_extra_attrs;
4627   struct dwarf2_section_info *dwo_abbrev_section;
4628   struct attribute *attr;
4629   struct attribute comp_dir_attr;
4630   struct die_info *comp_unit_die;
4631
4632   /* Both can't be provided.  */
4633   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4634
4635   /* These attributes aren't processed until later:
4636      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4637      However, the attribute is found in the stub which we won't have later.
4638      In order to not impose this complication on the rest of the code,
4639      we read them here and copy them to the DWO CU/TU die.  */
4640
4641   stmt_list = NULL;
4642   low_pc = NULL;
4643   high_pc = NULL;
4644   ranges = NULL;
4645   comp_dir = NULL;
4646
4647   if (stub_comp_unit_die != NULL)
4648     {
4649       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4650          DWO file.  */
4651       if (! this_cu->is_debug_types)
4652         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4653       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4654       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4655       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4656       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4657
4658       /* There should be a DW_AT_addr_base attribute here (if needed).
4659          We need the value before we can process DW_FORM_GNU_addr_index.  */
4660       cu->addr_base = 0;
4661       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4662       if (attr)
4663         cu->addr_base = DW_UNSND (attr);
4664
4665       /* There should be a DW_AT_ranges_base attribute here (if needed).
4666          We need the value before we can process DW_AT_ranges.  */
4667       cu->ranges_base = 0;
4668       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4669       if (attr)
4670         cu->ranges_base = DW_UNSND (attr);
4671     }
4672   else if (stub_comp_dir != NULL)
4673     {
4674       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4675       comp_dir = (struct attribute *)
4676         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4677       comp_dir->name = DW_AT_comp_dir;
4678       comp_dir->form = DW_FORM_string;
4679       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4680       DW_STRING (comp_dir) = stub_comp_dir;
4681     }
4682
4683   /* Set up for reading the DWO CU/TU.  */
4684   cu->dwo_unit = dwo_unit;
4685   section = dwo_unit->section;
4686   dwarf2_read_section (objfile, section);
4687   abfd = section->asection->owner;
4688   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4689   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4690   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4691
4692   if (this_cu->is_debug_types)
4693     {
4694       ULONGEST header_signature;
4695       cu_offset type_offset_in_tu;
4696       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4697
4698       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4699                                                 dwo_abbrev_section,
4700                                                 info_ptr,
4701                                                 &header_signature,
4702                                                 &type_offset_in_tu);
4703       /* This is not an assert because it can be caused by bad debug info.  */
4704       if (sig_type->signature != header_signature)
4705         {
4706           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4707                    " TU at offset 0x%x [in module %s]"),
4708                  hex_string (sig_type->signature),
4709                  hex_string (header_signature),
4710                  dwo_unit->offset.sect_off,
4711                  bfd_get_filename (abfd));
4712         }
4713       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4714       /* For DWOs coming from DWP files, we don't know the CU length
4715          nor the type's offset in the TU until now.  */
4716       dwo_unit->length = get_cu_length (&cu->header);
4717       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4718
4719       /* Establish the type offset that can be used to lookup the type.
4720          For DWO files, we don't know it until now.  */
4721       sig_type->type_offset_in_section.sect_off =
4722         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4723     }
4724   else
4725     {
4726       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4727                                                 dwo_abbrev_section,
4728                                                 info_ptr, 0);
4729       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4730       /* For DWOs coming from DWP files, we don't know the CU length
4731          until now.  */
4732       dwo_unit->length = get_cu_length (&cu->header);
4733     }
4734
4735   /* Replace the CU's original abbrev table with the DWO's.
4736      Reminder: We can't read the abbrev table until we've read the header.  */
4737   if (abbrev_table_provided)
4738     {
4739       /* Don't free the provided abbrev table, the caller of
4740          init_cutu_and_read_dies owns it.  */
4741       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4742       /* Ensure the DWO abbrev table gets freed.  */
4743       make_cleanup (dwarf2_free_abbrev_table, cu);
4744     }
4745   else
4746     {
4747       dwarf2_free_abbrev_table (cu);
4748       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4749       /* Leave any existing abbrev table cleanup as is.  */
4750     }
4751
4752   /* Read in the die, but leave space to copy over the attributes
4753      from the stub.  This has the benefit of simplifying the rest of
4754      the code - all the work to maintain the illusion of a single
4755      DW_TAG_{compile,type}_unit DIE is done here.  */
4756   num_extra_attrs = ((stmt_list != NULL)
4757                      + (low_pc != NULL)
4758                      + (high_pc != NULL)
4759                      + (ranges != NULL)
4760                      + (comp_dir != NULL));
4761   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4762                               result_has_children, num_extra_attrs);
4763
4764   /* Copy over the attributes from the stub to the DIE we just read in.  */
4765   comp_unit_die = *result_comp_unit_die;
4766   i = comp_unit_die->num_attrs;
4767   if (stmt_list != NULL)
4768     comp_unit_die->attrs[i++] = *stmt_list;
4769   if (low_pc != NULL)
4770     comp_unit_die->attrs[i++] = *low_pc;
4771   if (high_pc != NULL)
4772     comp_unit_die->attrs[i++] = *high_pc;
4773   if (ranges != NULL)
4774     comp_unit_die->attrs[i++] = *ranges;
4775   if (comp_dir != NULL)
4776     comp_unit_die->attrs[i++] = *comp_dir;
4777   comp_unit_die->num_attrs += num_extra_attrs;
4778
4779   if (dwarf2_die_debug)
4780     {
4781       fprintf_unfiltered (gdb_stdlog,
4782                           "Read die from %s@0x%x of %s:\n",
4783                           bfd_section_name (abfd, section->asection),
4784                           (unsigned) (begin_info_ptr - section->buffer),
4785                           bfd_get_filename (abfd));
4786       dump_die (comp_unit_die, dwarf2_die_debug);
4787     }
4788
4789   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4790      TUs by skipping the stub and going directly to the entry in the DWO file.
4791      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4792      to get it via circuitous means.  Blech.  */
4793   if (comp_dir != NULL)
4794     result_reader->comp_dir = DW_STRING (comp_dir);
4795
4796   /* Skip dummy compilation units.  */
4797   if (info_ptr >= begin_info_ptr + dwo_unit->length
4798       || peek_abbrev_code (abfd, info_ptr) == 0)
4799     return 0;
4800
4801   *result_info_ptr = info_ptr;
4802   return 1;
4803 }
4804
4805 /* Subroutine of init_cutu_and_read_dies to simplify it.
4806    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4807    Returns NULL if the specified DWO unit cannot be found.  */
4808
4809 static struct dwo_unit *
4810 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4811                  struct die_info *comp_unit_die)
4812 {
4813   struct dwarf2_cu *cu = this_cu->cu;
4814   struct attribute *attr;
4815   ULONGEST signature;
4816   struct dwo_unit *dwo_unit;
4817   const char *comp_dir, *dwo_name;
4818
4819   gdb_assert (cu != NULL);
4820
4821   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4822   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4823   gdb_assert (attr != NULL);
4824   dwo_name = DW_STRING (attr);
4825   comp_dir = NULL;
4826   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4827   if (attr)
4828     comp_dir = DW_STRING (attr);
4829
4830   if (this_cu->is_debug_types)
4831     {
4832       struct signatured_type *sig_type;
4833
4834       /* Since this_cu is the first member of struct signatured_type,
4835          we can go from a pointer to one to a pointer to the other.  */
4836       sig_type = (struct signatured_type *) this_cu;
4837       signature = sig_type->signature;
4838       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4839     }
4840   else
4841     {
4842       struct attribute *attr;
4843
4844       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4845       if (! attr)
4846         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4847                  " [in module %s]"),
4848                dwo_name, this_cu->objfile->name);
4849       signature = DW_UNSND (attr);
4850       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4851                                        signature);
4852     }
4853
4854   return dwo_unit;
4855 }
4856
4857 /* Subroutine of init_cutu_and_read_dies to simplify it.
4858    Read a TU directly from a DWO file, bypassing the stub.  */
4859
4860 static void
4861 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4862                            die_reader_func_ftype *die_reader_func,
4863                            void *data)
4864 {
4865   struct dwarf2_cu *cu;
4866   struct signatured_type *sig_type;
4867   struct cleanup *cleanups, *free_cu_cleanup;
4868   struct die_reader_specs reader;
4869   const gdb_byte *info_ptr;
4870   struct die_info *comp_unit_die;
4871   int has_children;
4872
4873   /* Verify we can do the following downcast, and that we have the
4874      data we need.  */
4875   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4876   sig_type = (struct signatured_type *) this_cu;
4877   gdb_assert (sig_type->dwo_unit != NULL);
4878
4879   cleanups = make_cleanup (null_cleanup, NULL);
4880
4881   gdb_assert (this_cu->cu == NULL);
4882   cu = xmalloc (sizeof (*cu));
4883   init_one_comp_unit (cu, this_cu);
4884   /* If an error occurs while loading, release our storage.  */
4885   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4886
4887   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4888                               0 /* abbrev_table_provided */,
4889                               NULL /* stub_comp_unit_die */,
4890                               sig_type->dwo_unit->dwo_file->comp_dir,
4891                               &reader, &info_ptr,
4892                               &comp_unit_die, &has_children) == 0)
4893     {
4894       /* Dummy die.  */
4895       do_cleanups (cleanups);
4896       return;
4897     }
4898
4899   /* All the "real" work is done here.  */
4900   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4901
4902   /* This duplicates some code in init_cutu_and_read_dies,
4903      but the alternative is making the latter more complex.
4904      This function is only for the special case of using DWO files directly:
4905      no point in overly complicating the general case just to handle this.  */
4906   if (keep)
4907     {
4908       /* We've successfully allocated this compilation unit.  Let our
4909          caller clean it up when finished with it.  */
4910       discard_cleanups (free_cu_cleanup);
4911
4912       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4913          So we have to manually free the abbrev table.  */
4914       dwarf2_free_abbrev_table (cu);
4915
4916       /* Link this CU into read_in_chain.  */
4917       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4918       dwarf2_per_objfile->read_in_chain = this_cu;
4919     }
4920   else
4921     do_cleanups (free_cu_cleanup);
4922
4923   do_cleanups (cleanups);
4924 }
4925
4926 /* Initialize a CU (or TU) and read its DIEs.
4927    If the CU defers to a DWO file, read the DWO file as well.
4928
4929    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4930    Otherwise the table specified in the comp unit header is read in and used.
4931    This is an optimization for when we already have the abbrev table.
4932
4933    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4934    Otherwise, a new CU is allocated with xmalloc.
4935
4936    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4937    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4938
4939    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4940    linker) then DIE_READER_FUNC will not get called.  */
4941
4942 static void
4943 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4944                          struct abbrev_table *abbrev_table,
4945                          int use_existing_cu, int keep,
4946                          die_reader_func_ftype *die_reader_func,
4947                          void *data)
4948 {
4949   struct objfile *objfile = dwarf2_per_objfile->objfile;
4950   struct dwarf2_section_info *section = this_cu->section;
4951   bfd *abfd = section->asection->owner;
4952   struct dwarf2_cu *cu;
4953   const gdb_byte *begin_info_ptr, *info_ptr;
4954   struct die_reader_specs reader;
4955   struct die_info *comp_unit_die;
4956   int has_children;
4957   struct attribute *attr;
4958   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4959   struct signatured_type *sig_type = NULL;
4960   struct dwarf2_section_info *abbrev_section;
4961   /* Non-zero if CU currently points to a DWO file and we need to
4962      reread it.  When this happens we need to reread the skeleton die
4963      before we can reread the DWO file (this only applies to CUs, not TUs).  */
4964   int rereading_dwo_cu = 0;
4965
4966   if (dwarf2_die_debug)
4967     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4968                         this_cu->is_debug_types ? "type" : "comp",
4969                         this_cu->offset.sect_off);
4970
4971   if (use_existing_cu)
4972     gdb_assert (keep);
4973
4974   /* If we're reading a TU directly from a DWO file, including a virtual DWO
4975      file (instead of going through the stub), short-circuit all of this.  */
4976   if (this_cu->reading_dwo_directly)
4977     {
4978       /* Narrow down the scope of possibilities to have to understand.  */
4979       gdb_assert (this_cu->is_debug_types);
4980       gdb_assert (abbrev_table == NULL);
4981       gdb_assert (!use_existing_cu);
4982       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
4983       return;
4984     }
4985
4986   cleanups = make_cleanup (null_cleanup, NULL);
4987
4988   /* This is cheap if the section is already read in.  */
4989   dwarf2_read_section (objfile, section);
4990
4991   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4992
4993   abbrev_section = get_abbrev_section_for_cu (this_cu);
4994
4995   if (use_existing_cu && this_cu->cu != NULL)
4996     {
4997       cu = this_cu->cu;
4998
4999       /* If this CU is from a DWO file we need to start over, we need to
5000          refetch the attributes from the skeleton CU.
5001          This could be optimized by retrieving those attributes from when we
5002          were here the first time: the previous comp_unit_die was stored in
5003          comp_unit_obstack.  But there's no data yet that we need this
5004          optimization.  */
5005       if (cu->dwo_unit != NULL)
5006         rereading_dwo_cu = 1;
5007     }
5008   else
5009     {
5010       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5011       gdb_assert (this_cu->cu == NULL);
5012
5013       cu = xmalloc (sizeof (*cu));
5014       init_one_comp_unit (cu, this_cu);
5015
5016       /* If an error occurs while loading, release our storage.  */
5017       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5018     }
5019
5020   /* Get the header.  */
5021   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5022     {
5023       /* We already have the header, there's no need to read it in again.  */
5024       info_ptr += cu->header.first_die_offset.cu_off;
5025     }
5026   else
5027     {
5028       if (this_cu->is_debug_types)
5029         {
5030           ULONGEST signature;
5031           cu_offset type_offset_in_tu;
5032
5033           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5034                                                     abbrev_section, info_ptr,
5035                                                     &signature,
5036                                                     &type_offset_in_tu);
5037
5038           /* Since per_cu is the first member of struct signatured_type,
5039              we can go from a pointer to one to a pointer to the other.  */
5040           sig_type = (struct signatured_type *) this_cu;
5041           gdb_assert (sig_type->signature == signature);
5042           gdb_assert (sig_type->type_offset_in_tu.cu_off
5043                       == type_offset_in_tu.cu_off);
5044           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5045
5046           /* LENGTH has not been set yet for type units if we're
5047              using .gdb_index.  */
5048           this_cu->length = get_cu_length (&cu->header);
5049
5050           /* Establish the type offset that can be used to lookup the type.  */
5051           sig_type->type_offset_in_section.sect_off =
5052             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5053         }
5054       else
5055         {
5056           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5057                                                     abbrev_section,
5058                                                     info_ptr, 0);
5059
5060           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5061           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5062         }
5063     }
5064
5065   /* Skip dummy compilation units.  */
5066   if (info_ptr >= begin_info_ptr + this_cu->length
5067       || peek_abbrev_code (abfd, info_ptr) == 0)
5068     {
5069       do_cleanups (cleanups);
5070       return;
5071     }
5072
5073   /* If we don't have them yet, read the abbrevs for this compilation unit.
5074      And if we need to read them now, make sure they're freed when we're
5075      done.  Note that it's important that if the CU had an abbrev table
5076      on entry we don't free it when we're done: Somewhere up the call stack
5077      it may be in use.  */
5078   if (abbrev_table != NULL)
5079     {
5080       gdb_assert (cu->abbrev_table == NULL);
5081       gdb_assert (cu->header.abbrev_offset.sect_off
5082                   == abbrev_table->offset.sect_off);
5083       cu->abbrev_table = abbrev_table;
5084     }
5085   else if (cu->abbrev_table == NULL)
5086     {
5087       dwarf2_read_abbrevs (cu, abbrev_section);
5088       make_cleanup (dwarf2_free_abbrev_table, cu);
5089     }
5090   else if (rereading_dwo_cu)
5091     {
5092       dwarf2_free_abbrev_table (cu);
5093       dwarf2_read_abbrevs (cu, abbrev_section);
5094     }
5095
5096   /* Read the top level CU/TU die.  */
5097   init_cu_die_reader (&reader, cu, section, NULL);
5098   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5099
5100   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5101      from the DWO file.
5102      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5103      DWO CU, that this test will fail (the attribute will not be present).  */
5104   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5105   if (attr)
5106     {
5107       struct dwo_unit *dwo_unit;
5108       struct die_info *dwo_comp_unit_die;
5109
5110       if (has_children)
5111         {
5112           complaint (&symfile_complaints,
5113                      _("compilation unit with DW_AT_GNU_dwo_name"
5114                        " has children (offset 0x%x) [in module %s]"),
5115                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5116         }
5117       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5118       if (dwo_unit != NULL)
5119         {
5120           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5121                                       abbrev_table != NULL,
5122                                       comp_unit_die, NULL,
5123                                       &reader, &info_ptr,
5124                                       &dwo_comp_unit_die, &has_children) == 0)
5125             {
5126               /* Dummy die.  */
5127               do_cleanups (cleanups);
5128               return;
5129             }
5130           comp_unit_die = dwo_comp_unit_die;
5131         }
5132       else
5133         {
5134           /* Yikes, we couldn't find the rest of the DIE, we only have
5135              the stub.  A complaint has already been logged.  There's
5136              not much more we can do except pass on the stub DIE to
5137              die_reader_func.  We don't want to throw an error on bad
5138              debug info.  */
5139         }
5140     }
5141
5142   /* All of the above is setup for this call.  Yikes.  */
5143   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5144
5145   /* Done, clean up.  */
5146   if (free_cu_cleanup != NULL)
5147     {
5148       if (keep)
5149         {
5150           /* We've successfully allocated this compilation unit.  Let our
5151              caller clean it up when finished with it.  */
5152           discard_cleanups (free_cu_cleanup);
5153
5154           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5155              So we have to manually free the abbrev table.  */
5156           dwarf2_free_abbrev_table (cu);
5157
5158           /* Link this CU into read_in_chain.  */
5159           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5160           dwarf2_per_objfile->read_in_chain = this_cu;
5161         }
5162       else
5163         do_cleanups (free_cu_cleanup);
5164     }
5165
5166   do_cleanups (cleanups);
5167 }
5168
5169 /* Read CU/TU THIS_CU in section SECTION,
5170    but do not follow DW_AT_GNU_dwo_name if present.
5171    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5172    to have already done the lookup to find the DWO/DWP file).
5173
5174    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5175    THIS_CU->is_debug_types, but nothing else.
5176
5177    We fill in THIS_CU->length.
5178
5179    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5180    linker) then DIE_READER_FUNC will not get called.
5181
5182    THIS_CU->cu is always freed when done.
5183    This is done in order to not leave THIS_CU->cu in a state where we have
5184    to care whether it refers to the "main" CU or the DWO CU.  */
5185
5186 static void
5187 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5188                                    struct dwarf2_section_info *abbrev_section,
5189                                    struct dwo_file *dwo_file,
5190                                    die_reader_func_ftype *die_reader_func,
5191                                    void *data)
5192 {
5193   struct objfile *objfile = dwarf2_per_objfile->objfile;
5194   struct dwarf2_section_info *section = this_cu->section;
5195   bfd *abfd = section->asection->owner;
5196   struct dwarf2_cu cu;
5197   const gdb_byte *begin_info_ptr, *info_ptr;
5198   struct die_reader_specs reader;
5199   struct cleanup *cleanups;
5200   struct die_info *comp_unit_die;
5201   int has_children;
5202
5203   if (dwarf2_die_debug)
5204     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5205                         this_cu->is_debug_types ? "type" : "comp",
5206                         this_cu->offset.sect_off);
5207
5208   gdb_assert (this_cu->cu == NULL);
5209
5210   /* This is cheap if the section is already read in.  */
5211   dwarf2_read_section (objfile, section);
5212
5213   init_one_comp_unit (&cu, this_cu);
5214
5215   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5216
5217   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5218   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5219                                             abbrev_section, info_ptr,
5220                                             this_cu->is_debug_types);
5221
5222   this_cu->length = get_cu_length (&cu.header);
5223
5224   /* Skip dummy compilation units.  */
5225   if (info_ptr >= begin_info_ptr + this_cu->length
5226       || peek_abbrev_code (abfd, info_ptr) == 0)
5227     {
5228       do_cleanups (cleanups);
5229       return;
5230     }
5231
5232   dwarf2_read_abbrevs (&cu, abbrev_section);
5233   make_cleanup (dwarf2_free_abbrev_table, &cu);
5234
5235   init_cu_die_reader (&reader, &cu, section, dwo_file);
5236   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5237
5238   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5239
5240   do_cleanups (cleanups);
5241 }
5242
5243 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5244    does not lookup the specified DWO file.
5245    This cannot be used to read DWO files.
5246
5247    THIS_CU->cu is always freed when done.
5248    This is done in order to not leave THIS_CU->cu in a state where we have
5249    to care whether it refers to the "main" CU or the DWO CU.
5250    We can revisit this if the data shows there's a performance issue.  */
5251
5252 static void
5253 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5254                                 die_reader_func_ftype *die_reader_func,
5255                                 void *data)
5256 {
5257   init_cutu_and_read_dies_no_follow (this_cu,
5258                                      get_abbrev_section_for_cu (this_cu),
5259                                      NULL,
5260                                      die_reader_func, data);
5261 }
5262 \f
5263 /* Type Unit Groups.
5264
5265    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5266    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5267    so that all types coming from the same compilation (.o file) are grouped
5268    together.  A future step could be to put the types in the same symtab as
5269    the CU the types ultimately came from.  */
5270
5271 static hashval_t
5272 hash_type_unit_group (const void *item)
5273 {
5274   const struct type_unit_group *tu_group = item;
5275
5276   return hash_stmt_list_entry (&tu_group->hash);
5277 }
5278
5279 static int
5280 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5281 {
5282   const struct type_unit_group *lhs = item_lhs;
5283   const struct type_unit_group *rhs = item_rhs;
5284
5285   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5286 }
5287
5288 /* Allocate a hash table for type unit groups.  */
5289
5290 static htab_t
5291 allocate_type_unit_groups_table (void)
5292 {
5293   return htab_create_alloc_ex (3,
5294                                hash_type_unit_group,
5295                                eq_type_unit_group,
5296                                NULL,
5297                                &dwarf2_per_objfile->objfile->objfile_obstack,
5298                                hashtab_obstack_allocate,
5299                                dummy_obstack_deallocate);
5300 }
5301
5302 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5303    partial symtabs.  We combine several TUs per psymtab to not let the size
5304    of any one psymtab grow too big.  */
5305 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5306 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5307
5308 /* Helper routine for get_type_unit_group.
5309    Create the type_unit_group object used to hold one or more TUs.  */
5310
5311 static struct type_unit_group *
5312 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5313 {
5314   struct objfile *objfile = dwarf2_per_objfile->objfile;
5315   struct dwarf2_per_cu_data *per_cu;
5316   struct type_unit_group *tu_group;
5317
5318   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5319                              struct type_unit_group);
5320   per_cu = &tu_group->per_cu;
5321   per_cu->objfile = objfile;
5322
5323   if (dwarf2_per_objfile->using_index)
5324     {
5325       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5326                                         struct dwarf2_per_cu_quick_data);
5327     }
5328   else
5329     {
5330       unsigned int line_offset = line_offset_struct.sect_off;
5331       struct partial_symtab *pst;
5332       char *name;
5333
5334       /* Give the symtab a useful name for debug purposes.  */
5335       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5336         name = xstrprintf ("<type_units_%d>",
5337                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5338       else
5339         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5340
5341       pst = create_partial_symtab (per_cu, name);
5342       pst->anonymous = 1;
5343
5344       xfree (name);
5345     }
5346
5347   tu_group->hash.dwo_unit = cu->dwo_unit;
5348   tu_group->hash.line_offset = line_offset_struct;
5349
5350   return tu_group;
5351 }
5352
5353 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5354    STMT_LIST is a DW_AT_stmt_list attribute.  */
5355
5356 static struct type_unit_group *
5357 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5358 {
5359   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5360   struct type_unit_group *tu_group;
5361   void **slot;
5362   unsigned int line_offset;
5363   struct type_unit_group type_unit_group_for_lookup;
5364
5365   if (dwarf2_per_objfile->type_unit_groups == NULL)
5366     {
5367       dwarf2_per_objfile->type_unit_groups =
5368         allocate_type_unit_groups_table ();
5369     }
5370
5371   /* Do we need to create a new group, or can we use an existing one?  */
5372
5373   if (stmt_list)
5374     {
5375       line_offset = DW_UNSND (stmt_list);
5376       ++tu_stats->nr_symtab_sharers;
5377     }
5378   else
5379     {
5380       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5381          We can do various things here like create one group per TU or
5382          spread them over multiple groups to split up the expansion work.
5383          To avoid worst case scenarios (too many groups or too large groups)
5384          we, umm, group them in bunches.  */
5385       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5386                      | (tu_stats->nr_stmt_less_type_units
5387                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5388       ++tu_stats->nr_stmt_less_type_units;
5389     }
5390
5391   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5392   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5393   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5394                          &type_unit_group_for_lookup, INSERT);
5395   if (*slot != NULL)
5396     {
5397       tu_group = *slot;
5398       gdb_assert (tu_group != NULL);
5399     }
5400   else
5401     {
5402       sect_offset line_offset_struct;
5403
5404       line_offset_struct.sect_off = line_offset;
5405       tu_group = create_type_unit_group (cu, line_offset_struct);
5406       *slot = tu_group;
5407       ++tu_stats->nr_symtabs;
5408     }
5409
5410   return tu_group;
5411 }
5412
5413 /* Struct used to sort TUs by their abbreviation table offset.  */
5414
5415 struct tu_abbrev_offset
5416 {
5417   struct signatured_type *sig_type;
5418   sect_offset abbrev_offset;
5419 };
5420
5421 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5422
5423 static int
5424 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5425 {
5426   const struct tu_abbrev_offset * const *a = ap;
5427   const struct tu_abbrev_offset * const *b = bp;
5428   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5429   unsigned int boff = (*b)->abbrev_offset.sect_off;
5430
5431   return (aoff > boff) - (aoff < boff);
5432 }
5433
5434 /* A helper function to add a type_unit_group to a table.  */
5435
5436 static int
5437 add_type_unit_group_to_table (void **slot, void *datum)
5438 {
5439   struct type_unit_group *tu_group = *slot;
5440   struct type_unit_group ***datap = datum;
5441
5442   **datap = tu_group;
5443   ++*datap;
5444
5445   return 1;
5446 }
5447
5448 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5449    each one passing FUNC,DATA.
5450
5451    The efficiency is because we sort TUs by the abbrev table they use and
5452    only read each abbrev table once.  In one program there are 200K TUs
5453    sharing 8K abbrev tables.
5454
5455    The main purpose of this function is to support building the
5456    dwarf2_per_objfile->type_unit_groups table.
5457    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5458    can collapse the search space by grouping them by stmt_list.
5459    The savings can be significant, in the same program from above the 200K TUs
5460    share 8K stmt_list tables.
5461
5462    FUNC is expected to call get_type_unit_group, which will create the
5463    struct type_unit_group if necessary and add it to
5464    dwarf2_per_objfile->type_unit_groups.  */
5465
5466 static void
5467 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5468 {
5469   struct objfile *objfile = dwarf2_per_objfile->objfile;
5470   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5471   struct cleanup *cleanups;
5472   struct abbrev_table *abbrev_table;
5473   sect_offset abbrev_offset;
5474   struct tu_abbrev_offset *sorted_by_abbrev;
5475   struct type_unit_group **iter;
5476   int i;
5477
5478   /* It's up to the caller to not call us multiple times.  */
5479   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5480
5481   if (dwarf2_per_objfile->n_type_units == 0)
5482     return;
5483
5484   /* TUs typically share abbrev tables, and there can be way more TUs than
5485      abbrev tables.  Sort by abbrev table to reduce the number of times we
5486      read each abbrev table in.
5487      Alternatives are to punt or to maintain a cache of abbrev tables.
5488      This is simpler and efficient enough for now.
5489
5490      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5491      symtab to use).  Typically TUs with the same abbrev offset have the same
5492      stmt_list value too so in practice this should work well.
5493
5494      The basic algorithm here is:
5495
5496       sort TUs by abbrev table
5497       for each TU with same abbrev table:
5498         read abbrev table if first user
5499         read TU top level DIE
5500           [IWBN if DWO skeletons had DW_AT_stmt_list]
5501         call FUNC  */
5502
5503   if (dwarf2_read_debug)
5504     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5505
5506   /* Sort in a separate table to maintain the order of all_type_units
5507      for .gdb_index: TU indices directly index all_type_units.  */
5508   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5509                               dwarf2_per_objfile->n_type_units);
5510   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5511     {
5512       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5513
5514       sorted_by_abbrev[i].sig_type = sig_type;
5515       sorted_by_abbrev[i].abbrev_offset =
5516         read_abbrev_offset (sig_type->per_cu.section,
5517                             sig_type->per_cu.offset);
5518     }
5519   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5520   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5521          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5522
5523   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5524      called any number of times, so we don't reset tu_stats here.  */
5525
5526   abbrev_offset.sect_off = ~(unsigned) 0;
5527   abbrev_table = NULL;
5528   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5529
5530   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5531     {
5532       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5533
5534       /* Switch to the next abbrev table if necessary.  */
5535       if (abbrev_table == NULL
5536           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5537         {
5538           if (abbrev_table != NULL)
5539             {
5540               abbrev_table_free (abbrev_table);
5541               /* Reset to NULL in case abbrev_table_read_table throws
5542                  an error: abbrev_table_free_cleanup will get called.  */
5543               abbrev_table = NULL;
5544             }
5545           abbrev_offset = tu->abbrev_offset;
5546           abbrev_table =
5547             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5548                                      abbrev_offset);
5549           ++tu_stats->nr_uniq_abbrev_tables;
5550         }
5551
5552       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5553                                func, data);
5554     }
5555
5556   /* type_unit_groups can be NULL if there is an error in the debug info.
5557      Just create an empty table so the rest of gdb doesn't have to watch
5558      for this error case.  */
5559   if (dwarf2_per_objfile->type_unit_groups == NULL)
5560     {
5561       dwarf2_per_objfile->type_unit_groups =
5562         allocate_type_unit_groups_table ();
5563       dwarf2_per_objfile->n_type_unit_groups = 0;
5564     }
5565
5566   /* Create a vector of pointers to primary type units to make it easy to
5567      iterate over them and CUs.  See dw2_get_primary_cu.  */
5568   dwarf2_per_objfile->n_type_unit_groups =
5569     htab_elements (dwarf2_per_objfile->type_unit_groups);
5570   dwarf2_per_objfile->all_type_unit_groups =
5571     obstack_alloc (&objfile->objfile_obstack,
5572                    dwarf2_per_objfile->n_type_unit_groups
5573                    * sizeof (struct type_unit_group *));
5574   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5575   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5576                           add_type_unit_group_to_table, &iter);
5577   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5578               == dwarf2_per_objfile->n_type_unit_groups);
5579
5580   do_cleanups (cleanups);
5581
5582   if (dwarf2_read_debug)
5583     {
5584       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5585       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5586                           dwarf2_per_objfile->n_type_units);
5587       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5588                           tu_stats->nr_uniq_abbrev_tables);
5589       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5590                           tu_stats->nr_symtabs);
5591       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5592                           tu_stats->nr_symtab_sharers);
5593       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5594                           tu_stats->nr_stmt_less_type_units);
5595     }
5596 }
5597 \f
5598 /* Partial symbol tables.  */
5599
5600 /* Create a psymtab named NAME and assign it to PER_CU.
5601
5602    The caller must fill in the following details:
5603    dirname, textlow, texthigh.  */
5604
5605 static struct partial_symtab *
5606 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5607 {
5608   struct objfile *objfile = per_cu->objfile;
5609   struct partial_symtab *pst;
5610
5611   pst = start_psymtab_common (objfile, objfile->section_offsets,
5612                               name, 0,
5613                               objfile->global_psymbols.next,
5614                               objfile->static_psymbols.next);
5615
5616   pst->psymtabs_addrmap_supported = 1;
5617
5618   /* This is the glue that links PST into GDB's symbol API.  */
5619   pst->read_symtab_private = per_cu;
5620   pst->read_symtab = dwarf2_read_symtab;
5621   per_cu->v.psymtab = pst;
5622
5623   return pst;
5624 }
5625
5626 /* die_reader_func for process_psymtab_comp_unit.  */
5627
5628 static void
5629 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5630                                   const gdb_byte *info_ptr,
5631                                   struct die_info *comp_unit_die,
5632                                   int has_children,
5633                                   void *data)
5634 {
5635   struct dwarf2_cu *cu = reader->cu;
5636   struct objfile *objfile = cu->objfile;
5637   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5638   struct attribute *attr;
5639   CORE_ADDR baseaddr;
5640   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5641   struct partial_symtab *pst;
5642   int has_pc_info;
5643   const char *filename;
5644   int *want_partial_unit_ptr = data;
5645
5646   if (comp_unit_die->tag == DW_TAG_partial_unit
5647       && (want_partial_unit_ptr == NULL
5648           || !*want_partial_unit_ptr))
5649     return;
5650
5651   gdb_assert (! per_cu->is_debug_types);
5652
5653   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5654
5655   cu->list_in_scope = &file_symbols;
5656
5657   /* Allocate a new partial symbol table structure.  */
5658   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5659   if (attr == NULL || !DW_STRING (attr))
5660     filename = "";
5661   else
5662     filename = DW_STRING (attr);
5663
5664   pst = create_partial_symtab (per_cu, filename);
5665
5666   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5667   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5668   if (attr != NULL)
5669     pst->dirname = DW_STRING (attr);
5670
5671   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5672
5673   dwarf2_find_base_address (comp_unit_die, cu);
5674
5675   /* Possibly set the default values of LOWPC and HIGHPC from
5676      `DW_AT_ranges'.  */
5677   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5678                                       &best_highpc, cu, pst);
5679   if (has_pc_info == 1 && best_lowpc < best_highpc)
5680     /* Store the contiguous range if it is not empty; it can be empty for
5681        CUs with no code.  */
5682     addrmap_set_empty (objfile->psymtabs_addrmap,
5683                        best_lowpc + baseaddr,
5684                        best_highpc + baseaddr - 1, pst);
5685
5686   /* Check if comp unit has_children.
5687      If so, read the rest of the partial symbols from this comp unit.
5688      If not, there's no more debug_info for this comp unit.  */
5689   if (has_children)
5690     {
5691       struct partial_die_info *first_die;
5692       CORE_ADDR lowpc, highpc;
5693
5694       lowpc = ((CORE_ADDR) -1);
5695       highpc = ((CORE_ADDR) 0);
5696
5697       first_die = load_partial_dies (reader, info_ptr, 1);
5698
5699       scan_partial_symbols (first_die, &lowpc, &highpc,
5700                             ! has_pc_info, cu);
5701
5702       /* If we didn't find a lowpc, set it to highpc to avoid
5703          complaints from `maint check'.  */
5704       if (lowpc == ((CORE_ADDR) -1))
5705         lowpc = highpc;
5706
5707       /* If the compilation unit didn't have an explicit address range,
5708          then use the information extracted from its child dies.  */
5709       if (! has_pc_info)
5710         {
5711           best_lowpc = lowpc;
5712           best_highpc = highpc;
5713         }
5714     }
5715   pst->textlow = best_lowpc + baseaddr;
5716   pst->texthigh = best_highpc + baseaddr;
5717
5718   pst->n_global_syms = objfile->global_psymbols.next -
5719     (objfile->global_psymbols.list + pst->globals_offset);
5720   pst->n_static_syms = objfile->static_psymbols.next -
5721     (objfile->static_psymbols.list + pst->statics_offset);
5722   sort_pst_symbols (objfile, pst);
5723
5724   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5725     {
5726       int i;
5727       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5728       struct dwarf2_per_cu_data *iter;
5729
5730       /* Fill in 'dependencies' here; we fill in 'users' in a
5731          post-pass.  */
5732       pst->number_of_dependencies = len;
5733       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5734                                          len * sizeof (struct symtab *));
5735       for (i = 0;
5736            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5737                         i, iter);
5738            ++i)
5739         pst->dependencies[i] = iter->v.psymtab;
5740
5741       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5742     }
5743
5744   /* Get the list of files included in the current compilation unit,
5745      and build a psymtab for each of them.  */
5746   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5747
5748   if (dwarf2_read_debug)
5749     {
5750       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5751
5752       fprintf_unfiltered (gdb_stdlog,
5753                           "Psymtab for %s unit @0x%x: %s - %s"
5754                           ", %d global, %d static syms\n",
5755                           per_cu->is_debug_types ? "type" : "comp",
5756                           per_cu->offset.sect_off,
5757                           paddress (gdbarch, pst->textlow),
5758                           paddress (gdbarch, pst->texthigh),
5759                           pst->n_global_syms, pst->n_static_syms);
5760     }
5761 }
5762
5763 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5764    Process compilation unit THIS_CU for a psymtab.  */
5765
5766 static void
5767 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5768                            int want_partial_unit)
5769 {
5770   /* If this compilation unit was already read in, free the
5771      cached copy in order to read it in again.  This is
5772      necessary because we skipped some symbols when we first
5773      read in the compilation unit (see load_partial_dies).
5774      This problem could be avoided, but the benefit is unclear.  */
5775   if (this_cu->cu != NULL)
5776     free_one_cached_comp_unit (this_cu);
5777
5778   gdb_assert (! this_cu->is_debug_types);
5779   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5780                            process_psymtab_comp_unit_reader,
5781                            &want_partial_unit);
5782
5783   /* Age out any secondary CUs.  */
5784   age_cached_comp_units ();
5785 }
5786
5787 /* Reader function for build_type_psymtabs.  */
5788
5789 static void
5790 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5791                             const gdb_byte *info_ptr,
5792                             struct die_info *type_unit_die,
5793                             int has_children,
5794                             void *data)
5795 {
5796   struct objfile *objfile = dwarf2_per_objfile->objfile;
5797   struct dwarf2_cu *cu = reader->cu;
5798   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5799   struct signatured_type *sig_type;
5800   struct type_unit_group *tu_group;
5801   struct attribute *attr;
5802   struct partial_die_info *first_die;
5803   CORE_ADDR lowpc, highpc;
5804   struct partial_symtab *pst;
5805
5806   gdb_assert (data == NULL);
5807   gdb_assert (per_cu->is_debug_types);
5808   sig_type = (struct signatured_type *) per_cu;
5809
5810   if (! has_children)
5811     return;
5812
5813   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5814   tu_group = get_type_unit_group (cu, attr);
5815
5816   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5817
5818   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5819   cu->list_in_scope = &file_symbols;
5820   pst = create_partial_symtab (per_cu, "");
5821   pst->anonymous = 1;
5822
5823   first_die = load_partial_dies (reader, info_ptr, 1);
5824
5825   lowpc = (CORE_ADDR) -1;
5826   highpc = (CORE_ADDR) 0;
5827   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5828
5829   pst->n_global_syms = objfile->global_psymbols.next -
5830     (objfile->global_psymbols.list + pst->globals_offset);
5831   pst->n_static_syms = objfile->static_psymbols.next -
5832     (objfile->static_psymbols.list + pst->statics_offset);
5833   sort_pst_symbols (objfile, pst);
5834 }
5835
5836 /* Traversal function for build_type_psymtabs.  */
5837
5838 static int
5839 build_type_psymtab_dependencies (void **slot, void *info)
5840 {
5841   struct objfile *objfile = dwarf2_per_objfile->objfile;
5842   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5843   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5844   struct partial_symtab *pst = per_cu->v.psymtab;
5845   int len = VEC_length (sig_type_ptr, tu_group->tus);
5846   struct signatured_type *iter;
5847   int i;
5848
5849   gdb_assert (len > 0);
5850   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5851
5852   pst->number_of_dependencies = len;
5853   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5854                                      len * sizeof (struct psymtab *));
5855   for (i = 0;
5856        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5857        ++i)
5858     {
5859       gdb_assert (iter->per_cu.is_debug_types);
5860       pst->dependencies[i] = iter->per_cu.v.psymtab;
5861       iter->type_unit_group = tu_group;
5862     }
5863
5864   VEC_free (sig_type_ptr, tu_group->tus);
5865
5866   return 1;
5867 }
5868
5869 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5870    Build partial symbol tables for the .debug_types comp-units.  */
5871
5872 static void
5873 build_type_psymtabs (struct objfile *objfile)
5874 {
5875   if (! create_all_type_units (objfile))
5876     return;
5877
5878   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5879
5880   /* Now that all TUs have been processed we can fill in the dependencies.  */
5881   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5882                           build_type_psymtab_dependencies, NULL);
5883 }
5884
5885 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5886
5887 static void
5888 psymtabs_addrmap_cleanup (void *o)
5889 {
5890   struct objfile *objfile = o;
5891
5892   objfile->psymtabs_addrmap = NULL;
5893 }
5894
5895 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5896
5897 static void
5898 set_partial_user (struct objfile *objfile)
5899 {
5900   int i;
5901
5902   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5903     {
5904       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5905       struct partial_symtab *pst = per_cu->v.psymtab;
5906       int j;
5907
5908       if (pst == NULL)
5909         continue;
5910
5911       for (j = 0; j < pst->number_of_dependencies; ++j)
5912         {
5913           /* Set the 'user' field only if it is not already set.  */
5914           if (pst->dependencies[j]->user == NULL)
5915             pst->dependencies[j]->user = pst;
5916         }
5917     }
5918 }
5919
5920 /* Build the partial symbol table by doing a quick pass through the
5921    .debug_info and .debug_abbrev sections.  */
5922
5923 static void
5924 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5925 {
5926   struct cleanup *back_to, *addrmap_cleanup;
5927   struct obstack temp_obstack;
5928   int i;
5929
5930   if (dwarf2_read_debug)
5931     {
5932       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5933                           objfile->name);
5934     }
5935
5936   dwarf2_per_objfile->reading_partial_symbols = 1;
5937
5938   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5939
5940   /* Any cached compilation units will be linked by the per-objfile
5941      read_in_chain.  Make sure to free them when we're done.  */
5942   back_to = make_cleanup (free_cached_comp_units, NULL);
5943
5944   build_type_psymtabs (objfile);
5945
5946   create_all_comp_units (objfile);
5947
5948   /* Create a temporary address map on a temporary obstack.  We later
5949      copy this to the final obstack.  */
5950   obstack_init (&temp_obstack);
5951   make_cleanup_obstack_free (&temp_obstack);
5952   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5953   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5954
5955   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5956     {
5957       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5958
5959       process_psymtab_comp_unit (per_cu, 0);
5960     }
5961
5962   set_partial_user (objfile);
5963
5964   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5965                                                     &objfile->objfile_obstack);
5966   discard_cleanups (addrmap_cleanup);
5967
5968   do_cleanups (back_to);
5969
5970   if (dwarf2_read_debug)
5971     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5972                         objfile->name);
5973 }
5974
5975 /* die_reader_func for load_partial_comp_unit.  */
5976
5977 static void
5978 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5979                                const gdb_byte *info_ptr,
5980                                struct die_info *comp_unit_die,
5981                                int has_children,
5982                                void *data)
5983 {
5984   struct dwarf2_cu *cu = reader->cu;
5985
5986   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5987
5988   /* Check if comp unit has_children.
5989      If so, read the rest of the partial symbols from this comp unit.
5990      If not, there's no more debug_info for this comp unit.  */
5991   if (has_children)
5992     load_partial_dies (reader, info_ptr, 0);
5993 }
5994
5995 /* Load the partial DIEs for a secondary CU into memory.
5996    This is also used when rereading a primary CU with load_all_dies.  */
5997
5998 static void
5999 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6000 {
6001   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6002                            load_partial_comp_unit_reader, NULL);
6003 }
6004
6005 static void
6006 read_comp_units_from_section (struct objfile *objfile,
6007                               struct dwarf2_section_info *section,
6008                               unsigned int is_dwz,
6009                               int *n_allocated,
6010                               int *n_comp_units,
6011                               struct dwarf2_per_cu_data ***all_comp_units)
6012 {
6013   const gdb_byte *info_ptr;
6014   bfd *abfd = section->asection->owner;
6015
6016   if (dwarf2_read_debug)
6017     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6018                         section->asection->name, bfd_get_filename (abfd));
6019
6020   dwarf2_read_section (objfile, section);
6021
6022   info_ptr = section->buffer;
6023
6024   while (info_ptr < section->buffer + section->size)
6025     {
6026       unsigned int length, initial_length_size;
6027       struct dwarf2_per_cu_data *this_cu;
6028       sect_offset offset;
6029
6030       offset.sect_off = info_ptr - section->buffer;
6031
6032       /* Read just enough information to find out where the next
6033          compilation unit is.  */
6034       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6035
6036       /* Save the compilation unit for later lookup.  */
6037       this_cu = obstack_alloc (&objfile->objfile_obstack,
6038                                sizeof (struct dwarf2_per_cu_data));
6039       memset (this_cu, 0, sizeof (*this_cu));
6040       this_cu->offset = offset;
6041       this_cu->length = length + initial_length_size;
6042       this_cu->is_dwz = is_dwz;
6043       this_cu->objfile = objfile;
6044       this_cu->section = section;
6045
6046       if (*n_comp_units == *n_allocated)
6047         {
6048           *n_allocated *= 2;
6049           *all_comp_units = xrealloc (*all_comp_units,
6050                                       *n_allocated
6051                                       * sizeof (struct dwarf2_per_cu_data *));
6052         }
6053       (*all_comp_units)[*n_comp_units] = this_cu;
6054       ++*n_comp_units;
6055
6056       info_ptr = info_ptr + this_cu->length;
6057     }
6058 }
6059
6060 /* Create a list of all compilation units in OBJFILE.
6061    This is only done for -readnow and building partial symtabs.  */
6062
6063 static void
6064 create_all_comp_units (struct objfile *objfile)
6065 {
6066   int n_allocated;
6067   int n_comp_units;
6068   struct dwarf2_per_cu_data **all_comp_units;
6069   struct dwz_file *dwz;
6070
6071   n_comp_units = 0;
6072   n_allocated = 10;
6073   all_comp_units = xmalloc (n_allocated
6074                             * sizeof (struct dwarf2_per_cu_data *));
6075
6076   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6077                                 &n_allocated, &n_comp_units, &all_comp_units);
6078
6079   dwz = dwarf2_get_dwz_file ();
6080   if (dwz != NULL)
6081     read_comp_units_from_section (objfile, &dwz->info, 1,
6082                                   &n_allocated, &n_comp_units,
6083                                   &all_comp_units);
6084
6085   dwarf2_per_objfile->all_comp_units
6086     = obstack_alloc (&objfile->objfile_obstack,
6087                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6088   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6089           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6090   xfree (all_comp_units);
6091   dwarf2_per_objfile->n_comp_units = n_comp_units;
6092 }
6093
6094 /* Process all loaded DIEs for compilation unit CU, starting at
6095    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6096    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6097    DW_AT_ranges).  If NEED_PC is set, then this function will set
6098    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6099    and record the covered ranges in the addrmap.  */
6100
6101 static void
6102 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6103                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6104 {
6105   struct partial_die_info *pdi;
6106
6107   /* Now, march along the PDI's, descending into ones which have
6108      interesting children but skipping the children of the other ones,
6109      until we reach the end of the compilation unit.  */
6110
6111   pdi = first_die;
6112
6113   while (pdi != NULL)
6114     {
6115       fixup_partial_die (pdi, cu);
6116
6117       /* Anonymous namespaces or modules have no name but have interesting
6118          children, so we need to look at them.  Ditto for anonymous
6119          enums.  */
6120
6121       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6122           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6123           || pdi->tag == DW_TAG_imported_unit)
6124         {
6125           switch (pdi->tag)
6126             {
6127             case DW_TAG_subprogram:
6128               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6129               break;
6130             case DW_TAG_constant:
6131             case DW_TAG_variable:
6132             case DW_TAG_typedef:
6133             case DW_TAG_union_type:
6134               if (!pdi->is_declaration)
6135                 {
6136                   add_partial_symbol (pdi, cu);
6137                 }
6138               break;
6139             case DW_TAG_class_type:
6140             case DW_TAG_interface_type:
6141             case DW_TAG_structure_type:
6142               if (!pdi->is_declaration)
6143                 {
6144                   add_partial_symbol (pdi, cu);
6145                 }
6146               break;
6147             case DW_TAG_enumeration_type:
6148               if (!pdi->is_declaration)
6149                 add_partial_enumeration (pdi, cu);
6150               break;
6151             case DW_TAG_base_type:
6152             case DW_TAG_subrange_type:
6153               /* File scope base type definitions are added to the partial
6154                  symbol table.  */
6155               add_partial_symbol (pdi, cu);
6156               break;
6157             case DW_TAG_namespace:
6158               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6159               break;
6160             case DW_TAG_module:
6161               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6162               break;
6163             case DW_TAG_imported_unit:
6164               {
6165                 struct dwarf2_per_cu_data *per_cu;
6166
6167                 /* For now we don't handle imported units in type units.  */
6168                 if (cu->per_cu->is_debug_types)
6169                   {
6170                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6171                              " supported in type units [in module %s]"),
6172                            cu->objfile->name);
6173                   }
6174
6175                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6176                                                            pdi->is_dwz,
6177                                                            cu->objfile);
6178
6179                 /* Go read the partial unit, if needed.  */
6180                 if (per_cu->v.psymtab == NULL)
6181                   process_psymtab_comp_unit (per_cu, 1);
6182
6183                 VEC_safe_push (dwarf2_per_cu_ptr,
6184                                cu->per_cu->imported_symtabs, per_cu);
6185               }
6186               break;
6187             default:
6188               break;
6189             }
6190         }
6191
6192       /* If the die has a sibling, skip to the sibling.  */
6193
6194       pdi = pdi->die_sibling;
6195     }
6196 }
6197
6198 /* Functions used to compute the fully scoped name of a partial DIE.
6199
6200    Normally, this is simple.  For C++, the parent DIE's fully scoped
6201    name is concatenated with "::" and the partial DIE's name.  For
6202    Java, the same thing occurs except that "." is used instead of "::".
6203    Enumerators are an exception; they use the scope of their parent
6204    enumeration type, i.e. the name of the enumeration type is not
6205    prepended to the enumerator.
6206
6207    There are two complexities.  One is DW_AT_specification; in this
6208    case "parent" means the parent of the target of the specification,
6209    instead of the direct parent of the DIE.  The other is compilers
6210    which do not emit DW_TAG_namespace; in this case we try to guess
6211    the fully qualified name of structure types from their members'
6212    linkage names.  This must be done using the DIE's children rather
6213    than the children of any DW_AT_specification target.  We only need
6214    to do this for structures at the top level, i.e. if the target of
6215    any DW_AT_specification (if any; otherwise the DIE itself) does not
6216    have a parent.  */
6217
6218 /* Compute the scope prefix associated with PDI's parent, in
6219    compilation unit CU.  The result will be allocated on CU's
6220    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6221    field.  NULL is returned if no prefix is necessary.  */
6222 static const char *
6223 partial_die_parent_scope (struct partial_die_info *pdi,
6224                           struct dwarf2_cu *cu)
6225 {
6226   const char *grandparent_scope;
6227   struct partial_die_info *parent, *real_pdi;
6228
6229   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6230      then this means the parent of the specification DIE.  */
6231
6232   real_pdi = pdi;
6233   while (real_pdi->has_specification)
6234     real_pdi = find_partial_die (real_pdi->spec_offset,
6235                                  real_pdi->spec_is_dwz, cu);
6236
6237   parent = real_pdi->die_parent;
6238   if (parent == NULL)
6239     return NULL;
6240
6241   if (parent->scope_set)
6242     return parent->scope;
6243
6244   fixup_partial_die (parent, cu);
6245
6246   grandparent_scope = partial_die_parent_scope (parent, cu);
6247
6248   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6249      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6250      Work around this problem here.  */
6251   if (cu->language == language_cplus
6252       && parent->tag == DW_TAG_namespace
6253       && strcmp (parent->name, "::") == 0
6254       && grandparent_scope == NULL)
6255     {
6256       parent->scope = NULL;
6257       parent->scope_set = 1;
6258       return NULL;
6259     }
6260
6261   if (pdi->tag == DW_TAG_enumerator)
6262     /* Enumerators should not get the name of the enumeration as a prefix.  */
6263     parent->scope = grandparent_scope;
6264   else if (parent->tag == DW_TAG_namespace
6265       || parent->tag == DW_TAG_module
6266       || parent->tag == DW_TAG_structure_type
6267       || parent->tag == DW_TAG_class_type
6268       || parent->tag == DW_TAG_interface_type
6269       || parent->tag == DW_TAG_union_type
6270       || parent->tag == DW_TAG_enumeration_type)
6271     {
6272       if (grandparent_scope == NULL)
6273         parent->scope = parent->name;
6274       else
6275         parent->scope = typename_concat (&cu->comp_unit_obstack,
6276                                          grandparent_scope,
6277                                          parent->name, 0, cu);
6278     }
6279   else
6280     {
6281       /* FIXME drow/2004-04-01: What should we be doing with
6282          function-local names?  For partial symbols, we should probably be
6283          ignoring them.  */
6284       complaint (&symfile_complaints,
6285                  _("unhandled containing DIE tag %d for DIE at %d"),
6286                  parent->tag, pdi->offset.sect_off);
6287       parent->scope = grandparent_scope;
6288     }
6289
6290   parent->scope_set = 1;
6291   return parent->scope;
6292 }
6293
6294 /* Return the fully scoped name associated with PDI, from compilation unit
6295    CU.  The result will be allocated with malloc.  */
6296
6297 static char *
6298 partial_die_full_name (struct partial_die_info *pdi,
6299                        struct dwarf2_cu *cu)
6300 {
6301   const char *parent_scope;
6302
6303   /* If this is a template instantiation, we can not work out the
6304      template arguments from partial DIEs.  So, unfortunately, we have
6305      to go through the full DIEs.  At least any work we do building
6306      types here will be reused if full symbols are loaded later.  */
6307   if (pdi->has_template_arguments)
6308     {
6309       fixup_partial_die (pdi, cu);
6310
6311       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6312         {
6313           struct die_info *die;
6314           struct attribute attr;
6315           struct dwarf2_cu *ref_cu = cu;
6316
6317           /* DW_FORM_ref_addr is using section offset.  */
6318           attr.name = 0;
6319           attr.form = DW_FORM_ref_addr;
6320           attr.u.unsnd = pdi->offset.sect_off;
6321           die = follow_die_ref (NULL, &attr, &ref_cu);
6322
6323           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6324         }
6325     }
6326
6327   parent_scope = partial_die_parent_scope (pdi, cu);
6328   if (parent_scope == NULL)
6329     return NULL;
6330   else
6331     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6332 }
6333
6334 static void
6335 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6336 {
6337   struct objfile *objfile = cu->objfile;
6338   CORE_ADDR addr = 0;
6339   const char *actual_name = NULL;
6340   CORE_ADDR baseaddr;
6341   char *built_actual_name;
6342
6343   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6344
6345   built_actual_name = partial_die_full_name (pdi, cu);
6346   if (built_actual_name != NULL)
6347     actual_name = built_actual_name;
6348
6349   if (actual_name == NULL)
6350     actual_name = pdi->name;
6351
6352   switch (pdi->tag)
6353     {
6354     case DW_TAG_subprogram:
6355       if (pdi->is_external || cu->language == language_ada)
6356         {
6357           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6358              of the global scope.  But in Ada, we want to be able to access
6359              nested procedures globally.  So all Ada subprograms are stored
6360              in the global scope.  */
6361           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6362              mst_text, objfile); */
6363           add_psymbol_to_list (actual_name, strlen (actual_name),
6364                                built_actual_name != NULL,
6365                                VAR_DOMAIN, LOC_BLOCK,
6366                                &objfile->global_psymbols,
6367                                0, pdi->lowpc + baseaddr,
6368                                cu->language, objfile);
6369         }
6370       else
6371         {
6372           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6373              mst_file_text, objfile); */
6374           add_psymbol_to_list (actual_name, strlen (actual_name),
6375                                built_actual_name != NULL,
6376                                VAR_DOMAIN, LOC_BLOCK,
6377                                &objfile->static_psymbols,
6378                                0, pdi->lowpc + baseaddr,
6379                                cu->language, objfile);
6380         }
6381       break;
6382     case DW_TAG_constant:
6383       {
6384         struct psymbol_allocation_list *list;
6385
6386         if (pdi->is_external)
6387           list = &objfile->global_psymbols;
6388         else
6389           list = &objfile->static_psymbols;
6390         add_psymbol_to_list (actual_name, strlen (actual_name),
6391                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6392                              list, 0, 0, cu->language, objfile);
6393       }
6394       break;
6395     case DW_TAG_variable:
6396       if (pdi->d.locdesc)
6397         addr = decode_locdesc (pdi->d.locdesc, cu);
6398
6399       if (pdi->d.locdesc
6400           && addr == 0
6401           && !dwarf2_per_objfile->has_section_at_zero)
6402         {
6403           /* A global or static variable may also have been stripped
6404              out by the linker if unused, in which case its address
6405              will be nullified; do not add such variables into partial
6406              symbol table then.  */
6407         }
6408       else if (pdi->is_external)
6409         {
6410           /* Global Variable.
6411              Don't enter into the minimal symbol tables as there is
6412              a minimal symbol table entry from the ELF symbols already.
6413              Enter into partial symbol table if it has a location
6414              descriptor or a type.
6415              If the location descriptor is missing, new_symbol will create
6416              a LOC_UNRESOLVED symbol, the address of the variable will then
6417              be determined from the minimal symbol table whenever the variable
6418              is referenced.
6419              The address for the partial symbol table entry is not
6420              used by GDB, but it comes in handy for debugging partial symbol
6421              table building.  */
6422
6423           if (pdi->d.locdesc || pdi->has_type)
6424             add_psymbol_to_list (actual_name, strlen (actual_name),
6425                                  built_actual_name != NULL,
6426                                  VAR_DOMAIN, LOC_STATIC,
6427                                  &objfile->global_psymbols,
6428                                  0, addr + baseaddr,
6429                                  cu->language, objfile);
6430         }
6431       else
6432         {
6433           /* Static Variable.  Skip symbols without location descriptors.  */
6434           if (pdi->d.locdesc == NULL)
6435             {
6436               xfree (built_actual_name);
6437               return;
6438             }
6439           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6440              mst_file_data, objfile); */
6441           add_psymbol_to_list (actual_name, strlen (actual_name),
6442                                built_actual_name != NULL,
6443                                VAR_DOMAIN, LOC_STATIC,
6444                                &objfile->static_psymbols,
6445                                0, addr + baseaddr,
6446                                cu->language, objfile);
6447         }
6448       break;
6449     case DW_TAG_typedef:
6450     case DW_TAG_base_type:
6451     case DW_TAG_subrange_type:
6452       add_psymbol_to_list (actual_name, strlen (actual_name),
6453                            built_actual_name != NULL,
6454                            VAR_DOMAIN, LOC_TYPEDEF,
6455                            &objfile->static_psymbols,
6456                            0, (CORE_ADDR) 0, cu->language, objfile);
6457       break;
6458     case DW_TAG_namespace:
6459       add_psymbol_to_list (actual_name, strlen (actual_name),
6460                            built_actual_name != NULL,
6461                            VAR_DOMAIN, LOC_TYPEDEF,
6462                            &objfile->global_psymbols,
6463                            0, (CORE_ADDR) 0, cu->language, objfile);
6464       break;
6465     case DW_TAG_class_type:
6466     case DW_TAG_interface_type:
6467     case DW_TAG_structure_type:
6468     case DW_TAG_union_type:
6469     case DW_TAG_enumeration_type:
6470       /* Skip external references.  The DWARF standard says in the section
6471          about "Structure, Union, and Class Type Entries": "An incomplete
6472          structure, union or class type is represented by a structure,
6473          union or class entry that does not have a byte size attribute
6474          and that has a DW_AT_declaration attribute."  */
6475       if (!pdi->has_byte_size && pdi->is_declaration)
6476         {
6477           xfree (built_actual_name);
6478           return;
6479         }
6480
6481       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6482          static vs. global.  */
6483       add_psymbol_to_list (actual_name, strlen (actual_name),
6484                            built_actual_name != NULL,
6485                            STRUCT_DOMAIN, LOC_TYPEDEF,
6486                            (cu->language == language_cplus
6487                             || cu->language == language_java)
6488                            ? &objfile->global_psymbols
6489                            : &objfile->static_psymbols,
6490                            0, (CORE_ADDR) 0, cu->language, objfile);
6491
6492       break;
6493     case DW_TAG_enumerator:
6494       add_psymbol_to_list (actual_name, strlen (actual_name),
6495                            built_actual_name != NULL,
6496                            VAR_DOMAIN, LOC_CONST,
6497                            (cu->language == language_cplus
6498                             || cu->language == language_java)
6499                            ? &objfile->global_psymbols
6500                            : &objfile->static_psymbols,
6501                            0, (CORE_ADDR) 0, cu->language, objfile);
6502       break;
6503     default:
6504       break;
6505     }
6506
6507   xfree (built_actual_name);
6508 }
6509
6510 /* Read a partial die corresponding to a namespace; also, add a symbol
6511    corresponding to that namespace to the symbol table.  NAMESPACE is
6512    the name of the enclosing namespace.  */
6513
6514 static void
6515 add_partial_namespace (struct partial_die_info *pdi,
6516                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6517                        int need_pc, struct dwarf2_cu *cu)
6518 {
6519   /* Add a symbol for the namespace.  */
6520
6521   add_partial_symbol (pdi, cu);
6522
6523   /* Now scan partial symbols in that namespace.  */
6524
6525   if (pdi->has_children)
6526     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6527 }
6528
6529 /* Read a partial die corresponding to a Fortran module.  */
6530
6531 static void
6532 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6533                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6534 {
6535   /* Now scan partial symbols in that module.  */
6536
6537   if (pdi->has_children)
6538     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6539 }
6540
6541 /* Read a partial die corresponding to a subprogram and create a partial
6542    symbol for that subprogram.  When the CU language allows it, this
6543    routine also defines a partial symbol for each nested subprogram
6544    that this subprogram contains.
6545
6546    DIE my also be a lexical block, in which case we simply search
6547    recursively for suprograms defined inside that lexical block.
6548    Again, this is only performed when the CU language allows this
6549    type of definitions.  */
6550
6551 static void
6552 add_partial_subprogram (struct partial_die_info *pdi,
6553                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6554                         int need_pc, struct dwarf2_cu *cu)
6555 {
6556   if (pdi->tag == DW_TAG_subprogram)
6557     {
6558       if (pdi->has_pc_info)
6559         {
6560           if (pdi->lowpc < *lowpc)
6561             *lowpc = pdi->lowpc;
6562           if (pdi->highpc > *highpc)
6563             *highpc = pdi->highpc;
6564           if (need_pc)
6565             {
6566               CORE_ADDR baseaddr;
6567               struct objfile *objfile = cu->objfile;
6568
6569               baseaddr = ANOFFSET (objfile->section_offsets,
6570                                    SECT_OFF_TEXT (objfile));
6571               addrmap_set_empty (objfile->psymtabs_addrmap,
6572                                  pdi->lowpc + baseaddr,
6573                                  pdi->highpc - 1 + baseaddr,
6574                                  cu->per_cu->v.psymtab);
6575             }
6576         }
6577
6578       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6579         {
6580           if (!pdi->is_declaration)
6581             /* Ignore subprogram DIEs that do not have a name, they are
6582                illegal.  Do not emit a complaint at this point, we will
6583                do so when we convert this psymtab into a symtab.  */
6584             if (pdi->name)
6585               add_partial_symbol (pdi, cu);
6586         }
6587     }
6588
6589   if (! pdi->has_children)
6590     return;
6591
6592   if (cu->language == language_ada)
6593     {
6594       pdi = pdi->die_child;
6595       while (pdi != NULL)
6596         {
6597           fixup_partial_die (pdi, cu);
6598           if (pdi->tag == DW_TAG_subprogram
6599               || pdi->tag == DW_TAG_lexical_block)
6600             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6601           pdi = pdi->die_sibling;
6602         }
6603     }
6604 }
6605
6606 /* Read a partial die corresponding to an enumeration type.  */
6607
6608 static void
6609 add_partial_enumeration (struct partial_die_info *enum_pdi,
6610                          struct dwarf2_cu *cu)
6611 {
6612   struct partial_die_info *pdi;
6613
6614   if (enum_pdi->name != NULL)
6615     add_partial_symbol (enum_pdi, cu);
6616
6617   pdi = enum_pdi->die_child;
6618   while (pdi)
6619     {
6620       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6621         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6622       else
6623         add_partial_symbol (pdi, cu);
6624       pdi = pdi->die_sibling;
6625     }
6626 }
6627
6628 /* Return the initial uleb128 in the die at INFO_PTR.  */
6629
6630 static unsigned int
6631 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6632 {
6633   unsigned int bytes_read;
6634
6635   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6636 }
6637
6638 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6639    Return the corresponding abbrev, or NULL if the number is zero (indicating
6640    an empty DIE).  In either case *BYTES_READ will be set to the length of
6641    the initial number.  */
6642
6643 static struct abbrev_info *
6644 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6645                  struct dwarf2_cu *cu)
6646 {
6647   bfd *abfd = cu->objfile->obfd;
6648   unsigned int abbrev_number;
6649   struct abbrev_info *abbrev;
6650
6651   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6652
6653   if (abbrev_number == 0)
6654     return NULL;
6655
6656   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6657   if (!abbrev)
6658     {
6659       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6660              abbrev_number, bfd_get_filename (abfd));
6661     }
6662
6663   return abbrev;
6664 }
6665
6666 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6667    Returns a pointer to the end of a series of DIEs, terminated by an empty
6668    DIE.  Any children of the skipped DIEs will also be skipped.  */
6669
6670 static const gdb_byte *
6671 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6672 {
6673   struct dwarf2_cu *cu = reader->cu;
6674   struct abbrev_info *abbrev;
6675   unsigned int bytes_read;
6676
6677   while (1)
6678     {
6679       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6680       if (abbrev == NULL)
6681         return info_ptr + bytes_read;
6682       else
6683         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6684     }
6685 }
6686
6687 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6688    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6689    abbrev corresponding to that skipped uleb128 should be passed in
6690    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6691    children.  */
6692
6693 static const gdb_byte *
6694 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6695               struct abbrev_info *abbrev)
6696 {
6697   unsigned int bytes_read;
6698   struct attribute attr;
6699   bfd *abfd = reader->abfd;
6700   struct dwarf2_cu *cu = reader->cu;
6701   const gdb_byte *buffer = reader->buffer;
6702   const gdb_byte *buffer_end = reader->buffer_end;
6703   const gdb_byte *start_info_ptr = info_ptr;
6704   unsigned int form, i;
6705
6706   for (i = 0; i < abbrev->num_attrs; i++)
6707     {
6708       /* The only abbrev we care about is DW_AT_sibling.  */
6709       if (abbrev->attrs[i].name == DW_AT_sibling)
6710         {
6711           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6712           if (attr.form == DW_FORM_ref_addr)
6713             complaint (&symfile_complaints,
6714                        _("ignoring absolute DW_AT_sibling"));
6715           else
6716             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6717         }
6718
6719       /* If it isn't DW_AT_sibling, skip this attribute.  */
6720       form = abbrev->attrs[i].form;
6721     skip_attribute:
6722       switch (form)
6723         {
6724         case DW_FORM_ref_addr:
6725           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6726              and later it is offset sized.  */
6727           if (cu->header.version == 2)
6728             info_ptr += cu->header.addr_size;
6729           else
6730             info_ptr += cu->header.offset_size;
6731           break;
6732         case DW_FORM_GNU_ref_alt:
6733           info_ptr += cu->header.offset_size;
6734           break;
6735         case DW_FORM_addr:
6736           info_ptr += cu->header.addr_size;
6737           break;
6738         case DW_FORM_data1:
6739         case DW_FORM_ref1:
6740         case DW_FORM_flag:
6741           info_ptr += 1;
6742           break;
6743         case DW_FORM_flag_present:
6744           break;
6745         case DW_FORM_data2:
6746         case DW_FORM_ref2:
6747           info_ptr += 2;
6748           break;
6749         case DW_FORM_data4:
6750         case DW_FORM_ref4:
6751           info_ptr += 4;
6752           break;
6753         case DW_FORM_data8:
6754         case DW_FORM_ref8:
6755         case DW_FORM_ref_sig8:
6756           info_ptr += 8;
6757           break;
6758         case DW_FORM_string:
6759           read_direct_string (abfd, info_ptr, &bytes_read);
6760           info_ptr += bytes_read;
6761           break;
6762         case DW_FORM_sec_offset:
6763         case DW_FORM_strp:
6764         case DW_FORM_GNU_strp_alt:
6765           info_ptr += cu->header.offset_size;
6766           break;
6767         case DW_FORM_exprloc:
6768         case DW_FORM_block:
6769           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6770           info_ptr += bytes_read;
6771           break;
6772         case DW_FORM_block1:
6773           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6774           break;
6775         case DW_FORM_block2:
6776           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6777           break;
6778         case DW_FORM_block4:
6779           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6780           break;
6781         case DW_FORM_sdata:
6782         case DW_FORM_udata:
6783         case DW_FORM_ref_udata:
6784         case DW_FORM_GNU_addr_index:
6785         case DW_FORM_GNU_str_index:
6786           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6787           break;
6788         case DW_FORM_indirect:
6789           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6790           info_ptr += bytes_read;
6791           /* We need to continue parsing from here, so just go back to
6792              the top.  */
6793           goto skip_attribute;
6794
6795         default:
6796           error (_("Dwarf Error: Cannot handle %s "
6797                    "in DWARF reader [in module %s]"),
6798                  dwarf_form_name (form),
6799                  bfd_get_filename (abfd));
6800         }
6801     }
6802
6803   if (abbrev->has_children)
6804     return skip_children (reader, info_ptr);
6805   else
6806     return info_ptr;
6807 }
6808
6809 /* Locate ORIG_PDI's sibling.
6810    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6811
6812 static const gdb_byte *
6813 locate_pdi_sibling (const struct die_reader_specs *reader,
6814                     struct partial_die_info *orig_pdi,
6815                     const gdb_byte *info_ptr)
6816 {
6817   /* Do we know the sibling already?  */
6818
6819   if (orig_pdi->sibling)
6820     return orig_pdi->sibling;
6821
6822   /* Are there any children to deal with?  */
6823
6824   if (!orig_pdi->has_children)
6825     return info_ptr;
6826
6827   /* Skip the children the long way.  */
6828
6829   return skip_children (reader, info_ptr);
6830 }
6831
6832 /* Expand this partial symbol table into a full symbol table.  SELF is
6833    not NULL.  */
6834
6835 static void
6836 dwarf2_read_symtab (struct partial_symtab *self,
6837                     struct objfile *objfile)
6838 {
6839   if (self->readin)
6840     {
6841       warning (_("bug: psymtab for %s is already read in."),
6842                self->filename);
6843     }
6844   else
6845     {
6846       if (info_verbose)
6847         {
6848           printf_filtered (_("Reading in symbols for %s..."),
6849                            self->filename);
6850           gdb_flush (gdb_stdout);
6851         }
6852
6853       /* Restore our global data.  */
6854       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6855
6856       /* If this psymtab is constructed from a debug-only objfile, the
6857          has_section_at_zero flag will not necessarily be correct.  We
6858          can get the correct value for this flag by looking at the data
6859          associated with the (presumably stripped) associated objfile.  */
6860       if (objfile->separate_debug_objfile_backlink)
6861         {
6862           struct dwarf2_per_objfile *dpo_backlink
6863             = objfile_data (objfile->separate_debug_objfile_backlink,
6864                             dwarf2_objfile_data_key);
6865
6866           dwarf2_per_objfile->has_section_at_zero
6867             = dpo_backlink->has_section_at_zero;
6868         }
6869
6870       dwarf2_per_objfile->reading_partial_symbols = 0;
6871
6872       psymtab_to_symtab_1 (self);
6873
6874       /* Finish up the debug error message.  */
6875       if (info_verbose)
6876         printf_filtered (_("done.\n"));
6877     }
6878
6879   process_cu_includes ();
6880 }
6881 \f
6882 /* Reading in full CUs.  */
6883
6884 /* Add PER_CU to the queue.  */
6885
6886 static void
6887 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6888                  enum language pretend_language)
6889 {
6890   struct dwarf2_queue_item *item;
6891
6892   per_cu->queued = 1;
6893   item = xmalloc (sizeof (*item));
6894   item->per_cu = per_cu;
6895   item->pretend_language = pretend_language;
6896   item->next = NULL;
6897
6898   if (dwarf2_queue == NULL)
6899     dwarf2_queue = item;
6900   else
6901     dwarf2_queue_tail->next = item;
6902
6903   dwarf2_queue_tail = item;
6904 }
6905
6906 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6907    unit and add it to our queue.
6908    The result is non-zero if PER_CU was queued, otherwise the result is zero
6909    meaning either PER_CU is already queued or it is already loaded.  */
6910
6911 static int
6912 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6913                        struct dwarf2_per_cu_data *per_cu,
6914                        enum language pretend_language)
6915 {
6916   /* We may arrive here during partial symbol reading, if we need full
6917      DIEs to process an unusual case (e.g. template arguments).  Do
6918      not queue PER_CU, just tell our caller to load its DIEs.  */
6919   if (dwarf2_per_objfile->reading_partial_symbols)
6920     {
6921       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6922         return 1;
6923       return 0;
6924     }
6925
6926   /* Mark the dependence relation so that we don't flush PER_CU
6927      too early.  */
6928   dwarf2_add_dependence (this_cu, per_cu);
6929
6930   /* If it's already on the queue, we have nothing to do.  */
6931   if (per_cu->queued)
6932     return 0;
6933
6934   /* If the compilation unit is already loaded, just mark it as
6935      used.  */
6936   if (per_cu->cu != NULL)
6937     {
6938       per_cu->cu->last_used = 0;
6939       return 0;
6940     }
6941
6942   /* Add it to the queue.  */
6943   queue_comp_unit (per_cu, pretend_language);
6944
6945   return 1;
6946 }
6947
6948 /* Process the queue.  */
6949
6950 static void
6951 process_queue (void)
6952 {
6953   struct dwarf2_queue_item *item, *next_item;
6954
6955   if (dwarf2_read_debug)
6956     {
6957       fprintf_unfiltered (gdb_stdlog,
6958                           "Expanding one or more symtabs of objfile %s ...\n",
6959                           dwarf2_per_objfile->objfile->name);
6960     }
6961
6962   /* The queue starts out with one item, but following a DIE reference
6963      may load a new CU, adding it to the end of the queue.  */
6964   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6965     {
6966       if (dwarf2_per_objfile->using_index
6967           ? !item->per_cu->v.quick->symtab
6968           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6969         {
6970           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6971           char buf[100];
6972
6973           if (per_cu->is_debug_types)
6974             {
6975               struct signatured_type *sig_type =
6976                 (struct signatured_type *) per_cu;
6977
6978               sprintf (buf, "TU %s at offset 0x%x",
6979                        hex_string (sig_type->signature), per_cu->offset.sect_off);
6980             }
6981           else
6982             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
6983
6984           if (dwarf2_read_debug)
6985             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
6986
6987           if (per_cu->is_debug_types)
6988             process_full_type_unit (per_cu, item->pretend_language);
6989           else
6990             process_full_comp_unit (per_cu, item->pretend_language);
6991
6992           if (dwarf2_read_debug)
6993             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
6994         }
6995
6996       item->per_cu->queued = 0;
6997       next_item = item->next;
6998       xfree (item);
6999     }
7000
7001   dwarf2_queue_tail = NULL;
7002
7003   if (dwarf2_read_debug)
7004     {
7005       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7006                           dwarf2_per_objfile->objfile->name);
7007     }
7008 }
7009
7010 /* Free all allocated queue entries.  This function only releases anything if
7011    an error was thrown; if the queue was processed then it would have been
7012    freed as we went along.  */
7013
7014 static void
7015 dwarf2_release_queue (void *dummy)
7016 {
7017   struct dwarf2_queue_item *item, *last;
7018
7019   item = dwarf2_queue;
7020   while (item)
7021     {
7022       /* Anything still marked queued is likely to be in an
7023          inconsistent state, so discard it.  */
7024       if (item->per_cu->queued)
7025         {
7026           if (item->per_cu->cu != NULL)
7027             free_one_cached_comp_unit (item->per_cu);
7028           item->per_cu->queued = 0;
7029         }
7030
7031       last = item;
7032       item = item->next;
7033       xfree (last);
7034     }
7035
7036   dwarf2_queue = dwarf2_queue_tail = NULL;
7037 }
7038
7039 /* Read in full symbols for PST, and anything it depends on.  */
7040
7041 static void
7042 psymtab_to_symtab_1 (struct partial_symtab *pst)
7043 {
7044   struct dwarf2_per_cu_data *per_cu;
7045   int i;
7046
7047   if (pst->readin)
7048     return;
7049
7050   for (i = 0; i < pst->number_of_dependencies; i++)
7051     if (!pst->dependencies[i]->readin
7052         && pst->dependencies[i]->user == NULL)
7053       {
7054         /* Inform about additional files that need to be read in.  */
7055         if (info_verbose)
7056           {
7057             /* FIXME: i18n: Need to make this a single string.  */
7058             fputs_filtered (" ", gdb_stdout);
7059             wrap_here ("");
7060             fputs_filtered ("and ", gdb_stdout);
7061             wrap_here ("");
7062             printf_filtered ("%s...", pst->dependencies[i]->filename);
7063             wrap_here ("");     /* Flush output.  */
7064             gdb_flush (gdb_stdout);
7065           }
7066         psymtab_to_symtab_1 (pst->dependencies[i]);
7067       }
7068
7069   per_cu = pst->read_symtab_private;
7070
7071   if (per_cu == NULL)
7072     {
7073       /* It's an include file, no symbols to read for it.
7074          Everything is in the parent symtab.  */
7075       pst->readin = 1;
7076       return;
7077     }
7078
7079   dw2_do_instantiate_symtab (per_cu);
7080 }
7081
7082 /* Trivial hash function for die_info: the hash value of a DIE
7083    is its offset in .debug_info for this objfile.  */
7084
7085 static hashval_t
7086 die_hash (const void *item)
7087 {
7088   const struct die_info *die = item;
7089
7090   return die->offset.sect_off;
7091 }
7092
7093 /* Trivial comparison function for die_info structures: two DIEs
7094    are equal if they have the same offset.  */
7095
7096 static int
7097 die_eq (const void *item_lhs, const void *item_rhs)
7098 {
7099   const struct die_info *die_lhs = item_lhs;
7100   const struct die_info *die_rhs = item_rhs;
7101
7102   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7103 }
7104
7105 /* die_reader_func for load_full_comp_unit.
7106    This is identical to read_signatured_type_reader,
7107    but is kept separate for now.  */
7108
7109 static void
7110 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7111                             const gdb_byte *info_ptr,
7112                             struct die_info *comp_unit_die,
7113                             int has_children,
7114                             void *data)
7115 {
7116   struct dwarf2_cu *cu = reader->cu;
7117   enum language *language_ptr = data;
7118
7119   gdb_assert (cu->die_hash == NULL);
7120   cu->die_hash =
7121     htab_create_alloc_ex (cu->header.length / 12,
7122                           die_hash,
7123                           die_eq,
7124                           NULL,
7125                           &cu->comp_unit_obstack,
7126                           hashtab_obstack_allocate,
7127                           dummy_obstack_deallocate);
7128
7129   if (has_children)
7130     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7131                                                   &info_ptr, comp_unit_die);
7132   cu->dies = comp_unit_die;
7133   /* comp_unit_die is not stored in die_hash, no need.  */
7134
7135   /* We try not to read any attributes in this function, because not
7136      all CUs needed for references have been loaded yet, and symbol
7137      table processing isn't initialized.  But we have to set the CU language,
7138      or we won't be able to build types correctly.
7139      Similarly, if we do not read the producer, we can not apply
7140      producer-specific interpretation.  */
7141   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7142 }
7143
7144 /* Load the DIEs associated with PER_CU into memory.  */
7145
7146 static void
7147 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7148                      enum language pretend_language)
7149 {
7150   gdb_assert (! this_cu->is_debug_types);
7151
7152   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7153                            load_full_comp_unit_reader, &pretend_language);
7154 }
7155
7156 /* Add a DIE to the delayed physname list.  */
7157
7158 static void
7159 add_to_method_list (struct type *type, int fnfield_index, int index,
7160                     const char *name, struct die_info *die,
7161                     struct dwarf2_cu *cu)
7162 {
7163   struct delayed_method_info mi;
7164   mi.type = type;
7165   mi.fnfield_index = fnfield_index;
7166   mi.index = index;
7167   mi.name = name;
7168   mi.die = die;
7169   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7170 }
7171
7172 /* A cleanup for freeing the delayed method list.  */
7173
7174 static void
7175 free_delayed_list (void *ptr)
7176 {
7177   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7178   if (cu->method_list != NULL)
7179     {
7180       VEC_free (delayed_method_info, cu->method_list);
7181       cu->method_list = NULL;
7182     }
7183 }
7184
7185 /* Compute the physnames of any methods on the CU's method list.
7186
7187    The computation of method physnames is delayed in order to avoid the
7188    (bad) condition that one of the method's formal parameters is of an as yet
7189    incomplete type.  */
7190
7191 static void
7192 compute_delayed_physnames (struct dwarf2_cu *cu)
7193 {
7194   int i;
7195   struct delayed_method_info *mi;
7196   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7197     {
7198       const char *physname;
7199       struct fn_fieldlist *fn_flp
7200         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7201       physname = dwarf2_physname (mi->name, mi->die, cu);
7202       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7203     }
7204 }
7205
7206 /* Go objects should be embedded in a DW_TAG_module DIE,
7207    and it's not clear if/how imported objects will appear.
7208    To keep Go support simple until that's worked out,
7209    go back through what we've read and create something usable.
7210    We could do this while processing each DIE, and feels kinda cleaner,
7211    but that way is more invasive.
7212    This is to, for example, allow the user to type "p var" or "b main"
7213    without having to specify the package name, and allow lookups
7214    of module.object to work in contexts that use the expression
7215    parser.  */
7216
7217 static void
7218 fixup_go_packaging (struct dwarf2_cu *cu)
7219 {
7220   char *package_name = NULL;
7221   struct pending *list;
7222   int i;
7223
7224   for (list = global_symbols; list != NULL; list = list->next)
7225     {
7226       for (i = 0; i < list->nsyms; ++i)
7227         {
7228           struct symbol *sym = list->symbol[i];
7229
7230           if (SYMBOL_LANGUAGE (sym) == language_go
7231               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7232             {
7233               char *this_package_name = go_symbol_package_name (sym);
7234
7235               if (this_package_name == NULL)
7236                 continue;
7237               if (package_name == NULL)
7238                 package_name = this_package_name;
7239               else
7240                 {
7241                   if (strcmp (package_name, this_package_name) != 0)
7242                     complaint (&symfile_complaints,
7243                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7244                                (SYMBOL_SYMTAB (sym)
7245                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7246                                 : cu->objfile->name),
7247                                this_package_name, package_name);
7248                   xfree (this_package_name);
7249                 }
7250             }
7251         }
7252     }
7253
7254   if (package_name != NULL)
7255     {
7256       struct objfile *objfile = cu->objfile;
7257       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7258                                                       package_name,
7259                                                       strlen (package_name));
7260       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7261                                      saved_package_name, objfile);
7262       struct symbol *sym;
7263
7264       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7265
7266       sym = allocate_symbol (objfile);
7267       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7268       SYMBOL_SET_NAMES (sym, saved_package_name,
7269                         strlen (saved_package_name), 0, objfile);
7270       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7271          e.g., "main" finds the "main" module and not C's main().  */
7272       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7273       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7274       SYMBOL_TYPE (sym) = type;
7275
7276       add_symbol_to_list (sym, &global_symbols);
7277
7278       xfree (package_name);
7279     }
7280 }
7281
7282 /* Return the symtab for PER_CU.  This works properly regardless of
7283    whether we're using the index or psymtabs.  */
7284
7285 static struct symtab *
7286 get_symtab (struct dwarf2_per_cu_data *per_cu)
7287 {
7288   return (dwarf2_per_objfile->using_index
7289           ? per_cu->v.quick->symtab
7290           : per_cu->v.psymtab->symtab);
7291 }
7292
7293 /* A helper function for computing the list of all symbol tables
7294    included by PER_CU.  */
7295
7296 static void
7297 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7298                                 htab_t all_children, htab_t all_type_symtabs,
7299                                 struct dwarf2_per_cu_data *per_cu,
7300                                 struct symtab *immediate_parent)
7301 {
7302   void **slot;
7303   int ix;
7304   struct symtab *symtab;
7305   struct dwarf2_per_cu_data *iter;
7306
7307   slot = htab_find_slot (all_children, per_cu, INSERT);
7308   if (*slot != NULL)
7309     {
7310       /* This inclusion and its children have been processed.  */
7311       return;
7312     }
7313
7314   *slot = per_cu;
7315   /* Only add a CU if it has a symbol table.  */
7316   symtab = get_symtab (per_cu);
7317   if (symtab != NULL)
7318     {
7319       /* If this is a type unit only add its symbol table if we haven't
7320          seen it yet (type unit per_cu's can share symtabs).  */
7321       if (per_cu->is_debug_types)
7322         {
7323           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7324           if (*slot == NULL)
7325             {
7326               *slot = symtab;
7327               VEC_safe_push (symtab_ptr, *result, symtab);
7328               if (symtab->user == NULL)
7329                 symtab->user = immediate_parent;
7330             }
7331         }
7332       else
7333         {
7334           VEC_safe_push (symtab_ptr, *result, symtab);
7335           if (symtab->user == NULL)
7336             symtab->user = immediate_parent;
7337         }
7338     }
7339
7340   for (ix = 0;
7341        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7342        ++ix)
7343     {
7344       recursively_compute_inclusions (result, all_children,
7345                                       all_type_symtabs, iter, symtab);
7346     }
7347 }
7348
7349 /* Compute the symtab 'includes' fields for the symtab related to
7350    PER_CU.  */
7351
7352 static void
7353 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7354 {
7355   gdb_assert (! per_cu->is_debug_types);
7356
7357   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7358     {
7359       int ix, len;
7360       struct dwarf2_per_cu_data *per_cu_iter;
7361       struct symtab *symtab_iter;
7362       VEC (symtab_ptr) *result_symtabs = NULL;
7363       htab_t all_children, all_type_symtabs;
7364       struct symtab *symtab = get_symtab (per_cu);
7365
7366       /* If we don't have a symtab, we can just skip this case.  */
7367       if (symtab == NULL)
7368         return;
7369
7370       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7371                                         NULL, xcalloc, xfree);
7372       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7373                                             NULL, xcalloc, xfree);
7374
7375       for (ix = 0;
7376            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7377                         ix, per_cu_iter);
7378            ++ix)
7379         {
7380           recursively_compute_inclusions (&result_symtabs, all_children,
7381                                           all_type_symtabs, per_cu_iter,
7382                                           symtab);
7383         }
7384
7385       /* Now we have a transitive closure of all the included symtabs.  */
7386       len = VEC_length (symtab_ptr, result_symtabs);
7387       symtab->includes
7388         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7389                          (len + 1) * sizeof (struct symtab *));
7390       for (ix = 0;
7391            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7392            ++ix)
7393         symtab->includes[ix] = symtab_iter;
7394       symtab->includes[len] = NULL;
7395
7396       VEC_free (symtab_ptr, result_symtabs);
7397       htab_delete (all_children);
7398       htab_delete (all_type_symtabs);
7399     }
7400 }
7401
7402 /* Compute the 'includes' field for the symtabs of all the CUs we just
7403    read.  */
7404
7405 static void
7406 process_cu_includes (void)
7407 {
7408   int ix;
7409   struct dwarf2_per_cu_data *iter;
7410
7411   for (ix = 0;
7412        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7413                     ix, iter);
7414        ++ix)
7415     {
7416       if (! iter->is_debug_types)
7417         compute_symtab_includes (iter);
7418     }
7419
7420   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7421 }
7422
7423 /* Generate full symbol information for PER_CU, whose DIEs have
7424    already been loaded into memory.  */
7425
7426 static void
7427 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7428                         enum language pretend_language)
7429 {
7430   struct dwarf2_cu *cu = per_cu->cu;
7431   struct objfile *objfile = per_cu->objfile;
7432   CORE_ADDR lowpc, highpc;
7433   struct symtab *symtab;
7434   struct cleanup *back_to, *delayed_list_cleanup;
7435   CORE_ADDR baseaddr;
7436   struct block *static_block;
7437
7438   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7439
7440   buildsym_init ();
7441   back_to = make_cleanup (really_free_pendings, NULL);
7442   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7443
7444   cu->list_in_scope = &file_symbols;
7445
7446   cu->language = pretend_language;
7447   cu->language_defn = language_def (cu->language);
7448
7449   /* Do line number decoding in read_file_scope () */
7450   process_die (cu->dies, cu);
7451
7452   /* For now fudge the Go package.  */
7453   if (cu->language == language_go)
7454     fixup_go_packaging (cu);
7455
7456   /* Now that we have processed all the DIEs in the CU, all the types 
7457      should be complete, and it should now be safe to compute all of the
7458      physnames.  */
7459   compute_delayed_physnames (cu);
7460   do_cleanups (delayed_list_cleanup);
7461
7462   /* Some compilers don't define a DW_AT_high_pc attribute for the
7463      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7464      it, by scanning the DIE's below the compilation unit.  */
7465   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7466
7467   static_block
7468     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7469
7470   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7471      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7472      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7473      addrmap to help ensure it has an accurate map of pc values belonging to
7474      this comp unit.  */
7475   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7476
7477   symtab = end_symtab_from_static_block (static_block, objfile,
7478                                          SECT_OFF_TEXT (objfile), 0);
7479
7480   if (symtab != NULL)
7481     {
7482       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7483
7484       /* Set symtab language to language from DW_AT_language.  If the
7485          compilation is from a C file generated by language preprocessors, do
7486          not set the language if it was already deduced by start_subfile.  */
7487       if (!(cu->language == language_c && symtab->language != language_c))
7488         symtab->language = cu->language;
7489
7490       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7491          produce DW_AT_location with location lists but it can be possibly
7492          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7493          there were bugs in prologue debug info, fixed later in GCC-4.5
7494          by "unwind info for epilogues" patch (which is not directly related).
7495
7496          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7497          needed, it would be wrong due to missing DW_AT_producer there.
7498
7499          Still one can confuse GDB by using non-standard GCC compilation
7500          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7501          */ 
7502       if (cu->has_loclist && gcc_4_minor >= 5)
7503         symtab->locations_valid = 1;
7504
7505       if (gcc_4_minor >= 5)
7506         symtab->epilogue_unwind_valid = 1;
7507
7508       symtab->call_site_htab = cu->call_site_htab;
7509     }
7510
7511   if (dwarf2_per_objfile->using_index)
7512     per_cu->v.quick->symtab = symtab;
7513   else
7514     {
7515       struct partial_symtab *pst = per_cu->v.psymtab;
7516       pst->symtab = symtab;
7517       pst->readin = 1;
7518     }
7519
7520   /* Push it for inclusion processing later.  */
7521   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7522
7523   do_cleanups (back_to);
7524 }
7525
7526 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7527    already been loaded into memory.  */
7528
7529 static void
7530 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7531                         enum language pretend_language)
7532 {
7533   struct dwarf2_cu *cu = per_cu->cu;
7534   struct objfile *objfile = per_cu->objfile;
7535   struct symtab *symtab;
7536   struct cleanup *back_to, *delayed_list_cleanup;
7537   struct signatured_type *sig_type;
7538
7539   gdb_assert (per_cu->is_debug_types);
7540   sig_type = (struct signatured_type *) per_cu;
7541
7542   buildsym_init ();
7543   back_to = make_cleanup (really_free_pendings, NULL);
7544   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7545
7546   cu->list_in_scope = &file_symbols;
7547
7548   cu->language = pretend_language;
7549   cu->language_defn = language_def (cu->language);
7550
7551   /* The symbol tables are set up in read_type_unit_scope.  */
7552   process_die (cu->dies, cu);
7553
7554   /* For now fudge the Go package.  */
7555   if (cu->language == language_go)
7556     fixup_go_packaging (cu);
7557
7558   /* Now that we have processed all the DIEs in the CU, all the types 
7559      should be complete, and it should now be safe to compute all of the
7560      physnames.  */
7561   compute_delayed_physnames (cu);
7562   do_cleanups (delayed_list_cleanup);
7563
7564   /* TUs share symbol tables.
7565      If this is the first TU to use this symtab, complete the construction
7566      of it with end_expandable_symtab.  Otherwise, complete the addition of
7567      this TU's symbols to the existing symtab.  */
7568   if (sig_type->type_unit_group->primary_symtab == NULL)
7569     {
7570       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7571       sig_type->type_unit_group->primary_symtab = symtab;
7572
7573       if (symtab != NULL)
7574         {
7575           /* Set symtab language to language from DW_AT_language.  If the
7576              compilation is from a C file generated by language preprocessors,
7577              do not set the language if it was already deduced by
7578              start_subfile.  */
7579           if (!(cu->language == language_c && symtab->language != language_c))
7580             symtab->language = cu->language;
7581         }
7582     }
7583   else
7584     {
7585       augment_type_symtab (objfile,
7586                            sig_type->type_unit_group->primary_symtab);
7587       symtab = sig_type->type_unit_group->primary_symtab;
7588     }
7589
7590   if (dwarf2_per_objfile->using_index)
7591     per_cu->v.quick->symtab = symtab;
7592   else
7593     {
7594       struct partial_symtab *pst = per_cu->v.psymtab;
7595       pst->symtab = symtab;
7596       pst->readin = 1;
7597     }
7598
7599   do_cleanups (back_to);
7600 }
7601
7602 /* Process an imported unit DIE.  */
7603
7604 static void
7605 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7606 {
7607   struct attribute *attr;
7608
7609   /* For now we don't handle imported units in type units.  */
7610   if (cu->per_cu->is_debug_types)
7611     {
7612       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7613                " supported in type units [in module %s]"),
7614              cu->objfile->name);
7615     }
7616
7617   attr = dwarf2_attr (die, DW_AT_import, cu);
7618   if (attr != NULL)
7619     {
7620       struct dwarf2_per_cu_data *per_cu;
7621       struct symtab *imported_symtab;
7622       sect_offset offset;
7623       int is_dwz;
7624
7625       offset = dwarf2_get_ref_die_offset (attr);
7626       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7627       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7628
7629       /* Queue the unit, if needed.  */
7630       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7631         load_full_comp_unit (per_cu, cu->language);
7632
7633       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7634                      per_cu);
7635     }
7636 }
7637
7638 /* Process a die and its children.  */
7639
7640 static void
7641 process_die (struct die_info *die, struct dwarf2_cu *cu)
7642 {
7643   switch (die->tag)
7644     {
7645     case DW_TAG_padding:
7646       break;
7647     case DW_TAG_compile_unit:
7648     case DW_TAG_partial_unit:
7649       read_file_scope (die, cu);
7650       break;
7651     case DW_TAG_type_unit:
7652       read_type_unit_scope (die, cu);
7653       break;
7654     case DW_TAG_subprogram:
7655     case DW_TAG_inlined_subroutine:
7656       read_func_scope (die, cu);
7657       break;
7658     case DW_TAG_lexical_block:
7659     case DW_TAG_try_block:
7660     case DW_TAG_catch_block:
7661       read_lexical_block_scope (die, cu);
7662       break;
7663     case DW_TAG_GNU_call_site:
7664       read_call_site_scope (die, cu);
7665       break;
7666     case DW_TAG_class_type:
7667     case DW_TAG_interface_type:
7668     case DW_TAG_structure_type:
7669     case DW_TAG_union_type:
7670       process_structure_scope (die, cu);
7671       break;
7672     case DW_TAG_enumeration_type:
7673       process_enumeration_scope (die, cu);
7674       break;
7675
7676     /* These dies have a type, but processing them does not create
7677        a symbol or recurse to process the children.  Therefore we can
7678        read them on-demand through read_type_die.  */
7679     case DW_TAG_subroutine_type:
7680     case DW_TAG_set_type:
7681     case DW_TAG_array_type:
7682     case DW_TAG_pointer_type:
7683     case DW_TAG_ptr_to_member_type:
7684     case DW_TAG_reference_type:
7685     case DW_TAG_string_type:
7686       break;
7687
7688     case DW_TAG_base_type:
7689     case DW_TAG_subrange_type:
7690     case DW_TAG_typedef:
7691       /* Add a typedef symbol for the type definition, if it has a
7692          DW_AT_name.  */
7693       new_symbol (die, read_type_die (die, cu), cu);
7694       break;
7695     case DW_TAG_common_block:
7696       read_common_block (die, cu);
7697       break;
7698     case DW_TAG_common_inclusion:
7699       break;
7700     case DW_TAG_namespace:
7701       cu->processing_has_namespace_info = 1;
7702       read_namespace (die, cu);
7703       break;
7704     case DW_TAG_module:
7705       cu->processing_has_namespace_info = 1;
7706       read_module (die, cu);
7707       break;
7708     case DW_TAG_imported_declaration:
7709     case DW_TAG_imported_module:
7710       cu->processing_has_namespace_info = 1;
7711       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7712                                  || cu->language != language_fortran))
7713         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7714                    dwarf_tag_name (die->tag));
7715       read_import_statement (die, cu);
7716       break;
7717
7718     case DW_TAG_imported_unit:
7719       process_imported_unit_die (die, cu);
7720       break;
7721
7722     default:
7723       new_symbol (die, NULL, cu);
7724       break;
7725     }
7726 }
7727 \f
7728 /* DWARF name computation.  */
7729
7730 /* A helper function for dwarf2_compute_name which determines whether DIE
7731    needs to have the name of the scope prepended to the name listed in the
7732    die.  */
7733
7734 static int
7735 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7736 {
7737   struct attribute *attr;
7738
7739   switch (die->tag)
7740     {
7741     case DW_TAG_namespace:
7742     case DW_TAG_typedef:
7743     case DW_TAG_class_type:
7744     case DW_TAG_interface_type:
7745     case DW_TAG_structure_type:
7746     case DW_TAG_union_type:
7747     case DW_TAG_enumeration_type:
7748     case DW_TAG_enumerator:
7749     case DW_TAG_subprogram:
7750     case DW_TAG_member:
7751       return 1;
7752
7753     case DW_TAG_variable:
7754     case DW_TAG_constant:
7755       /* We only need to prefix "globally" visible variables.  These include
7756          any variable marked with DW_AT_external or any variable that
7757          lives in a namespace.  [Variables in anonymous namespaces
7758          require prefixing, but they are not DW_AT_external.]  */
7759
7760       if (dwarf2_attr (die, DW_AT_specification, cu))
7761         {
7762           struct dwarf2_cu *spec_cu = cu;
7763
7764           return die_needs_namespace (die_specification (die, &spec_cu),
7765                                       spec_cu);
7766         }
7767
7768       attr = dwarf2_attr (die, DW_AT_external, cu);
7769       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7770           && die->parent->tag != DW_TAG_module)
7771         return 0;
7772       /* A variable in a lexical block of some kind does not need a
7773          namespace, even though in C++ such variables may be external
7774          and have a mangled name.  */
7775       if (die->parent->tag ==  DW_TAG_lexical_block
7776           || die->parent->tag ==  DW_TAG_try_block
7777           || die->parent->tag ==  DW_TAG_catch_block
7778           || die->parent->tag == DW_TAG_subprogram)
7779         return 0;
7780       return 1;
7781
7782     default:
7783       return 0;
7784     }
7785 }
7786
7787 /* Retrieve the last character from a mem_file.  */
7788
7789 static void
7790 do_ui_file_peek_last (void *object, const char *buffer, long length)
7791 {
7792   char *last_char_p = (char *) object;
7793
7794   if (length > 0)
7795     *last_char_p = buffer[length - 1];
7796 }
7797
7798 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7799    compute the physname for the object, which include a method's:
7800    - formal parameters (C++/Java),
7801    - receiver type (Go),
7802    - return type (Java).
7803
7804    The term "physname" is a bit confusing.
7805    For C++, for example, it is the demangled name.
7806    For Go, for example, it's the mangled name.
7807
7808    For Ada, return the DIE's linkage name rather than the fully qualified
7809    name.  PHYSNAME is ignored..
7810
7811    The result is allocated on the objfile_obstack and canonicalized.  */
7812
7813 static const char *
7814 dwarf2_compute_name (const char *name,
7815                      struct die_info *die, struct dwarf2_cu *cu,
7816                      int physname)
7817 {
7818   struct objfile *objfile = cu->objfile;
7819
7820   if (name == NULL)
7821     name = dwarf2_name (die, cu);
7822
7823   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7824      compute it by typename_concat inside GDB.  */
7825   if (cu->language == language_ada
7826       || (cu->language == language_fortran && physname))
7827     {
7828       /* For Ada unit, we prefer the linkage name over the name, as
7829          the former contains the exported name, which the user expects
7830          to be able to reference.  Ideally, we want the user to be able
7831          to reference this entity using either natural or linkage name,
7832          but we haven't started looking at this enhancement yet.  */
7833       struct attribute *attr;
7834
7835       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7836       if (attr == NULL)
7837         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7838       if (attr && DW_STRING (attr))
7839         return DW_STRING (attr);
7840     }
7841
7842   /* These are the only languages we know how to qualify names in.  */
7843   if (name != NULL
7844       && (cu->language == language_cplus || cu->language == language_java
7845           || cu->language == language_fortran))
7846     {
7847       if (die_needs_namespace (die, cu))
7848         {
7849           long length;
7850           const char *prefix;
7851           struct ui_file *buf;
7852
7853           prefix = determine_prefix (die, cu);
7854           buf = mem_fileopen ();
7855           if (*prefix != '\0')
7856             {
7857               char *prefixed_name = typename_concat (NULL, prefix, name,
7858                                                      physname, cu);
7859
7860               fputs_unfiltered (prefixed_name, buf);
7861               xfree (prefixed_name);
7862             }
7863           else
7864             fputs_unfiltered (name, buf);
7865
7866           /* Template parameters may be specified in the DIE's DW_AT_name, or
7867              as children with DW_TAG_template_type_param or
7868              DW_TAG_value_type_param.  If the latter, add them to the name
7869              here.  If the name already has template parameters, then
7870              skip this step; some versions of GCC emit both, and
7871              it is more efficient to use the pre-computed name.
7872
7873              Something to keep in mind about this process: it is very
7874              unlikely, or in some cases downright impossible, to produce
7875              something that will match the mangled name of a function.
7876              If the definition of the function has the same debug info,
7877              we should be able to match up with it anyway.  But fallbacks
7878              using the minimal symbol, for instance to find a method
7879              implemented in a stripped copy of libstdc++, will not work.
7880              If we do not have debug info for the definition, we will have to
7881              match them up some other way.
7882
7883              When we do name matching there is a related problem with function
7884              templates; two instantiated function templates are allowed to
7885              differ only by their return types, which we do not add here.  */
7886
7887           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7888             {
7889               struct attribute *attr;
7890               struct die_info *child;
7891               int first = 1;
7892
7893               die->building_fullname = 1;
7894
7895               for (child = die->child; child != NULL; child = child->sibling)
7896                 {
7897                   struct type *type;
7898                   LONGEST value;
7899                   const gdb_byte *bytes;
7900                   struct dwarf2_locexpr_baton *baton;
7901                   struct value *v;
7902
7903                   if (child->tag != DW_TAG_template_type_param
7904                       && child->tag != DW_TAG_template_value_param)
7905                     continue;
7906
7907                   if (first)
7908                     {
7909                       fputs_unfiltered ("<", buf);
7910                       first = 0;
7911                     }
7912                   else
7913                     fputs_unfiltered (", ", buf);
7914
7915                   attr = dwarf2_attr (child, DW_AT_type, cu);
7916                   if (attr == NULL)
7917                     {
7918                       complaint (&symfile_complaints,
7919                                  _("template parameter missing DW_AT_type"));
7920                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7921                       continue;
7922                     }
7923                   type = die_type (child, cu);
7924
7925                   if (child->tag == DW_TAG_template_type_param)
7926                     {
7927                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7928                       continue;
7929                     }
7930
7931                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7932                   if (attr == NULL)
7933                     {
7934                       complaint (&symfile_complaints,
7935                                  _("template parameter missing "
7936                                    "DW_AT_const_value"));
7937                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7938                       continue;
7939                     }
7940
7941                   dwarf2_const_value_attr (attr, type, name,
7942                                            &cu->comp_unit_obstack, cu,
7943                                            &value, &bytes, &baton);
7944
7945                   if (TYPE_NOSIGN (type))
7946                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7947                        changed, this can use value_print instead.  */
7948                     c_printchar (value, type, buf);
7949                   else
7950                     {
7951                       struct value_print_options opts;
7952
7953                       if (baton != NULL)
7954                         v = dwarf2_evaluate_loc_desc (type, NULL,
7955                                                       baton->data,
7956                                                       baton->size,
7957                                                       baton->per_cu);
7958                       else if (bytes != NULL)
7959                         {
7960                           v = allocate_value (type);
7961                           memcpy (value_contents_writeable (v), bytes,
7962                                   TYPE_LENGTH (type));
7963                         }
7964                       else
7965                         v = value_from_longest (type, value);
7966
7967                       /* Specify decimal so that we do not depend on
7968                          the radix.  */
7969                       get_formatted_print_options (&opts, 'd');
7970                       opts.raw = 1;
7971                       value_print (v, buf, &opts);
7972                       release_value (v);
7973                       value_free (v);
7974                     }
7975                 }
7976
7977               die->building_fullname = 0;
7978
7979               if (!first)
7980                 {
7981                   /* Close the argument list, with a space if necessary
7982                      (nested templates).  */
7983                   char last_char = '\0';
7984                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7985                   if (last_char == '>')
7986                     fputs_unfiltered (" >", buf);
7987                   else
7988                     fputs_unfiltered (">", buf);
7989                 }
7990             }
7991
7992           /* For Java and C++ methods, append formal parameter type
7993              information, if PHYSNAME.  */
7994
7995           if (physname && die->tag == DW_TAG_subprogram
7996               && (cu->language == language_cplus
7997                   || cu->language == language_java))
7998             {
7999               struct type *type = read_type_die (die, cu);
8000
8001               c_type_print_args (type, buf, 1, cu->language,
8002                                  &type_print_raw_options);
8003
8004               if (cu->language == language_java)
8005                 {
8006                   /* For java, we must append the return type to method
8007                      names.  */
8008                   if (die->tag == DW_TAG_subprogram)
8009                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8010                                      0, 0, &type_print_raw_options);
8011                 }
8012               else if (cu->language == language_cplus)
8013                 {
8014                   /* Assume that an artificial first parameter is
8015                      "this", but do not crash if it is not.  RealView
8016                      marks unnamed (and thus unused) parameters as
8017                      artificial; there is no way to differentiate
8018                      the two cases.  */
8019                   if (TYPE_NFIELDS (type) > 0
8020                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8021                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8022                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8023                                                                         0))))
8024                     fputs_unfiltered (" const", buf);
8025                 }
8026             }
8027
8028           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8029                                        &length);
8030           ui_file_delete (buf);
8031
8032           if (cu->language == language_cplus)
8033             {
8034               const char *cname
8035                 = dwarf2_canonicalize_name (name, cu,
8036                                             &objfile->objfile_obstack);
8037
8038               if (cname != NULL)
8039                 name = cname;
8040             }
8041         }
8042     }
8043
8044   return name;
8045 }
8046
8047 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8048    If scope qualifiers are appropriate they will be added.  The result
8049    will be allocated on the objfile_obstack, or NULL if the DIE does
8050    not have a name.  NAME may either be from a previous call to
8051    dwarf2_name or NULL.
8052
8053    The output string will be canonicalized (if C++/Java).  */
8054
8055 static const char *
8056 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8057 {
8058   return dwarf2_compute_name (name, die, cu, 0);
8059 }
8060
8061 /* Construct a physname for the given DIE in CU.  NAME may either be
8062    from a previous call to dwarf2_name or NULL.  The result will be
8063    allocated on the objfile_objstack or NULL if the DIE does not have a
8064    name.
8065
8066    The output string will be canonicalized (if C++/Java).  */
8067
8068 static const char *
8069 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8070 {
8071   struct objfile *objfile = cu->objfile;
8072   struct attribute *attr;
8073   const char *retval, *mangled = NULL, *canon = NULL;
8074   struct cleanup *back_to;
8075   int need_copy = 1;
8076
8077   /* In this case dwarf2_compute_name is just a shortcut not building anything
8078      on its own.  */
8079   if (!die_needs_namespace (die, cu))
8080     return dwarf2_compute_name (name, die, cu, 1);
8081
8082   back_to = make_cleanup (null_cleanup, NULL);
8083
8084   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8085   if (!attr)
8086     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8087
8088   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8089      has computed.  */
8090   if (attr && DW_STRING (attr))
8091     {
8092       char *demangled;
8093
8094       mangled = DW_STRING (attr);
8095
8096       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8097          type.  It is easier for GDB users to search for such functions as
8098          `name(params)' than `long name(params)'.  In such case the minimal
8099          symbol names do not match the full symbol names but for template
8100          functions there is never a need to look up their definition from their
8101          declaration so the only disadvantage remains the minimal symbol
8102          variant `long name(params)' does not have the proper inferior type.
8103          */
8104
8105       if (cu->language == language_go)
8106         {
8107           /* This is a lie, but we already lie to the caller new_symbol_full.
8108              new_symbol_full assumes we return the mangled name.
8109              This just undoes that lie until things are cleaned up.  */
8110           demangled = NULL;
8111         }
8112       else
8113         {
8114           demangled = gdb_demangle (mangled,
8115                                     (DMGL_PARAMS | DMGL_ANSI
8116                                      | (cu->language == language_java
8117                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8118                                         : DMGL_RET_DROP)));
8119         }
8120       if (demangled)
8121         {
8122           make_cleanup (xfree, demangled);
8123           canon = demangled;
8124         }
8125       else
8126         {
8127           canon = mangled;
8128           need_copy = 0;
8129         }
8130     }
8131
8132   if (canon == NULL || check_physname)
8133     {
8134       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8135
8136       if (canon != NULL && strcmp (physname, canon) != 0)
8137         {
8138           /* It may not mean a bug in GDB.  The compiler could also
8139              compute DW_AT_linkage_name incorrectly.  But in such case
8140              GDB would need to be bug-to-bug compatible.  */
8141
8142           complaint (&symfile_complaints,
8143                      _("Computed physname <%s> does not match demangled <%s> "
8144                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8145                      physname, canon, mangled, die->offset.sect_off, objfile->name);
8146
8147           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8148              is available here - over computed PHYSNAME.  It is safer
8149              against both buggy GDB and buggy compilers.  */
8150
8151           retval = canon;
8152         }
8153       else
8154         {
8155           retval = physname;
8156           need_copy = 0;
8157         }
8158     }
8159   else
8160     retval = canon;
8161
8162   if (need_copy)
8163     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8164
8165   do_cleanups (back_to);
8166   return retval;
8167 }
8168
8169 /* Read the import statement specified by the given die and record it.  */
8170
8171 static void
8172 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8173 {
8174   struct objfile *objfile = cu->objfile;
8175   struct attribute *import_attr;
8176   struct die_info *imported_die, *child_die;
8177   struct dwarf2_cu *imported_cu;
8178   const char *imported_name;
8179   const char *imported_name_prefix;
8180   const char *canonical_name;
8181   const char *import_alias;
8182   const char *imported_declaration = NULL;
8183   const char *import_prefix;
8184   VEC (const_char_ptr) *excludes = NULL;
8185   struct cleanup *cleanups;
8186
8187   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8188   if (import_attr == NULL)
8189     {
8190       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8191                  dwarf_tag_name (die->tag));
8192       return;
8193     }
8194
8195   imported_cu = cu;
8196   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8197   imported_name = dwarf2_name (imported_die, imported_cu);
8198   if (imported_name == NULL)
8199     {
8200       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8201
8202         The import in the following code:
8203         namespace A
8204           {
8205             typedef int B;
8206           }
8207
8208         int main ()
8209           {
8210             using A::B;
8211             B b;
8212             return b;
8213           }
8214
8215         ...
8216          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8217             <52>   DW_AT_decl_file   : 1
8218             <53>   DW_AT_decl_line   : 6
8219             <54>   DW_AT_import      : <0x75>
8220          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8221             <59>   DW_AT_name        : B
8222             <5b>   DW_AT_decl_file   : 1
8223             <5c>   DW_AT_decl_line   : 2
8224             <5d>   DW_AT_type        : <0x6e>
8225         ...
8226          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8227             <76>   DW_AT_byte_size   : 4
8228             <77>   DW_AT_encoding    : 5        (signed)
8229
8230         imports the wrong die ( 0x75 instead of 0x58 ).
8231         This case will be ignored until the gcc bug is fixed.  */
8232       return;
8233     }
8234
8235   /* Figure out the local name after import.  */
8236   import_alias = dwarf2_name (die, cu);
8237
8238   /* Figure out where the statement is being imported to.  */
8239   import_prefix = determine_prefix (die, cu);
8240
8241   /* Figure out what the scope of the imported die is and prepend it
8242      to the name of the imported die.  */
8243   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8244
8245   if (imported_die->tag != DW_TAG_namespace
8246       && imported_die->tag != DW_TAG_module)
8247     {
8248       imported_declaration = imported_name;
8249       canonical_name = imported_name_prefix;
8250     }
8251   else if (strlen (imported_name_prefix) > 0)
8252     canonical_name = obconcat (&objfile->objfile_obstack,
8253                                imported_name_prefix, "::", imported_name,
8254                                (char *) NULL);
8255   else
8256     canonical_name = imported_name;
8257
8258   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8259
8260   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8261     for (child_die = die->child; child_die && child_die->tag;
8262          child_die = sibling_die (child_die))
8263       {
8264         /* DWARF-4: A Fortran use statement with a “rename list” may be
8265            represented by an imported module entry with an import attribute
8266            referring to the module and owned entries corresponding to those
8267            entities that are renamed as part of being imported.  */
8268
8269         if (child_die->tag != DW_TAG_imported_declaration)
8270           {
8271             complaint (&symfile_complaints,
8272                        _("child DW_TAG_imported_declaration expected "
8273                          "- DIE at 0x%x [in module %s]"),
8274                        child_die->offset.sect_off, objfile->name);
8275             continue;
8276           }
8277
8278         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8279         if (import_attr == NULL)
8280           {
8281             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8282                        dwarf_tag_name (child_die->tag));
8283             continue;
8284           }
8285
8286         imported_cu = cu;
8287         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8288                                               &imported_cu);
8289         imported_name = dwarf2_name (imported_die, imported_cu);
8290         if (imported_name == NULL)
8291           {
8292             complaint (&symfile_complaints,
8293                        _("child DW_TAG_imported_declaration has unknown "
8294                          "imported name - DIE at 0x%x [in module %s]"),
8295                        child_die->offset.sect_off, objfile->name);
8296             continue;
8297           }
8298
8299         VEC_safe_push (const_char_ptr, excludes, imported_name);
8300
8301         process_die (child_die, cu);
8302       }
8303
8304   cp_add_using_directive (import_prefix,
8305                           canonical_name,
8306                           import_alias,
8307                           imported_declaration,
8308                           excludes,
8309                           0,
8310                           &objfile->objfile_obstack);
8311
8312   do_cleanups (cleanups);
8313 }
8314
8315 /* Cleanup function for handle_DW_AT_stmt_list.  */
8316
8317 static void
8318 free_cu_line_header (void *arg)
8319 {
8320   struct dwarf2_cu *cu = arg;
8321
8322   free_line_header (cu->line_header);
8323   cu->line_header = NULL;
8324 }
8325
8326 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8327    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8328    this, it was first present in GCC release 4.3.0.  */
8329
8330 static int
8331 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8332 {
8333   if (!cu->checked_producer)
8334     check_producer (cu);
8335
8336   return cu->producer_is_gcc_lt_4_3;
8337 }
8338
8339 static void
8340 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8341                          const char **name, const char **comp_dir)
8342 {
8343   struct attribute *attr;
8344
8345   *name = NULL;
8346   *comp_dir = NULL;
8347
8348   /* Find the filename.  Do not use dwarf2_name here, since the filename
8349      is not a source language identifier.  */
8350   attr = dwarf2_attr (die, DW_AT_name, cu);
8351   if (attr)
8352     {
8353       *name = DW_STRING (attr);
8354     }
8355
8356   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8357   if (attr)
8358     *comp_dir = DW_STRING (attr);
8359   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8360            && IS_ABSOLUTE_PATH (*name))
8361     {
8362       char *d = ldirname (*name);
8363
8364       *comp_dir = d;
8365       if (d != NULL)
8366         make_cleanup (xfree, d);
8367     }
8368   if (*comp_dir != NULL)
8369     {
8370       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8371          directory, get rid of it.  */
8372       char *cp = strchr (*comp_dir, ':');
8373
8374       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8375         *comp_dir = cp + 1;
8376     }
8377
8378   if (*name == NULL)
8379     *name = "<unknown>";
8380 }
8381
8382 /* Handle DW_AT_stmt_list for a compilation unit.
8383    DIE is the DW_TAG_compile_unit die for CU.
8384    COMP_DIR is the compilation directory.
8385    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8386
8387 static void
8388 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8389                         const char *comp_dir) /* ARI: editCase function */
8390 {
8391   struct attribute *attr;
8392
8393   gdb_assert (! cu->per_cu->is_debug_types);
8394
8395   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8396   if (attr)
8397     {
8398       unsigned int line_offset = DW_UNSND (attr);
8399       struct line_header *line_header
8400         = dwarf_decode_line_header (line_offset, cu);
8401
8402       if (line_header)
8403         {
8404           cu->line_header = line_header;
8405           make_cleanup (free_cu_line_header, cu);
8406           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8407         }
8408     }
8409 }
8410
8411 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8412
8413 static void
8414 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8415 {
8416   struct objfile *objfile = dwarf2_per_objfile->objfile;
8417   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8418   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8419   CORE_ADDR highpc = ((CORE_ADDR) 0);
8420   struct attribute *attr;
8421   const char *name = NULL;
8422   const char *comp_dir = NULL;
8423   struct die_info *child_die;
8424   bfd *abfd = objfile->obfd;
8425   CORE_ADDR baseaddr;
8426
8427   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8428
8429   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8430
8431   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8432      from finish_block.  */
8433   if (lowpc == ((CORE_ADDR) -1))
8434     lowpc = highpc;
8435   lowpc += baseaddr;
8436   highpc += baseaddr;
8437
8438   find_file_and_directory (die, cu, &name, &comp_dir);
8439
8440   prepare_one_comp_unit (cu, die, cu->language);
8441
8442   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8443      standardised yet.  As a workaround for the language detection we fall
8444      back to the DW_AT_producer string.  */
8445   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8446     cu->language = language_opencl;
8447
8448   /* Similar hack for Go.  */
8449   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8450     set_cu_language (DW_LANG_Go, cu);
8451
8452   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8453
8454   /* Decode line number information if present.  We do this before
8455      processing child DIEs, so that the line header table is available
8456      for DW_AT_decl_file.  */
8457   handle_DW_AT_stmt_list (die, cu, comp_dir);
8458
8459   /* Process all dies in compilation unit.  */
8460   if (die->child != NULL)
8461     {
8462       child_die = die->child;
8463       while (child_die && child_die->tag)
8464         {
8465           process_die (child_die, cu);
8466           child_die = sibling_die (child_die);
8467         }
8468     }
8469
8470   /* Decode macro information, if present.  Dwarf 2 macro information
8471      refers to information in the line number info statement program
8472      header, so we can only read it if we've read the header
8473      successfully.  */
8474   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8475   if (attr && cu->line_header)
8476     {
8477       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8478         complaint (&symfile_complaints,
8479                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8480
8481       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8482     }
8483   else
8484     {
8485       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8486       if (attr && cu->line_header)
8487         {
8488           unsigned int macro_offset = DW_UNSND (attr);
8489
8490           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8491         }
8492     }
8493
8494   do_cleanups (back_to);
8495 }
8496
8497 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8498    Create the set of symtabs used by this TU, or if this TU is sharing
8499    symtabs with another TU and the symtabs have already been created
8500    then restore those symtabs in the line header.
8501    We don't need the pc/line-number mapping for type units.  */
8502
8503 static void
8504 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8505 {
8506   struct objfile *objfile = dwarf2_per_objfile->objfile;
8507   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8508   struct type_unit_group *tu_group;
8509   int first_time;
8510   struct line_header *lh;
8511   struct attribute *attr;
8512   unsigned int i, line_offset;
8513   struct signatured_type *sig_type;
8514
8515   gdb_assert (per_cu->is_debug_types);
8516   sig_type = (struct signatured_type *) per_cu;
8517
8518   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8519
8520   /* If we're using .gdb_index (includes -readnow) then
8521      per_cu->type_unit_group may not have been set up yet.  */
8522   if (sig_type->type_unit_group == NULL)
8523     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8524   tu_group = sig_type->type_unit_group;
8525
8526   /* If we've already processed this stmt_list there's no real need to
8527      do it again, we could fake it and just recreate the part we need
8528      (file name,index -> symtab mapping).  If data shows this optimization
8529      is useful we can do it then.  */
8530   first_time = tu_group->primary_symtab == NULL;
8531
8532   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8533      debug info.  */
8534   lh = NULL;
8535   if (attr != NULL)
8536     {
8537       line_offset = DW_UNSND (attr);
8538       lh = dwarf_decode_line_header (line_offset, cu);
8539     }
8540   if (lh == NULL)
8541     {
8542       if (first_time)
8543         dwarf2_start_symtab (cu, "", NULL, 0);
8544       else
8545         {
8546           gdb_assert (tu_group->symtabs == NULL);
8547           restart_symtab (0);
8548         }
8549       /* Note: The primary symtab will get allocated at the end.  */
8550       return;
8551     }
8552
8553   cu->line_header = lh;
8554   make_cleanup (free_cu_line_header, cu);
8555
8556   if (first_time)
8557     {
8558       dwarf2_start_symtab (cu, "", NULL, 0);
8559
8560       tu_group->num_symtabs = lh->num_file_names;
8561       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8562
8563       for (i = 0; i < lh->num_file_names; ++i)
8564         {
8565           const char *dir = NULL;
8566           struct file_entry *fe = &lh->file_names[i];
8567
8568           if (fe->dir_index)
8569             dir = lh->include_dirs[fe->dir_index - 1];
8570           dwarf2_start_subfile (fe->name, dir, NULL);
8571
8572           /* Note: We don't have to watch for the main subfile here, type units
8573              don't have DW_AT_name.  */
8574
8575           if (current_subfile->symtab == NULL)
8576             {
8577               /* NOTE: start_subfile will recognize when it's been passed
8578                  a file it has already seen.  So we can't assume there's a
8579                  simple mapping from lh->file_names to subfiles,
8580                  lh->file_names may contain dups.  */
8581               current_subfile->symtab = allocate_symtab (current_subfile->name,
8582                                                          objfile);
8583             }
8584
8585           fe->symtab = current_subfile->symtab;
8586           tu_group->symtabs[i] = fe->symtab;
8587         }
8588     }
8589   else
8590     {
8591       restart_symtab (0);
8592
8593       for (i = 0; i < lh->num_file_names; ++i)
8594         {
8595           struct file_entry *fe = &lh->file_names[i];
8596
8597           fe->symtab = tu_group->symtabs[i];
8598         }
8599     }
8600
8601   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8602      so they don't have a "real" (so to speak) symtab anyway.
8603      There is later code that will assign the main symtab to all symbols
8604      that don't have one.  We need to handle the case of a symbol with a
8605      missing symtab (DW_AT_decl_file) anyway.  */
8606 }
8607
8608 /* Process DW_TAG_type_unit.
8609    For TUs we want to skip the first top level sibling if it's not the
8610    actual type being defined by this TU.  In this case the first top
8611    level sibling is there to provide context only.  */
8612
8613 static void
8614 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8615 {
8616   struct die_info *child_die;
8617
8618   prepare_one_comp_unit (cu, die, language_minimal);
8619
8620   /* Initialize (or reinitialize) the machinery for building symtabs.
8621      We do this before processing child DIEs, so that the line header table
8622      is available for DW_AT_decl_file.  */
8623   setup_type_unit_groups (die, cu);
8624
8625   if (die->child != NULL)
8626     {
8627       child_die = die->child;
8628       while (child_die && child_die->tag)
8629         {
8630           process_die (child_die, cu);
8631           child_die = sibling_die (child_die);
8632         }
8633     }
8634 }
8635 \f
8636 /* DWO/DWP files.
8637
8638    http://gcc.gnu.org/wiki/DebugFission
8639    http://gcc.gnu.org/wiki/DebugFissionDWP
8640
8641    To simplify handling of both DWO files ("object" files with the DWARF info)
8642    and DWP files (a file with the DWOs packaged up into one file), we treat
8643    DWP files as having a collection of virtual DWO files.  */
8644
8645 static hashval_t
8646 hash_dwo_file (const void *item)
8647 {
8648   const struct dwo_file *dwo_file = item;
8649   hashval_t hash;
8650
8651   hash = htab_hash_string (dwo_file->dwo_name);
8652   if (dwo_file->comp_dir != NULL)
8653     hash += htab_hash_string (dwo_file->comp_dir);
8654   return hash;
8655 }
8656
8657 static int
8658 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8659 {
8660   const struct dwo_file *lhs = item_lhs;
8661   const struct dwo_file *rhs = item_rhs;
8662
8663   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8664     return 0;
8665   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8666     return lhs->comp_dir == rhs->comp_dir;
8667   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8668 }
8669
8670 /* Allocate a hash table for DWO files.  */
8671
8672 static htab_t
8673 allocate_dwo_file_hash_table (void)
8674 {
8675   struct objfile *objfile = dwarf2_per_objfile->objfile;
8676
8677   return htab_create_alloc_ex (41,
8678                                hash_dwo_file,
8679                                eq_dwo_file,
8680                                NULL,
8681                                &objfile->objfile_obstack,
8682                                hashtab_obstack_allocate,
8683                                dummy_obstack_deallocate);
8684 }
8685
8686 /* Lookup DWO file DWO_NAME.  */
8687
8688 static void **
8689 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8690 {
8691   struct dwo_file find_entry;
8692   void **slot;
8693
8694   if (dwarf2_per_objfile->dwo_files == NULL)
8695     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8696
8697   memset (&find_entry, 0, sizeof (find_entry));
8698   find_entry.dwo_name = dwo_name;
8699   find_entry.comp_dir = comp_dir;
8700   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8701
8702   return slot;
8703 }
8704
8705 static hashval_t
8706 hash_dwo_unit (const void *item)
8707 {
8708   const struct dwo_unit *dwo_unit = item;
8709
8710   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8711   return dwo_unit->signature;
8712 }
8713
8714 static int
8715 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8716 {
8717   const struct dwo_unit *lhs = item_lhs;
8718   const struct dwo_unit *rhs = item_rhs;
8719
8720   /* The signature is assumed to be unique within the DWO file.
8721      So while object file CU dwo_id's always have the value zero,
8722      that's OK, assuming each object file DWO file has only one CU,
8723      and that's the rule for now.  */
8724   return lhs->signature == rhs->signature;
8725 }
8726
8727 /* Allocate a hash table for DWO CUs,TUs.
8728    There is one of these tables for each of CUs,TUs for each DWO file.  */
8729
8730 static htab_t
8731 allocate_dwo_unit_table (struct objfile *objfile)
8732 {
8733   /* Start out with a pretty small number.
8734      Generally DWO files contain only one CU and maybe some TUs.  */
8735   return htab_create_alloc_ex (3,
8736                                hash_dwo_unit,
8737                                eq_dwo_unit,
8738                                NULL,
8739                                &objfile->objfile_obstack,
8740                                hashtab_obstack_allocate,
8741                                dummy_obstack_deallocate);
8742 }
8743
8744 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8745
8746 struct create_dwo_cu_data
8747 {
8748   struct dwo_file *dwo_file;
8749   struct dwo_unit dwo_unit;
8750 };
8751
8752 /* die_reader_func for create_dwo_cu.  */
8753
8754 static void
8755 create_dwo_cu_reader (const struct die_reader_specs *reader,
8756                       const gdb_byte *info_ptr,
8757                       struct die_info *comp_unit_die,
8758                       int has_children,
8759                       void *datap)
8760 {
8761   struct dwarf2_cu *cu = reader->cu;
8762   struct objfile *objfile = dwarf2_per_objfile->objfile;
8763   sect_offset offset = cu->per_cu->offset;
8764   struct dwarf2_section_info *section = cu->per_cu->section;
8765   struct create_dwo_cu_data *data = datap;
8766   struct dwo_file *dwo_file = data->dwo_file;
8767   struct dwo_unit *dwo_unit = &data->dwo_unit;
8768   struct attribute *attr;
8769
8770   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8771   if (attr == NULL)
8772     {
8773       complaint (&symfile_complaints,
8774                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8775                    " its dwo_id [in module %s]"),
8776                  offset.sect_off, dwo_file->dwo_name);
8777       return;
8778     }
8779
8780   dwo_unit->dwo_file = dwo_file;
8781   dwo_unit->signature = DW_UNSND (attr);
8782   dwo_unit->section = section;
8783   dwo_unit->offset = offset;
8784   dwo_unit->length = cu->per_cu->length;
8785
8786   if (dwarf2_read_debug)
8787     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8788                         offset.sect_off, hex_string (dwo_unit->signature));
8789 }
8790
8791 /* Create the dwo_unit for the lone CU in DWO_FILE.
8792    Note: This function processes DWO files only, not DWP files.  */
8793
8794 static struct dwo_unit *
8795 create_dwo_cu (struct dwo_file *dwo_file)
8796 {
8797   struct objfile *objfile = dwarf2_per_objfile->objfile;
8798   struct dwarf2_section_info *section = &dwo_file->sections.info;
8799   bfd *abfd;
8800   htab_t cu_htab;
8801   const gdb_byte *info_ptr, *end_ptr;
8802   struct create_dwo_cu_data create_dwo_cu_data;
8803   struct dwo_unit *dwo_unit;
8804
8805   dwarf2_read_section (objfile, section);
8806   info_ptr = section->buffer;
8807
8808   if (info_ptr == NULL)
8809     return NULL;
8810
8811   /* We can't set abfd until now because the section may be empty or
8812      not present, in which case section->asection will be NULL.  */
8813   abfd = section->asection->owner;
8814
8815   if (dwarf2_read_debug)
8816     {
8817       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8818                           bfd_section_name (abfd, section->asection),
8819                           bfd_get_filename (abfd));
8820     }
8821
8822   create_dwo_cu_data.dwo_file = dwo_file;
8823   dwo_unit = NULL;
8824
8825   end_ptr = info_ptr + section->size;
8826   while (info_ptr < end_ptr)
8827     {
8828       struct dwarf2_per_cu_data per_cu;
8829
8830       memset (&create_dwo_cu_data.dwo_unit, 0,
8831               sizeof (create_dwo_cu_data.dwo_unit));
8832       memset (&per_cu, 0, sizeof (per_cu));
8833       per_cu.objfile = objfile;
8834       per_cu.is_debug_types = 0;
8835       per_cu.offset.sect_off = info_ptr - section->buffer;
8836       per_cu.section = section;
8837
8838       init_cutu_and_read_dies_no_follow (&per_cu,
8839                                          &dwo_file->sections.abbrev,
8840                                          dwo_file,
8841                                          create_dwo_cu_reader,
8842                                          &create_dwo_cu_data);
8843
8844       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8845         {
8846           /* If we've already found one, complain.  We only support one
8847              because having more than one requires hacking the dwo_name of
8848              each to match, which is highly unlikely to happen.  */
8849           if (dwo_unit != NULL)
8850             {
8851               complaint (&symfile_complaints,
8852                          _("Multiple CUs in DWO file %s [in module %s]"),
8853                          dwo_file->dwo_name, objfile->name);
8854               break;
8855             }
8856
8857           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8858           *dwo_unit = create_dwo_cu_data.dwo_unit;
8859         }
8860
8861       info_ptr += per_cu.length;
8862     }
8863
8864   return dwo_unit;
8865 }
8866
8867 /* DWP file .debug_{cu,tu}_index section format:
8868    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8869
8870    DWP Version 1:
8871
8872    Both index sections have the same format, and serve to map a 64-bit
8873    signature to a set of section numbers.  Each section begins with a header,
8874    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8875    indexes, and a pool of 32-bit section numbers.  The index sections will be
8876    aligned at 8-byte boundaries in the file.
8877
8878    The index section header consists of:
8879
8880     V, 32 bit version number
8881     -, 32 bits unused
8882     N, 32 bit number of compilation units or type units in the index
8883     M, 32 bit number of slots in the hash table
8884
8885    Numbers are recorded using the byte order of the application binary.
8886
8887    We assume that N and M will not exceed 2^32 - 1.
8888
8889    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8890
8891    The hash table begins at offset 16 in the section, and consists of an array
8892    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8893    order of the application binary).  Unused slots in the hash table are 0.
8894    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8895
8896    The parallel table begins immediately after the hash table
8897    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8898    array of 32-bit indexes (using the byte order of the application binary),
8899    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8900    table contains a 32-bit index into the pool of section numbers.  For unused
8901    hash table slots, the corresponding entry in the parallel table will be 0.
8902
8903    Given a 64-bit compilation unit signature or a type signature S, an entry
8904    in the hash table is located as follows:
8905
8906    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8907       the low-order k bits all set to 1.
8908
8909    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8910
8911    3) If the hash table entry at index H matches the signature, use that
8912       entry.  If the hash table entry at index H is unused (all zeroes),
8913       terminate the search: the signature is not present in the table.
8914
8915    4) Let H = (H + H') modulo M. Repeat at Step 3.
8916
8917    Because M > N and H' and M are relatively prime, the search is guaranteed
8918    to stop at an unused slot or find the match.
8919
8920    The pool of section numbers begins immediately following the hash table
8921    (at offset 16 + 12 * M from the beginning of the section).  The pool of
8922    section numbers consists of an array of 32-bit words (using the byte order
8923    of the application binary).  Each item in the array is indexed starting
8924    from 0.  The hash table entry provides the index of the first section
8925    number in the set.  Additional section numbers in the set follow, and the
8926    set is terminated by a 0 entry (section number 0 is not used in ELF).
8927
8928    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8929    section must be the first entry in the set, and the .debug_abbrev.dwo must
8930    be the second entry. Other members of the set may follow in any order.  */
8931
8932 /* Create a hash table to map DWO IDs to their CU/TU entry in
8933    .debug_{info,types}.dwo in DWP_FILE.
8934    Returns NULL if there isn't one.
8935    Note: This function processes DWP files only, not DWO files.  */
8936
8937 static struct dwp_hash_table *
8938 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8939 {
8940   struct objfile *objfile = dwarf2_per_objfile->objfile;
8941   bfd *dbfd = dwp_file->dbfd;
8942   const gdb_byte *index_ptr, *index_end;
8943   struct dwarf2_section_info *index;
8944   uint32_t version, nr_units, nr_slots;
8945   struct dwp_hash_table *htab;
8946
8947   if (is_debug_types)
8948     index = &dwp_file->sections.tu_index;
8949   else
8950     index = &dwp_file->sections.cu_index;
8951
8952   if (dwarf2_section_empty_p (index))
8953     return NULL;
8954   dwarf2_read_section (objfile, index);
8955
8956   index_ptr = index->buffer;
8957   index_end = index_ptr + index->size;
8958
8959   version = read_4_bytes (dbfd, index_ptr);
8960   index_ptr += 8; /* Skip the unused word.  */
8961   nr_units = read_4_bytes (dbfd, index_ptr);
8962   index_ptr += 4;
8963   nr_slots = read_4_bytes (dbfd, index_ptr);
8964   index_ptr += 4;
8965
8966   if (version != 1)
8967     {
8968       error (_("Dwarf Error: unsupported DWP file version (%s)"
8969                " [in module %s]"),
8970              pulongest (version), dwp_file->name);
8971     }
8972   if (nr_slots != (nr_slots & -nr_slots))
8973     {
8974       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
8975                " is not power of 2 [in module %s]"),
8976              pulongest (nr_slots), dwp_file->name);
8977     }
8978
8979   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8980   htab->nr_units = nr_units;
8981   htab->nr_slots = nr_slots;
8982   htab->hash_table = index_ptr;
8983   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8984   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8985
8986   return htab;
8987 }
8988
8989 /* Update SECTIONS with the data from SECTP.
8990
8991    This function is like the other "locate" section routines that are
8992    passed to bfd_map_over_sections, but in this context the sections to
8993    read comes from the DWP hash table, not the full ELF section table.
8994
8995    The result is non-zero for success, or zero if an error was found.  */
8996
8997 static int
8998 locate_virtual_dwo_sections (asection *sectp,
8999                              struct virtual_dwo_sections *sections)
9000 {
9001   const struct dwop_section_names *names = &dwop_section_names;
9002
9003   if (section_is_p (sectp->name, &names->abbrev_dwo))
9004     {
9005       /* There can be only one.  */
9006       if (sections->abbrev.asection != NULL)
9007         return 0;
9008       sections->abbrev.asection = sectp;
9009       sections->abbrev.size = bfd_get_section_size (sectp);
9010     }
9011   else if (section_is_p (sectp->name, &names->info_dwo)
9012            || section_is_p (sectp->name, &names->types_dwo))
9013     {
9014       /* There can be only one.  */
9015       if (sections->info_or_types.asection != NULL)
9016         return 0;
9017       sections->info_or_types.asection = sectp;
9018       sections->info_or_types.size = bfd_get_section_size (sectp);
9019     }
9020   else if (section_is_p (sectp->name, &names->line_dwo))
9021     {
9022       /* There can be only one.  */
9023       if (sections->line.asection != NULL)
9024         return 0;
9025       sections->line.asection = sectp;
9026       sections->line.size = bfd_get_section_size (sectp);
9027     }
9028   else if (section_is_p (sectp->name, &names->loc_dwo))
9029     {
9030       /* There can be only one.  */
9031       if (sections->loc.asection != NULL)
9032         return 0;
9033       sections->loc.asection = sectp;
9034       sections->loc.size = bfd_get_section_size (sectp);
9035     }
9036   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9037     {
9038       /* There can be only one.  */
9039       if (sections->macinfo.asection != NULL)
9040         return 0;
9041       sections->macinfo.asection = sectp;
9042       sections->macinfo.size = bfd_get_section_size (sectp);
9043     }
9044   else if (section_is_p (sectp->name, &names->macro_dwo))
9045     {
9046       /* There can be only one.  */
9047       if (sections->macro.asection != NULL)
9048         return 0;
9049       sections->macro.asection = sectp;
9050       sections->macro.size = bfd_get_section_size (sectp);
9051     }
9052   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9053     {
9054       /* There can be only one.  */
9055       if (sections->str_offsets.asection != NULL)
9056         return 0;
9057       sections->str_offsets.asection = sectp;
9058       sections->str_offsets.size = bfd_get_section_size (sectp);
9059     }
9060   else
9061     {
9062       /* No other kind of section is valid.  */
9063       return 0;
9064     }
9065
9066   return 1;
9067 }
9068
9069 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9070    HTAB is the hash table from the DWP file.
9071    SECTION_INDEX is the index of the DWO in HTAB.
9072    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9073
9074 static struct dwo_unit *
9075 create_dwo_in_dwp (struct dwp_file *dwp_file,
9076                    const struct dwp_hash_table *htab,
9077                    uint32_t section_index,
9078                    const char *comp_dir,
9079                    ULONGEST signature, int is_debug_types)
9080 {
9081   struct objfile *objfile = dwarf2_per_objfile->objfile;
9082   bfd *dbfd = dwp_file->dbfd;
9083   const char *kind = is_debug_types ? "TU" : "CU";
9084   struct dwo_file *dwo_file;
9085   struct dwo_unit *dwo_unit;
9086   struct virtual_dwo_sections sections;
9087   void **dwo_file_slot;
9088   char *virtual_dwo_name;
9089   struct dwarf2_section_info *cutu;
9090   struct cleanup *cleanups;
9091   int i;
9092
9093   if (dwarf2_read_debug)
9094     {
9095       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9096                           kind,
9097                           pulongest (section_index), hex_string (signature),
9098                           dwp_file->name);
9099     }
9100
9101   /* Fetch the sections of this DWO.
9102      Put a limit on the number of sections we look for so that bad data
9103      doesn't cause us to loop forever.  */
9104
9105 #define MAX_NR_DWO_SECTIONS \
9106   (1 /* .debug_info or .debug_types */ \
9107    + 1 /* .debug_abbrev */ \
9108    + 1 /* .debug_line */ \
9109    + 1 /* .debug_loc */ \
9110    + 1 /* .debug_str_offsets */ \
9111    + 1 /* .debug_macro */ \
9112    + 1 /* .debug_macinfo */ \
9113    + 1 /* trailing zero */)
9114
9115   memset (&sections, 0, sizeof (sections));
9116   cleanups = make_cleanup (null_cleanup, 0);
9117
9118   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9119     {
9120       asection *sectp;
9121       uint32_t section_nr =
9122         read_4_bytes (dbfd,
9123                       htab->section_pool
9124                       + (section_index + i) * sizeof (uint32_t));
9125
9126       if (section_nr == 0)
9127         break;
9128       if (section_nr >= dwp_file->num_sections)
9129         {
9130           error (_("Dwarf Error: bad DWP hash table, section number too large"
9131                    " [in module %s]"),
9132                  dwp_file->name);
9133         }
9134
9135       sectp = dwp_file->elf_sections[section_nr];
9136       if (! locate_virtual_dwo_sections (sectp, &sections))
9137         {
9138           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9139                    " [in module %s]"),
9140                  dwp_file->name);
9141         }
9142     }
9143
9144   if (i < 2
9145       || sections.info_or_types.asection == NULL
9146       || sections.abbrev.asection == NULL)
9147     {
9148       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9149                " [in module %s]"),
9150              dwp_file->name);
9151     }
9152   if (i == MAX_NR_DWO_SECTIONS)
9153     {
9154       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9155                " [in module %s]"),
9156              dwp_file->name);
9157     }
9158
9159   /* It's easier for the rest of the code if we fake a struct dwo_file and
9160      have dwo_unit "live" in that.  At least for now.
9161
9162      The DWP file can be made up of a random collection of CUs and TUs.
9163      However, for each CU + set of TUs that came from the same original DWO
9164      file, we want to combine them back into a virtual DWO file to save space
9165      (fewer struct dwo_file objects to allocated).  Remember that for really
9166      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9167
9168   virtual_dwo_name =
9169     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9170                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9171                 sections.line.asection ? sections.line.asection->id : 0,
9172                 sections.loc.asection ? sections.loc.asection->id : 0,
9173                 (sections.str_offsets.asection
9174                 ? sections.str_offsets.asection->id
9175                 : 0));
9176   make_cleanup (xfree, virtual_dwo_name);
9177   /* Can we use an existing virtual DWO file?  */
9178   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9179   /* Create one if necessary.  */
9180   if (*dwo_file_slot == NULL)
9181     {
9182       if (dwarf2_read_debug)
9183         {
9184           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9185                               virtual_dwo_name);
9186         }
9187       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9188       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9189                                           virtual_dwo_name,
9190                                           strlen (virtual_dwo_name));
9191       dwo_file->comp_dir = comp_dir;
9192       dwo_file->sections.abbrev = sections.abbrev;
9193       dwo_file->sections.line = sections.line;
9194       dwo_file->sections.loc = sections.loc;
9195       dwo_file->sections.macinfo = sections.macinfo;
9196       dwo_file->sections.macro = sections.macro;
9197       dwo_file->sections.str_offsets = sections.str_offsets;
9198       /* The "str" section is global to the entire DWP file.  */
9199       dwo_file->sections.str = dwp_file->sections.str;
9200       /* The info or types section is assigned later to dwo_unit,
9201          there's no need to record it in dwo_file.
9202          Also, we can't simply record type sections in dwo_file because
9203          we record a pointer into the vector in dwo_unit.  As we collect more
9204          types we'll grow the vector and eventually have to reallocate space
9205          for it, invalidating all the pointers into the current copy.  */
9206       *dwo_file_slot = dwo_file;
9207     }
9208   else
9209     {
9210       if (dwarf2_read_debug)
9211         {
9212           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9213                               virtual_dwo_name);
9214         }
9215       dwo_file = *dwo_file_slot;
9216     }
9217   do_cleanups (cleanups);
9218
9219   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9220   dwo_unit->dwo_file = dwo_file;
9221   dwo_unit->signature = signature;
9222   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9223                                      sizeof (struct dwarf2_section_info));
9224   *dwo_unit->section = sections.info_or_types;
9225   /* offset, length, type_offset_in_tu are set later.  */
9226
9227   return dwo_unit;
9228 }
9229
9230 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9231
9232 static struct dwo_unit *
9233 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9234                    const struct dwp_hash_table *htab,
9235                    const char *comp_dir,
9236                    ULONGEST signature, int is_debug_types)
9237 {
9238   bfd *dbfd = dwp_file->dbfd;
9239   uint32_t mask = htab->nr_slots - 1;
9240   uint32_t hash = signature & mask;
9241   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9242   unsigned int i;
9243   void **slot;
9244   struct dwo_unit find_dwo_cu, *dwo_cu;
9245
9246   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9247   find_dwo_cu.signature = signature;
9248   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9249
9250   if (*slot != NULL)
9251     return *slot;
9252
9253   /* Use a for loop so that we don't loop forever on bad debug info.  */
9254   for (i = 0; i < htab->nr_slots; ++i)
9255     {
9256       ULONGEST signature_in_table;
9257
9258       signature_in_table =
9259         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9260       if (signature_in_table == signature)
9261         {
9262           uint32_t section_index =
9263             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9264
9265           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9266                                      comp_dir, signature, is_debug_types);
9267           return *slot;
9268         }
9269       if (signature_in_table == 0)
9270         return NULL;
9271       hash = (hash + hash2) & mask;
9272     }
9273
9274   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9275            " [in module %s]"),
9276          dwp_file->name);
9277 }
9278
9279 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9280    Open the file specified by FILE_NAME and hand it off to BFD for
9281    preliminary analysis.  Return a newly initialized bfd *, which
9282    includes a canonicalized copy of FILE_NAME.
9283    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9284    SEARCH_CWD is true if the current directory is to be searched.
9285    It will be searched before debug-file-directory.
9286    If unable to find/open the file, return NULL.
9287    NOTE: This function is derived from symfile_bfd_open.  */
9288
9289 static bfd *
9290 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9291 {
9292   bfd *sym_bfd;
9293   int desc, flags;
9294   char *absolute_name;
9295   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9296      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9297      to debug_file_directory.  */
9298   char *search_path;
9299   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9300
9301   if (search_cwd)
9302     {
9303       if (*debug_file_directory != '\0')
9304         search_path = concat (".", dirname_separator_string,
9305                               debug_file_directory, NULL);
9306       else
9307         search_path = xstrdup (".");
9308     }
9309   else
9310     search_path = xstrdup (debug_file_directory);
9311
9312   flags = 0;
9313   if (is_dwp)
9314     flags |= OPF_SEARCH_IN_PATH;
9315   desc = openp (search_path, flags, file_name,
9316                 O_RDONLY | O_BINARY, &absolute_name);
9317   xfree (search_path);
9318   if (desc < 0)
9319     return NULL;
9320
9321   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9322   xfree (absolute_name);
9323   if (sym_bfd == NULL)
9324     return NULL;
9325   bfd_set_cacheable (sym_bfd, 1);
9326
9327   if (!bfd_check_format (sym_bfd, bfd_object))
9328     {
9329       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9330       return NULL;
9331     }
9332
9333   return sym_bfd;
9334 }
9335
9336 /* Try to open DWO file FILE_NAME.
9337    COMP_DIR is the DW_AT_comp_dir attribute.
9338    The result is the bfd handle of the file.
9339    If there is a problem finding or opening the file, return NULL.
9340    Upon success, the canonicalized path of the file is stored in the bfd,
9341    same as symfile_bfd_open.  */
9342
9343 static bfd *
9344 open_dwo_file (const char *file_name, const char *comp_dir)
9345 {
9346   bfd *abfd;
9347
9348   if (IS_ABSOLUTE_PATH (file_name))
9349     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9350
9351   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9352
9353   if (comp_dir != NULL)
9354     {
9355       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9356
9357       /* NOTE: If comp_dir is a relative path, this will also try the
9358          search path, which seems useful.  */
9359       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9360       xfree (path_to_try);
9361       if (abfd != NULL)
9362         return abfd;
9363     }
9364
9365   /* That didn't work, try debug-file-directory, which, despite its name,
9366      is a list of paths.  */
9367
9368   if (*debug_file_directory == '\0')
9369     return NULL;
9370
9371   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9372 }
9373
9374 /* This function is mapped across the sections and remembers the offset and
9375    size of each of the DWO debugging sections we are interested in.  */
9376
9377 static void
9378 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9379 {
9380   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9381   const struct dwop_section_names *names = &dwop_section_names;
9382
9383   if (section_is_p (sectp->name, &names->abbrev_dwo))
9384     {
9385       dwo_sections->abbrev.asection = sectp;
9386       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9387     }
9388   else if (section_is_p (sectp->name, &names->info_dwo))
9389     {
9390       dwo_sections->info.asection = sectp;
9391       dwo_sections->info.size = bfd_get_section_size (sectp);
9392     }
9393   else if (section_is_p (sectp->name, &names->line_dwo))
9394     {
9395       dwo_sections->line.asection = sectp;
9396       dwo_sections->line.size = bfd_get_section_size (sectp);
9397     }
9398   else if (section_is_p (sectp->name, &names->loc_dwo))
9399     {
9400       dwo_sections->loc.asection = sectp;
9401       dwo_sections->loc.size = bfd_get_section_size (sectp);
9402     }
9403   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9404     {
9405       dwo_sections->macinfo.asection = sectp;
9406       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9407     }
9408   else if (section_is_p (sectp->name, &names->macro_dwo))
9409     {
9410       dwo_sections->macro.asection = sectp;
9411       dwo_sections->macro.size = bfd_get_section_size (sectp);
9412     }
9413   else if (section_is_p (sectp->name, &names->str_dwo))
9414     {
9415       dwo_sections->str.asection = sectp;
9416       dwo_sections->str.size = bfd_get_section_size (sectp);
9417     }
9418   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9419     {
9420       dwo_sections->str_offsets.asection = sectp;
9421       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9422     }
9423   else if (section_is_p (sectp->name, &names->types_dwo))
9424     {
9425       struct dwarf2_section_info type_section;
9426
9427       memset (&type_section, 0, sizeof (type_section));
9428       type_section.asection = sectp;
9429       type_section.size = bfd_get_section_size (sectp);
9430       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9431                      &type_section);
9432     }
9433 }
9434
9435 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9436    by PER_CU.  This is for the non-DWP case.
9437    The result is NULL if DWO_NAME can't be found.  */
9438
9439 static struct dwo_file *
9440 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9441                         const char *dwo_name, const char *comp_dir)
9442 {
9443   struct objfile *objfile = dwarf2_per_objfile->objfile;
9444   struct dwo_file *dwo_file;
9445   bfd *dbfd;
9446   struct cleanup *cleanups;
9447
9448   dbfd = open_dwo_file (dwo_name, comp_dir);
9449   if (dbfd == NULL)
9450     {
9451       if (dwarf2_read_debug)
9452         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9453       return NULL;
9454     }
9455   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9456   dwo_file->dwo_name = dwo_name;
9457   dwo_file->comp_dir = comp_dir;
9458   dwo_file->dbfd = dbfd;
9459
9460   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9461
9462   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9463
9464   dwo_file->cu = create_dwo_cu (dwo_file);
9465
9466   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9467                                                  dwo_file->sections.types);
9468
9469   discard_cleanups (cleanups);
9470
9471   if (dwarf2_read_debug)
9472     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9473
9474   return dwo_file;
9475 }
9476
9477 /* This function is mapped across the sections and remembers the offset and
9478    size of each of the DWP debugging sections we are interested in.  */
9479
9480 static void
9481 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9482 {
9483   struct dwp_file *dwp_file = dwp_file_ptr;
9484   const struct dwop_section_names *names = &dwop_section_names;
9485   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9486
9487   /* Record the ELF section number for later lookup: this is what the
9488      .debug_cu_index,.debug_tu_index tables use.  */
9489   gdb_assert (elf_section_nr < dwp_file->num_sections);
9490   dwp_file->elf_sections[elf_section_nr] = sectp;
9491
9492   /* Look for specific sections that we need.  */
9493   if (section_is_p (sectp->name, &names->str_dwo))
9494     {
9495       dwp_file->sections.str.asection = sectp;
9496       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9497     }
9498   else if (section_is_p (sectp->name, &names->cu_index))
9499     {
9500       dwp_file->sections.cu_index.asection = sectp;
9501       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9502     }
9503   else if (section_is_p (sectp->name, &names->tu_index))
9504     {
9505       dwp_file->sections.tu_index.asection = sectp;
9506       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9507     }
9508 }
9509
9510 /* Hash function for dwp_file loaded CUs/TUs.  */
9511
9512 static hashval_t
9513 hash_dwp_loaded_cutus (const void *item)
9514 {
9515   const struct dwo_unit *dwo_unit = item;
9516
9517   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9518   return dwo_unit->signature;
9519 }
9520
9521 /* Equality function for dwp_file loaded CUs/TUs.  */
9522
9523 static int
9524 eq_dwp_loaded_cutus (const void *a, const void *b)
9525 {
9526   const struct dwo_unit *dua = a;
9527   const struct dwo_unit *dub = b;
9528
9529   return dua->signature == dub->signature;
9530 }
9531
9532 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9533
9534 static htab_t
9535 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9536 {
9537   return htab_create_alloc_ex (3,
9538                                hash_dwp_loaded_cutus,
9539                                eq_dwp_loaded_cutus,
9540                                NULL,
9541                                &objfile->objfile_obstack,
9542                                hashtab_obstack_allocate,
9543                                dummy_obstack_deallocate);
9544 }
9545
9546 /* Try to open DWP file FILE_NAME.
9547    The result is the bfd handle of the file.
9548    If there is a problem finding or opening the file, return NULL.
9549    Upon success, the canonicalized path of the file is stored in the bfd,
9550    same as symfile_bfd_open.  */
9551
9552 static bfd *
9553 open_dwp_file (const char *file_name)
9554 {
9555   bfd *abfd;
9556
9557   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9558   if (abfd != NULL)
9559     return abfd;
9560
9561   /* Work around upstream bug 15652.
9562      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9563      [Whether that's a "bug" is debatable, but it is getting in our way.]
9564      We have no real idea where the dwp file is, because gdb's realpath-ing
9565      of the executable's path may have discarded the needed info.
9566      [IWBN if the dwp file name was recorded in the executable, akin to
9567      .gnu_debuglink, but that doesn't exist yet.]
9568      Strip the directory from FILE_NAME and search again.  */
9569   if (*debug_file_directory != '\0')
9570     {
9571       /* Don't implicitly search the current directory here.
9572          If the user wants to search "." to handle this case,
9573          it must be added to debug-file-directory.  */
9574       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9575                                  0 /*search_cwd*/);
9576     }
9577
9578   return NULL;
9579 }
9580
9581 /* Initialize the use of the DWP file for the current objfile.
9582    By convention the name of the DWP file is ${objfile}.dwp.
9583    The result is NULL if it can't be found.  */
9584
9585 static struct dwp_file *
9586 open_and_init_dwp_file (void)
9587 {
9588   struct objfile *objfile = dwarf2_per_objfile->objfile;
9589   struct dwp_file *dwp_file;
9590   char *dwp_name;
9591   bfd *dbfd;
9592   struct cleanup *cleanups;
9593
9594   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9595   cleanups = make_cleanup (xfree, dwp_name);
9596
9597   dbfd = open_dwp_file (dwp_name);
9598   if (dbfd == NULL)
9599     {
9600       if (dwarf2_read_debug)
9601         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9602       do_cleanups (cleanups);
9603       return NULL;
9604     }
9605   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9606   dwp_file->name = bfd_get_filename (dbfd);
9607   dwp_file->dbfd = dbfd;
9608   do_cleanups (cleanups);
9609
9610   /* +1: section 0 is unused */
9611   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9612   dwp_file->elf_sections =
9613     OBSTACK_CALLOC (&objfile->objfile_obstack,
9614                     dwp_file->num_sections, asection *);
9615
9616   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9617
9618   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9619
9620   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9621
9622   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9623
9624   if (dwarf2_read_debug)
9625     {
9626       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9627       fprintf_unfiltered (gdb_stdlog,
9628                           "    %s CUs, %s TUs\n",
9629                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9630                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9631     }
9632
9633   return dwp_file;
9634 }
9635
9636 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9637
9638 static struct dwp_file *
9639 get_dwp_file (void)
9640 {
9641   if (! dwarf2_per_objfile->dwp_checked)
9642     {
9643       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9644       dwarf2_per_objfile->dwp_checked = 1;
9645     }
9646   return dwarf2_per_objfile->dwp_file;
9647 }
9648
9649 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9650    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9651    or in the DWP file for the objfile, referenced by THIS_UNIT.
9652    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9653    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9654
9655    This is called, for example, when wanting to read a variable with a
9656    complex location.  Therefore we don't want to do file i/o for every call.
9657    Therefore we don't want to look for a DWO file on every call.
9658    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9659    then we check if we've already seen DWO_NAME, and only THEN do we check
9660    for a DWO file.
9661
9662    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9663    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9664
9665 static struct dwo_unit *
9666 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9667                  const char *dwo_name, const char *comp_dir,
9668                  ULONGEST signature, int is_debug_types)
9669 {
9670   struct objfile *objfile = dwarf2_per_objfile->objfile;
9671   const char *kind = is_debug_types ? "TU" : "CU";
9672   void **dwo_file_slot;
9673   struct dwo_file *dwo_file;
9674   struct dwp_file *dwp_file;
9675
9676   /* First see if there's a DWP file.
9677      If we have a DWP file but didn't find the DWO inside it, don't
9678      look for the original DWO file.  It makes gdb behave differently
9679      depending on whether one is debugging in the build tree.  */
9680
9681   dwp_file = get_dwp_file ();
9682   if (dwp_file != NULL)
9683     {
9684       const struct dwp_hash_table *dwp_htab =
9685         is_debug_types ? dwp_file->tus : dwp_file->cus;
9686
9687       if (dwp_htab != NULL)
9688         {
9689           struct dwo_unit *dwo_cutu =
9690             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9691                                signature, is_debug_types);
9692
9693           if (dwo_cutu != NULL)
9694             {
9695               if (dwarf2_read_debug)
9696                 {
9697                   fprintf_unfiltered (gdb_stdlog,
9698                                       "Virtual DWO %s %s found: @%s\n",
9699                                       kind, hex_string (signature),
9700                                       host_address_to_string (dwo_cutu));
9701                 }
9702               return dwo_cutu;
9703             }
9704         }
9705     }
9706   else
9707     {
9708       /* No DWP file, look for the DWO file.  */
9709
9710       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9711       if (*dwo_file_slot == NULL)
9712         {
9713           /* Read in the file and build a table of the CUs/TUs it contains.  */
9714           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9715         }
9716       /* NOTE: This will be NULL if unable to open the file.  */
9717       dwo_file = *dwo_file_slot;
9718
9719       if (dwo_file != NULL)
9720         {
9721           struct dwo_unit *dwo_cutu = NULL;
9722
9723           if (is_debug_types && dwo_file->tus)
9724             {
9725               struct dwo_unit find_dwo_cutu;
9726
9727               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9728               find_dwo_cutu.signature = signature;
9729               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9730             }
9731           else if (!is_debug_types && dwo_file->cu)
9732             {
9733               if (signature == dwo_file->cu->signature)
9734                 dwo_cutu = dwo_file->cu;
9735             }
9736
9737           if (dwo_cutu != NULL)
9738             {
9739               if (dwarf2_read_debug)
9740                 {
9741                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9742                                       kind, dwo_name, hex_string (signature),
9743                                       host_address_to_string (dwo_cutu));
9744                 }
9745               return dwo_cutu;
9746             }
9747         }
9748     }
9749
9750   /* We didn't find it.  This could mean a dwo_id mismatch, or
9751      someone deleted the DWO/DWP file, or the search path isn't set up
9752      correctly to find the file.  */
9753
9754   if (dwarf2_read_debug)
9755     {
9756       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9757                           kind, dwo_name, hex_string (signature));
9758     }
9759
9760   /* This is a warning and not a complaint because it can be caused by
9761      pilot error (e.g., user accidentally deleting the DWO).  */
9762   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9763              " [in module %s]"),
9764            kind, dwo_name, hex_string (signature),
9765            this_unit->is_debug_types ? "TU" : "CU",
9766            this_unit->offset.sect_off, objfile->name);
9767   return NULL;
9768 }
9769
9770 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9771    See lookup_dwo_cutu_unit for details.  */
9772
9773 static struct dwo_unit *
9774 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9775                       const char *dwo_name, const char *comp_dir,
9776                       ULONGEST signature)
9777 {
9778   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9779 }
9780
9781 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9782    See lookup_dwo_cutu_unit for details.  */
9783
9784 static struct dwo_unit *
9785 lookup_dwo_type_unit (struct signatured_type *this_tu,
9786                       const char *dwo_name, const char *comp_dir)
9787 {
9788   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9789 }
9790
9791 /* Free all resources associated with DWO_FILE.
9792    Close the DWO file and munmap the sections.
9793    All memory should be on the objfile obstack.  */
9794
9795 static void
9796 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9797 {
9798   int ix;
9799   struct dwarf2_section_info *section;
9800
9801   /* Note: dbfd is NULL for virtual DWO files.  */
9802   gdb_bfd_unref (dwo_file->dbfd);
9803
9804   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9805 }
9806
9807 /* Wrapper for free_dwo_file for use in cleanups.  */
9808
9809 static void
9810 free_dwo_file_cleanup (void *arg)
9811 {
9812   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9813   struct objfile *objfile = dwarf2_per_objfile->objfile;
9814
9815   free_dwo_file (dwo_file, objfile);
9816 }
9817
9818 /* Traversal function for free_dwo_files.  */
9819
9820 static int
9821 free_dwo_file_from_slot (void **slot, void *info)
9822 {
9823   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9824   struct objfile *objfile = (struct objfile *) info;
9825
9826   free_dwo_file (dwo_file, objfile);
9827
9828   return 1;
9829 }
9830
9831 /* Free all resources associated with DWO_FILES.  */
9832
9833 static void
9834 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9835 {
9836   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9837 }
9838 \f
9839 /* Read in various DIEs.  */
9840
9841 /* qsort helper for inherit_abstract_dies.  */
9842
9843 static int
9844 unsigned_int_compar (const void *ap, const void *bp)
9845 {
9846   unsigned int a = *(unsigned int *) ap;
9847   unsigned int b = *(unsigned int *) bp;
9848
9849   return (a > b) - (b > a);
9850 }
9851
9852 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9853    Inherit only the children of the DW_AT_abstract_origin DIE not being
9854    already referenced by DW_AT_abstract_origin from the children of the
9855    current DIE.  */
9856
9857 static void
9858 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9859 {
9860   struct die_info *child_die;
9861   unsigned die_children_count;
9862   /* CU offsets which were referenced by children of the current DIE.  */
9863   sect_offset *offsets;
9864   sect_offset *offsets_end, *offsetp;
9865   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9866   struct die_info *origin_die;
9867   /* Iterator of the ORIGIN_DIE children.  */
9868   struct die_info *origin_child_die;
9869   struct cleanup *cleanups;
9870   struct attribute *attr;
9871   struct dwarf2_cu *origin_cu;
9872   struct pending **origin_previous_list_in_scope;
9873
9874   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9875   if (!attr)
9876     return;
9877
9878   /* Note that following die references may follow to a die in a
9879      different cu.  */
9880
9881   origin_cu = cu;
9882   origin_die = follow_die_ref (die, attr, &origin_cu);
9883
9884   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9885      symbols in.  */
9886   origin_previous_list_in_scope = origin_cu->list_in_scope;
9887   origin_cu->list_in_scope = cu->list_in_scope;
9888
9889   if (die->tag != origin_die->tag
9890       && !(die->tag == DW_TAG_inlined_subroutine
9891            && origin_die->tag == DW_TAG_subprogram))
9892     complaint (&symfile_complaints,
9893                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9894                die->offset.sect_off, origin_die->offset.sect_off);
9895
9896   child_die = die->child;
9897   die_children_count = 0;
9898   while (child_die && child_die->tag)
9899     {
9900       child_die = sibling_die (child_die);
9901       die_children_count++;
9902     }
9903   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9904   cleanups = make_cleanup (xfree, offsets);
9905
9906   offsets_end = offsets;
9907   child_die = die->child;
9908   while (child_die && child_die->tag)
9909     {
9910       /* For each CHILD_DIE, find the corresponding child of
9911          ORIGIN_DIE.  If there is more than one layer of
9912          DW_AT_abstract_origin, follow them all; there shouldn't be,
9913          but GCC versions at least through 4.4 generate this (GCC PR
9914          40573).  */
9915       struct die_info *child_origin_die = child_die;
9916       struct dwarf2_cu *child_origin_cu = cu;
9917
9918       while (1)
9919         {
9920           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9921                               child_origin_cu);
9922           if (attr == NULL)
9923             break;
9924           child_origin_die = follow_die_ref (child_origin_die, attr,
9925                                              &child_origin_cu);
9926         }
9927
9928       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9929          counterpart may exist.  */
9930       if (child_origin_die != child_die)
9931         {
9932           if (child_die->tag != child_origin_die->tag
9933               && !(child_die->tag == DW_TAG_inlined_subroutine
9934                    && child_origin_die->tag == DW_TAG_subprogram))
9935             complaint (&symfile_complaints,
9936                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9937                          "different tags"), child_die->offset.sect_off,
9938                        child_origin_die->offset.sect_off);
9939           if (child_origin_die->parent != origin_die)
9940             complaint (&symfile_complaints,
9941                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9942                          "different parents"), child_die->offset.sect_off,
9943                        child_origin_die->offset.sect_off);
9944           else
9945             *offsets_end++ = child_origin_die->offset;
9946         }
9947       child_die = sibling_die (child_die);
9948     }
9949   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9950          unsigned_int_compar);
9951   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9952     if (offsetp[-1].sect_off == offsetp->sect_off)
9953       complaint (&symfile_complaints,
9954                  _("Multiple children of DIE 0x%x refer "
9955                    "to DIE 0x%x as their abstract origin"),
9956                  die->offset.sect_off, offsetp->sect_off);
9957
9958   offsetp = offsets;
9959   origin_child_die = origin_die->child;
9960   while (origin_child_die && origin_child_die->tag)
9961     {
9962       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9963       while (offsetp < offsets_end
9964              && offsetp->sect_off < origin_child_die->offset.sect_off)
9965         offsetp++;
9966       if (offsetp >= offsets_end
9967           || offsetp->sect_off > origin_child_die->offset.sect_off)
9968         {
9969           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9970           process_die (origin_child_die, origin_cu);
9971         }
9972       origin_child_die = sibling_die (origin_child_die);
9973     }
9974   origin_cu->list_in_scope = origin_previous_list_in_scope;
9975
9976   do_cleanups (cleanups);
9977 }
9978
9979 static void
9980 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9981 {
9982   struct objfile *objfile = cu->objfile;
9983   struct context_stack *new;
9984   CORE_ADDR lowpc;
9985   CORE_ADDR highpc;
9986   struct die_info *child_die;
9987   struct attribute *attr, *call_line, *call_file;
9988   const char *name;
9989   CORE_ADDR baseaddr;
9990   struct block *block;
9991   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9992   VEC (symbolp) *template_args = NULL;
9993   struct template_symbol *templ_func = NULL;
9994
9995   if (inlined_func)
9996     {
9997       /* If we do not have call site information, we can't show the
9998          caller of this inlined function.  That's too confusing, so
9999          only use the scope for local variables.  */
10000       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10001       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10002       if (call_line == NULL || call_file == NULL)
10003         {
10004           read_lexical_block_scope (die, cu);
10005           return;
10006         }
10007     }
10008
10009   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10010
10011   name = dwarf2_name (die, cu);
10012
10013   /* Ignore functions with missing or empty names.  These are actually
10014      illegal according to the DWARF standard.  */
10015   if (name == NULL)
10016     {
10017       complaint (&symfile_complaints,
10018                  _("missing name for subprogram DIE at %d"),
10019                  die->offset.sect_off);
10020       return;
10021     }
10022
10023   /* Ignore functions with missing or invalid low and high pc attributes.  */
10024   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10025     {
10026       attr = dwarf2_attr (die, DW_AT_external, cu);
10027       if (!attr || !DW_UNSND (attr))
10028         complaint (&symfile_complaints,
10029                    _("cannot get low and high bounds "
10030                      "for subprogram DIE at %d"),
10031                    die->offset.sect_off);
10032       return;
10033     }
10034
10035   lowpc += baseaddr;
10036   highpc += baseaddr;
10037
10038   /* If we have any template arguments, then we must allocate a
10039      different sort of symbol.  */
10040   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10041     {
10042       if (child_die->tag == DW_TAG_template_type_param
10043           || child_die->tag == DW_TAG_template_value_param)
10044         {
10045           templ_func = allocate_template_symbol (objfile);
10046           templ_func->base.is_cplus_template_function = 1;
10047           break;
10048         }
10049     }
10050
10051   new = push_context (0, lowpc);
10052   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10053                                (struct symbol *) templ_func);
10054
10055   /* If there is a location expression for DW_AT_frame_base, record
10056      it.  */
10057   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10058   if (attr)
10059     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10060
10061   cu->list_in_scope = &local_symbols;
10062
10063   if (die->child != NULL)
10064     {
10065       child_die = die->child;
10066       while (child_die && child_die->tag)
10067         {
10068           if (child_die->tag == DW_TAG_template_type_param
10069               || child_die->tag == DW_TAG_template_value_param)
10070             {
10071               struct symbol *arg = new_symbol (child_die, NULL, cu);
10072
10073               if (arg != NULL)
10074                 VEC_safe_push (symbolp, template_args, arg);
10075             }
10076           else
10077             process_die (child_die, cu);
10078           child_die = sibling_die (child_die);
10079         }
10080     }
10081
10082   inherit_abstract_dies (die, cu);
10083
10084   /* If we have a DW_AT_specification, we might need to import using
10085      directives from the context of the specification DIE.  See the
10086      comment in determine_prefix.  */
10087   if (cu->language == language_cplus
10088       && dwarf2_attr (die, DW_AT_specification, cu))
10089     {
10090       struct dwarf2_cu *spec_cu = cu;
10091       struct die_info *spec_die = die_specification (die, &spec_cu);
10092
10093       while (spec_die)
10094         {
10095           child_die = spec_die->child;
10096           while (child_die && child_die->tag)
10097             {
10098               if (child_die->tag == DW_TAG_imported_module)
10099                 process_die (child_die, spec_cu);
10100               child_die = sibling_die (child_die);
10101             }
10102
10103           /* In some cases, GCC generates specification DIEs that
10104              themselves contain DW_AT_specification attributes.  */
10105           spec_die = die_specification (spec_die, &spec_cu);
10106         }
10107     }
10108
10109   new = pop_context ();
10110   /* Make a block for the local symbols within.  */
10111   block = finish_block (new->name, &local_symbols, new->old_blocks,
10112                         lowpc, highpc, objfile);
10113
10114   /* For C++, set the block's scope.  */
10115   if ((cu->language == language_cplus || cu->language == language_fortran)
10116       && cu->processing_has_namespace_info)
10117     block_set_scope (block, determine_prefix (die, cu),
10118                      &objfile->objfile_obstack);
10119
10120   /* If we have address ranges, record them.  */
10121   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10122
10123   /* Attach template arguments to function.  */
10124   if (! VEC_empty (symbolp, template_args))
10125     {
10126       gdb_assert (templ_func != NULL);
10127
10128       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10129       templ_func->template_arguments
10130         = obstack_alloc (&objfile->objfile_obstack,
10131                          (templ_func->n_template_arguments
10132                           * sizeof (struct symbol *)));
10133       memcpy (templ_func->template_arguments,
10134               VEC_address (symbolp, template_args),
10135               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10136       VEC_free (symbolp, template_args);
10137     }
10138
10139   /* In C++, we can have functions nested inside functions (e.g., when
10140      a function declares a class that has methods).  This means that
10141      when we finish processing a function scope, we may need to go
10142      back to building a containing block's symbol lists.  */
10143   local_symbols = new->locals;
10144   using_directives = new->using_directives;
10145
10146   /* If we've finished processing a top-level function, subsequent
10147      symbols go in the file symbol list.  */
10148   if (outermost_context_p ())
10149     cu->list_in_scope = &file_symbols;
10150 }
10151
10152 /* Process all the DIES contained within a lexical block scope.  Start
10153    a new scope, process the dies, and then close the scope.  */
10154
10155 static void
10156 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10157 {
10158   struct objfile *objfile = cu->objfile;
10159   struct context_stack *new;
10160   CORE_ADDR lowpc, highpc;
10161   struct die_info *child_die;
10162   CORE_ADDR baseaddr;
10163
10164   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10165
10166   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10167   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10168      as multiple lexical blocks?  Handling children in a sane way would
10169      be nasty.  Might be easier to properly extend generic blocks to
10170      describe ranges.  */
10171   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10172     return;
10173   lowpc += baseaddr;
10174   highpc += baseaddr;
10175
10176   push_context (0, lowpc);
10177   if (die->child != NULL)
10178     {
10179       child_die = die->child;
10180       while (child_die && child_die->tag)
10181         {
10182           process_die (child_die, cu);
10183           child_die = sibling_die (child_die);
10184         }
10185     }
10186   new = pop_context ();
10187
10188   if (local_symbols != NULL || using_directives != NULL)
10189     {
10190       struct block *block
10191         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10192                         highpc, objfile);
10193
10194       /* Note that recording ranges after traversing children, as we
10195          do here, means that recording a parent's ranges entails
10196          walking across all its children's ranges as they appear in
10197          the address map, which is quadratic behavior.
10198
10199          It would be nicer to record the parent's ranges before
10200          traversing its children, simply overriding whatever you find
10201          there.  But since we don't even decide whether to create a
10202          block until after we've traversed its children, that's hard
10203          to do.  */
10204       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10205     }
10206   local_symbols = new->locals;
10207   using_directives = new->using_directives;
10208 }
10209
10210 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10211
10212 static void
10213 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10214 {
10215   struct objfile *objfile = cu->objfile;
10216   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10217   CORE_ADDR pc, baseaddr;
10218   struct attribute *attr;
10219   struct call_site *call_site, call_site_local;
10220   void **slot;
10221   int nparams;
10222   struct die_info *child_die;
10223
10224   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10225
10226   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10227   if (!attr)
10228     {
10229       complaint (&symfile_complaints,
10230                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10231                    "DIE 0x%x [in module %s]"),
10232                  die->offset.sect_off, objfile->name);
10233       return;
10234     }
10235   pc = DW_ADDR (attr) + baseaddr;
10236
10237   if (cu->call_site_htab == NULL)
10238     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10239                                                NULL, &objfile->objfile_obstack,
10240                                                hashtab_obstack_allocate, NULL);
10241   call_site_local.pc = pc;
10242   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10243   if (*slot != NULL)
10244     {
10245       complaint (&symfile_complaints,
10246                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10247                    "DIE 0x%x [in module %s]"),
10248                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
10249       return;
10250     }
10251
10252   /* Count parameters at the caller.  */
10253
10254   nparams = 0;
10255   for (child_die = die->child; child_die && child_die->tag;
10256        child_die = sibling_die (child_die))
10257     {
10258       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10259         {
10260           complaint (&symfile_complaints,
10261                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10262                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10263                      child_die->tag, child_die->offset.sect_off, objfile->name);
10264           continue;
10265         }
10266
10267       nparams++;
10268     }
10269
10270   call_site = obstack_alloc (&objfile->objfile_obstack,
10271                              (sizeof (*call_site)
10272                               + (sizeof (*call_site->parameter)
10273                                  * (nparams - 1))));
10274   *slot = call_site;
10275   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10276   call_site->pc = pc;
10277
10278   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10279     {
10280       struct die_info *func_die;
10281
10282       /* Skip also over DW_TAG_inlined_subroutine.  */
10283       for (func_die = die->parent;
10284            func_die && func_die->tag != DW_TAG_subprogram
10285            && func_die->tag != DW_TAG_subroutine_type;
10286            func_die = func_die->parent);
10287
10288       /* DW_AT_GNU_all_call_sites is a superset
10289          of DW_AT_GNU_all_tail_call_sites.  */
10290       if (func_die
10291           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10292           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10293         {
10294           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10295              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10296              both the initial caller containing the real return address PC and
10297              the final callee containing the current PC of a chain of tail
10298              calls do not need to have the tail call list complete.  But any
10299              function candidate for a virtual tail call frame searched via
10300              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10301              determined unambiguously.  */
10302         }
10303       else
10304         {
10305           struct type *func_type = NULL;
10306
10307           if (func_die)
10308             func_type = get_die_type (func_die, cu);
10309           if (func_type != NULL)
10310             {
10311               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10312
10313               /* Enlist this call site to the function.  */
10314               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10315               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10316             }
10317           else
10318             complaint (&symfile_complaints,
10319                        _("Cannot find function owning DW_TAG_GNU_call_site "
10320                          "DIE 0x%x [in module %s]"),
10321                        die->offset.sect_off, objfile->name);
10322         }
10323     }
10324
10325   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10326   if (attr == NULL)
10327     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10328   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10329   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10330     /* Keep NULL DWARF_BLOCK.  */;
10331   else if (attr_form_is_block (attr))
10332     {
10333       struct dwarf2_locexpr_baton *dlbaton;
10334
10335       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10336       dlbaton->data = DW_BLOCK (attr)->data;
10337       dlbaton->size = DW_BLOCK (attr)->size;
10338       dlbaton->per_cu = cu->per_cu;
10339
10340       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10341     }
10342   else if (attr_form_is_ref (attr))
10343     {
10344       struct dwarf2_cu *target_cu = cu;
10345       struct die_info *target_die;
10346
10347       target_die = follow_die_ref (die, attr, &target_cu);
10348       gdb_assert (target_cu->objfile == objfile);
10349       if (die_is_declaration (target_die, target_cu))
10350         {
10351           const char *target_physname = NULL;
10352           struct attribute *target_attr;
10353
10354           /* Prefer the mangled name; otherwise compute the demangled one.  */
10355           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10356           if (target_attr == NULL)
10357             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10358                                        target_cu);
10359           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10360             target_physname = DW_STRING (target_attr);
10361           else
10362             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10363           if (target_physname == NULL)
10364             complaint (&symfile_complaints,
10365                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10366                          "physname, for referencing DIE 0x%x [in module %s]"),
10367                        die->offset.sect_off, objfile->name);
10368           else
10369             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10370         }
10371       else
10372         {
10373           CORE_ADDR lowpc;
10374
10375           /* DW_AT_entry_pc should be preferred.  */
10376           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10377             complaint (&symfile_complaints,
10378                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10379                          "low pc, for referencing DIE 0x%x [in module %s]"),
10380                        die->offset.sect_off, objfile->name);
10381           else
10382             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10383         }
10384     }
10385   else
10386     complaint (&symfile_complaints,
10387                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10388                  "block nor reference, for DIE 0x%x [in module %s]"),
10389                die->offset.sect_off, objfile->name);
10390
10391   call_site->per_cu = cu->per_cu;
10392
10393   for (child_die = die->child;
10394        child_die && child_die->tag;
10395        child_die = sibling_die (child_die))
10396     {
10397       struct call_site_parameter *parameter;
10398       struct attribute *loc, *origin;
10399
10400       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10401         {
10402           /* Already printed the complaint above.  */
10403           continue;
10404         }
10405
10406       gdb_assert (call_site->parameter_count < nparams);
10407       parameter = &call_site->parameter[call_site->parameter_count];
10408
10409       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10410          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10411          register is contained in DW_AT_GNU_call_site_value.  */
10412
10413       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10414       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10415       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
10416         {
10417           sect_offset offset;
10418
10419           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10420           offset = dwarf2_get_ref_die_offset (origin);
10421           if (!offset_in_cu_p (&cu->header, offset))
10422             {
10423               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10424                  binding can be done only inside one CU.  Such referenced DIE
10425                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10426               complaint (&symfile_complaints,
10427                          _("DW_AT_abstract_origin offset is not in CU for "
10428                            "DW_TAG_GNU_call_site child DIE 0x%x "
10429                            "[in module %s]"),
10430                          child_die->offset.sect_off, objfile->name);
10431               continue;
10432             }
10433           parameter->u.param_offset.cu_off = (offset.sect_off
10434                                               - cu->header.offset.sect_off);
10435         }
10436       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10437         {
10438           complaint (&symfile_complaints,
10439                      _("No DW_FORM_block* DW_AT_location for "
10440                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10441                      child_die->offset.sect_off, objfile->name);
10442           continue;
10443         }
10444       else
10445         {
10446           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10447             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10448           if (parameter->u.dwarf_reg != -1)
10449             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10450           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10451                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10452                                              &parameter->u.fb_offset))
10453             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10454           else
10455             {
10456               complaint (&symfile_complaints,
10457                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10458                            "for DW_FORM_block* DW_AT_location is supported for "
10459                            "DW_TAG_GNU_call_site child DIE 0x%x "
10460                            "[in module %s]"),
10461                          child_die->offset.sect_off, objfile->name);
10462               continue;
10463             }
10464         }
10465
10466       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10467       if (!attr_form_is_block (attr))
10468         {
10469           complaint (&symfile_complaints,
10470                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10471                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10472                      child_die->offset.sect_off, objfile->name);
10473           continue;
10474         }
10475       parameter->value = DW_BLOCK (attr)->data;
10476       parameter->value_size = DW_BLOCK (attr)->size;
10477
10478       /* Parameters are not pre-cleared by memset above.  */
10479       parameter->data_value = NULL;
10480       parameter->data_value_size = 0;
10481       call_site->parameter_count++;
10482
10483       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10484       if (attr)
10485         {
10486           if (!attr_form_is_block (attr))
10487             complaint (&symfile_complaints,
10488                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10489                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10490                        child_die->offset.sect_off, objfile->name);
10491           else
10492             {
10493               parameter->data_value = DW_BLOCK (attr)->data;
10494               parameter->data_value_size = DW_BLOCK (attr)->size;
10495             }
10496         }
10497     }
10498 }
10499
10500 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10501    Return 1 if the attributes are present and valid, otherwise, return 0.
10502    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10503
10504 static int
10505 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10506                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10507                     struct partial_symtab *ranges_pst)
10508 {
10509   struct objfile *objfile = cu->objfile;
10510   struct comp_unit_head *cu_header = &cu->header;
10511   bfd *obfd = objfile->obfd;
10512   unsigned int addr_size = cu_header->addr_size;
10513   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10514   /* Base address selection entry.  */
10515   CORE_ADDR base;
10516   int found_base;
10517   unsigned int dummy;
10518   const gdb_byte *buffer;
10519   CORE_ADDR marker;
10520   int low_set;
10521   CORE_ADDR low = 0;
10522   CORE_ADDR high = 0;
10523   CORE_ADDR baseaddr;
10524
10525   found_base = cu->base_known;
10526   base = cu->base_address;
10527
10528   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10529   if (offset >= dwarf2_per_objfile->ranges.size)
10530     {
10531       complaint (&symfile_complaints,
10532                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10533                  offset);
10534       return 0;
10535     }
10536   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10537
10538   /* Read in the largest possible address.  */
10539   marker = read_address (obfd, buffer, cu, &dummy);
10540   if ((marker & mask) == mask)
10541     {
10542       /* If we found the largest possible address, then
10543          read the base address.  */
10544       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10545       buffer += 2 * addr_size;
10546       offset += 2 * addr_size;
10547       found_base = 1;
10548     }
10549
10550   low_set = 0;
10551
10552   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10553
10554   while (1)
10555     {
10556       CORE_ADDR range_beginning, range_end;
10557
10558       range_beginning = read_address (obfd, buffer, cu, &dummy);
10559       buffer += addr_size;
10560       range_end = read_address (obfd, buffer, cu, &dummy);
10561       buffer += addr_size;
10562       offset += 2 * addr_size;
10563
10564       /* An end of list marker is a pair of zero addresses.  */
10565       if (range_beginning == 0 && range_end == 0)
10566         /* Found the end of list entry.  */
10567         break;
10568
10569       /* Each base address selection entry is a pair of 2 values.
10570          The first is the largest possible address, the second is
10571          the base address.  Check for a base address here.  */
10572       if ((range_beginning & mask) == mask)
10573         {
10574           /* If we found the largest possible address, then
10575              read the base address.  */
10576           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10577           found_base = 1;
10578           continue;
10579         }
10580
10581       if (!found_base)
10582         {
10583           /* We have no valid base address for the ranges
10584              data.  */
10585           complaint (&symfile_complaints,
10586                      _("Invalid .debug_ranges data (no base address)"));
10587           return 0;
10588         }
10589
10590       if (range_beginning > range_end)
10591         {
10592           /* Inverted range entries are invalid.  */
10593           complaint (&symfile_complaints,
10594                      _("Invalid .debug_ranges data (inverted range)"));
10595           return 0;
10596         }
10597
10598       /* Empty range entries have no effect.  */
10599       if (range_beginning == range_end)
10600         continue;
10601
10602       range_beginning += base;
10603       range_end += base;
10604
10605       /* A not-uncommon case of bad debug info.
10606          Don't pollute the addrmap with bad data.  */
10607       if (range_beginning + baseaddr == 0
10608           && !dwarf2_per_objfile->has_section_at_zero)
10609         {
10610           complaint (&symfile_complaints,
10611                      _(".debug_ranges entry has start address of zero"
10612                        " [in module %s]"), objfile->name);
10613           continue;
10614         }
10615
10616       if (ranges_pst != NULL)
10617         addrmap_set_empty (objfile->psymtabs_addrmap,
10618                            range_beginning + baseaddr,
10619                            range_end - 1 + baseaddr,
10620                            ranges_pst);
10621
10622       /* FIXME: This is recording everything as a low-high
10623          segment of consecutive addresses.  We should have a
10624          data structure for discontiguous block ranges
10625          instead.  */
10626       if (! low_set)
10627         {
10628           low = range_beginning;
10629           high = range_end;
10630           low_set = 1;
10631         }
10632       else
10633         {
10634           if (range_beginning < low)
10635             low = range_beginning;
10636           if (range_end > high)
10637             high = range_end;
10638         }
10639     }
10640
10641   if (! low_set)
10642     /* If the first entry is an end-of-list marker, the range
10643        describes an empty scope, i.e. no instructions.  */
10644     return 0;
10645
10646   if (low_return)
10647     *low_return = low;
10648   if (high_return)
10649     *high_return = high;
10650   return 1;
10651 }
10652
10653 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10654    are present and valid, otherwise, return 0.  Return -1 if the range is
10655    discontinuous, i.e. derived from DW_AT_ranges information.  */
10656
10657 static int
10658 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10659                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10660                       struct partial_symtab *pst)
10661 {
10662   struct attribute *attr;
10663   struct attribute *attr_high;
10664   CORE_ADDR low = 0;
10665   CORE_ADDR high = 0;
10666   int ret = 0;
10667
10668   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10669   if (attr_high)
10670     {
10671       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10672       if (attr)
10673         {
10674           low = DW_ADDR (attr);
10675           if (attr_high->form == DW_FORM_addr
10676               || attr_high->form == DW_FORM_GNU_addr_index)
10677             high = DW_ADDR (attr_high);
10678           else
10679             high = low + DW_UNSND (attr_high);
10680         }
10681       else
10682         /* Found high w/o low attribute.  */
10683         return 0;
10684
10685       /* Found consecutive range of addresses.  */
10686       ret = 1;
10687     }
10688   else
10689     {
10690       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10691       if (attr != NULL)
10692         {
10693           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10694              We take advantage of the fact that DW_AT_ranges does not appear
10695              in DW_TAG_compile_unit of DWO files.  */
10696           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10697           unsigned int ranges_offset = (DW_UNSND (attr)
10698                                         + (need_ranges_base
10699                                            ? cu->ranges_base
10700                                            : 0));
10701
10702           /* Value of the DW_AT_ranges attribute is the offset in the
10703              .debug_ranges section.  */
10704           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10705             return 0;
10706           /* Found discontinuous range of addresses.  */
10707           ret = -1;
10708         }
10709     }
10710
10711   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10712   if (high <= low)
10713     return 0;
10714
10715   /* When using the GNU linker, .gnu.linkonce. sections are used to
10716      eliminate duplicate copies of functions and vtables and such.
10717      The linker will arbitrarily choose one and discard the others.
10718      The AT_*_pc values for such functions refer to local labels in
10719      these sections.  If the section from that file was discarded, the
10720      labels are not in the output, so the relocs get a value of 0.
10721      If this is a discarded function, mark the pc bounds as invalid,
10722      so that GDB will ignore it.  */
10723   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10724     return 0;
10725
10726   *lowpc = low;
10727   if (highpc)
10728     *highpc = high;
10729   return ret;
10730 }
10731
10732 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10733    its low and high PC addresses.  Do nothing if these addresses could not
10734    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10735    and HIGHPC to the high address if greater than HIGHPC.  */
10736
10737 static void
10738 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10739                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10740                                  struct dwarf2_cu *cu)
10741 {
10742   CORE_ADDR low, high;
10743   struct die_info *child = die->child;
10744
10745   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10746     {
10747       *lowpc = min (*lowpc, low);
10748       *highpc = max (*highpc, high);
10749     }
10750
10751   /* If the language does not allow nested subprograms (either inside
10752      subprograms or lexical blocks), we're done.  */
10753   if (cu->language != language_ada)
10754     return;
10755
10756   /* Check all the children of the given DIE.  If it contains nested
10757      subprograms, then check their pc bounds.  Likewise, we need to
10758      check lexical blocks as well, as they may also contain subprogram
10759      definitions.  */
10760   while (child && child->tag)
10761     {
10762       if (child->tag == DW_TAG_subprogram
10763           || child->tag == DW_TAG_lexical_block)
10764         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10765       child = sibling_die (child);
10766     }
10767 }
10768
10769 /* Get the low and high pc's represented by the scope DIE, and store
10770    them in *LOWPC and *HIGHPC.  If the correct values can't be
10771    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10772
10773 static void
10774 get_scope_pc_bounds (struct die_info *die,
10775                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10776                      struct dwarf2_cu *cu)
10777 {
10778   CORE_ADDR best_low = (CORE_ADDR) -1;
10779   CORE_ADDR best_high = (CORE_ADDR) 0;
10780   CORE_ADDR current_low, current_high;
10781
10782   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10783     {
10784       best_low = current_low;
10785       best_high = current_high;
10786     }
10787   else
10788     {
10789       struct die_info *child = die->child;
10790
10791       while (child && child->tag)
10792         {
10793           switch (child->tag) {
10794           case DW_TAG_subprogram:
10795             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10796             break;
10797           case DW_TAG_namespace:
10798           case DW_TAG_module:
10799             /* FIXME: carlton/2004-01-16: Should we do this for
10800                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10801                that current GCC's always emit the DIEs corresponding
10802                to definitions of methods of classes as children of a
10803                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10804                the DIEs giving the declarations, which could be
10805                anywhere).  But I don't see any reason why the
10806                standards says that they have to be there.  */
10807             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10808
10809             if (current_low != ((CORE_ADDR) -1))
10810               {
10811                 best_low = min (best_low, current_low);
10812                 best_high = max (best_high, current_high);
10813               }
10814             break;
10815           default:
10816             /* Ignore.  */
10817             break;
10818           }
10819
10820           child = sibling_die (child);
10821         }
10822     }
10823
10824   *lowpc = best_low;
10825   *highpc = best_high;
10826 }
10827
10828 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10829    in DIE.  */
10830
10831 static void
10832 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10833                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10834 {
10835   struct objfile *objfile = cu->objfile;
10836   struct attribute *attr;
10837   struct attribute *attr_high;
10838
10839   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10840   if (attr_high)
10841     {
10842       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10843       if (attr)
10844         {
10845           CORE_ADDR low = DW_ADDR (attr);
10846           CORE_ADDR high;
10847           if (attr_high->form == DW_FORM_addr
10848               || attr_high->form == DW_FORM_GNU_addr_index)
10849             high = DW_ADDR (attr_high);
10850           else
10851             high = low + DW_UNSND (attr_high);
10852
10853           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10854         }
10855     }
10856
10857   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10858   if (attr)
10859     {
10860       bfd *obfd = objfile->obfd;
10861       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10862          We take advantage of the fact that DW_AT_ranges does not appear
10863          in DW_TAG_compile_unit of DWO files.  */
10864       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10865
10866       /* The value of the DW_AT_ranges attribute is the offset of the
10867          address range list in the .debug_ranges section.  */
10868       unsigned long offset = (DW_UNSND (attr)
10869                               + (need_ranges_base ? cu->ranges_base : 0));
10870       const gdb_byte *buffer;
10871
10872       /* For some target architectures, but not others, the
10873          read_address function sign-extends the addresses it returns.
10874          To recognize base address selection entries, we need a
10875          mask.  */
10876       unsigned int addr_size = cu->header.addr_size;
10877       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10878
10879       /* The base address, to which the next pair is relative.  Note
10880          that this 'base' is a DWARF concept: most entries in a range
10881          list are relative, to reduce the number of relocs against the
10882          debugging information.  This is separate from this function's
10883          'baseaddr' argument, which GDB uses to relocate debugging
10884          information from a shared library based on the address at
10885          which the library was loaded.  */
10886       CORE_ADDR base = cu->base_address;
10887       int base_known = cu->base_known;
10888
10889       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10890       if (offset >= dwarf2_per_objfile->ranges.size)
10891         {
10892           complaint (&symfile_complaints,
10893                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10894                      offset);
10895           return;
10896         }
10897       buffer = dwarf2_per_objfile->ranges.buffer + offset;
10898
10899       for (;;)
10900         {
10901           unsigned int bytes_read;
10902           CORE_ADDR start, end;
10903
10904           start = read_address (obfd, buffer, cu, &bytes_read);
10905           buffer += bytes_read;
10906           end = read_address (obfd, buffer, cu, &bytes_read);
10907           buffer += bytes_read;
10908
10909           /* Did we find the end of the range list?  */
10910           if (start == 0 && end == 0)
10911             break;
10912
10913           /* Did we find a base address selection entry?  */
10914           else if ((start & base_select_mask) == base_select_mask)
10915             {
10916               base = end;
10917               base_known = 1;
10918             }
10919
10920           /* We found an ordinary address range.  */
10921           else
10922             {
10923               if (!base_known)
10924                 {
10925                   complaint (&symfile_complaints,
10926                              _("Invalid .debug_ranges data "
10927                                "(no base address)"));
10928                   return;
10929                 }
10930
10931               if (start > end)
10932                 {
10933                   /* Inverted range entries are invalid.  */
10934                   complaint (&symfile_complaints,
10935                              _("Invalid .debug_ranges data "
10936                                "(inverted range)"));
10937                   return;
10938                 }
10939
10940               /* Empty range entries have no effect.  */
10941               if (start == end)
10942                 continue;
10943
10944               start += base + baseaddr;
10945               end += base + baseaddr;
10946
10947               /* A not-uncommon case of bad debug info.
10948                  Don't pollute the addrmap with bad data.  */
10949               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10950                 {
10951                   complaint (&symfile_complaints,
10952                              _(".debug_ranges entry has start address of zero"
10953                                " [in module %s]"), objfile->name);
10954                   continue;
10955                 }
10956
10957               record_block_range (block, start, end - 1);
10958             }
10959         }
10960     }
10961 }
10962
10963 /* Check whether the producer field indicates either of GCC < 4.6, or the
10964    Intel C/C++ compiler, and cache the result in CU.  */
10965
10966 static void
10967 check_producer (struct dwarf2_cu *cu)
10968 {
10969   const char *cs;
10970   int major, minor, release;
10971
10972   if (cu->producer == NULL)
10973     {
10974       /* For unknown compilers expect their behavior is DWARF version
10975          compliant.
10976
10977          GCC started to support .debug_types sections by -gdwarf-4 since
10978          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10979          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10980          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10981          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10982     }
10983   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10984     {
10985       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10986
10987       cs = &cu->producer[strlen ("GNU ")];
10988       while (*cs && !isdigit (*cs))
10989         cs++;
10990       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10991         {
10992           /* Not recognized as GCC.  */
10993         }
10994       else
10995         {
10996           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10997           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10998         }
10999     }
11000   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11001     cu->producer_is_icc = 1;
11002   else
11003     {
11004       /* For other non-GCC compilers, expect their behavior is DWARF version
11005          compliant.  */
11006     }
11007
11008   cu->checked_producer = 1;
11009 }
11010
11011 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11012    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11013    during 4.6.0 experimental.  */
11014
11015 static int
11016 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11017 {
11018   if (!cu->checked_producer)
11019     check_producer (cu);
11020
11021   return cu->producer_is_gxx_lt_4_6;
11022 }
11023
11024 /* Return the default accessibility type if it is not overriden by
11025    DW_AT_accessibility.  */
11026
11027 static enum dwarf_access_attribute
11028 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11029 {
11030   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11031     {
11032       /* The default DWARF 2 accessibility for members is public, the default
11033          accessibility for inheritance is private.  */
11034
11035       if (die->tag != DW_TAG_inheritance)
11036         return DW_ACCESS_public;
11037       else
11038         return DW_ACCESS_private;
11039     }
11040   else
11041     {
11042       /* DWARF 3+ defines the default accessibility a different way.  The same
11043          rules apply now for DW_TAG_inheritance as for the members and it only
11044          depends on the container kind.  */
11045
11046       if (die->parent->tag == DW_TAG_class_type)
11047         return DW_ACCESS_private;
11048       else
11049         return DW_ACCESS_public;
11050     }
11051 }
11052
11053 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11054    offset.  If the attribute was not found return 0, otherwise return
11055    1.  If it was found but could not properly be handled, set *OFFSET
11056    to 0.  */
11057
11058 static int
11059 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11060                              LONGEST *offset)
11061 {
11062   struct attribute *attr;
11063
11064   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11065   if (attr != NULL)
11066     {
11067       *offset = 0;
11068
11069       /* Note that we do not check for a section offset first here.
11070          This is because DW_AT_data_member_location is new in DWARF 4,
11071          so if we see it, we can assume that a constant form is really
11072          a constant and not a section offset.  */
11073       if (attr_form_is_constant (attr))
11074         *offset = dwarf2_get_attr_constant_value (attr, 0);
11075       else if (attr_form_is_section_offset (attr))
11076         dwarf2_complex_location_expr_complaint ();
11077       else if (attr_form_is_block (attr))
11078         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11079       else
11080         dwarf2_complex_location_expr_complaint ();
11081
11082       return 1;
11083     }
11084
11085   return 0;
11086 }
11087
11088 /* Add an aggregate field to the field list.  */
11089
11090 static void
11091 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11092                   struct dwarf2_cu *cu)
11093 {
11094   struct objfile *objfile = cu->objfile;
11095   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11096   struct nextfield *new_field;
11097   struct attribute *attr;
11098   struct field *fp;
11099   const char *fieldname = "";
11100
11101   /* Allocate a new field list entry and link it in.  */
11102   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11103   make_cleanup (xfree, new_field);
11104   memset (new_field, 0, sizeof (struct nextfield));
11105
11106   if (die->tag == DW_TAG_inheritance)
11107     {
11108       new_field->next = fip->baseclasses;
11109       fip->baseclasses = new_field;
11110     }
11111   else
11112     {
11113       new_field->next = fip->fields;
11114       fip->fields = new_field;
11115     }
11116   fip->nfields++;
11117
11118   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11119   if (attr)
11120     new_field->accessibility = DW_UNSND (attr);
11121   else
11122     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11123   if (new_field->accessibility != DW_ACCESS_public)
11124     fip->non_public_fields = 1;
11125
11126   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11127   if (attr)
11128     new_field->virtuality = DW_UNSND (attr);
11129   else
11130     new_field->virtuality = DW_VIRTUALITY_none;
11131
11132   fp = &new_field->field;
11133
11134   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11135     {
11136       LONGEST offset;
11137
11138       /* Data member other than a C++ static data member.  */
11139
11140       /* Get type of field.  */
11141       fp->type = die_type (die, cu);
11142
11143       SET_FIELD_BITPOS (*fp, 0);
11144
11145       /* Get bit size of field (zero if none).  */
11146       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11147       if (attr)
11148         {
11149           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11150         }
11151       else
11152         {
11153           FIELD_BITSIZE (*fp) = 0;
11154         }
11155
11156       /* Get bit offset of field.  */
11157       if (handle_data_member_location (die, cu, &offset))
11158         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11159       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11160       if (attr)
11161         {
11162           if (gdbarch_bits_big_endian (gdbarch))
11163             {
11164               /* For big endian bits, the DW_AT_bit_offset gives the
11165                  additional bit offset from the MSB of the containing
11166                  anonymous object to the MSB of the field.  We don't
11167                  have to do anything special since we don't need to
11168                  know the size of the anonymous object.  */
11169               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11170             }
11171           else
11172             {
11173               /* For little endian bits, compute the bit offset to the
11174                  MSB of the anonymous object, subtract off the number of
11175                  bits from the MSB of the field to the MSB of the
11176                  object, and then subtract off the number of bits of
11177                  the field itself.  The result is the bit offset of
11178                  the LSB of the field.  */
11179               int anonymous_size;
11180               int bit_offset = DW_UNSND (attr);
11181
11182               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11183               if (attr)
11184                 {
11185                   /* The size of the anonymous object containing
11186                      the bit field is explicit, so use the
11187                      indicated size (in bytes).  */
11188                   anonymous_size = DW_UNSND (attr);
11189                 }
11190               else
11191                 {
11192                   /* The size of the anonymous object containing
11193                      the bit field must be inferred from the type
11194                      attribute of the data member containing the
11195                      bit field.  */
11196                   anonymous_size = TYPE_LENGTH (fp->type);
11197                 }
11198               SET_FIELD_BITPOS (*fp,
11199                                 (FIELD_BITPOS (*fp)
11200                                  + anonymous_size * bits_per_byte
11201                                  - bit_offset - FIELD_BITSIZE (*fp)));
11202             }
11203         }
11204
11205       /* Get name of field.  */
11206       fieldname = dwarf2_name (die, cu);
11207       if (fieldname == NULL)
11208         fieldname = "";
11209
11210       /* The name is already allocated along with this objfile, so we don't
11211          need to duplicate it for the type.  */
11212       fp->name = fieldname;
11213
11214       /* Change accessibility for artificial fields (e.g. virtual table
11215          pointer or virtual base class pointer) to private.  */
11216       if (dwarf2_attr (die, DW_AT_artificial, cu))
11217         {
11218           FIELD_ARTIFICIAL (*fp) = 1;
11219           new_field->accessibility = DW_ACCESS_private;
11220           fip->non_public_fields = 1;
11221         }
11222     }
11223   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11224     {
11225       /* C++ static member.  */
11226
11227       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11228          is a declaration, but all versions of G++ as of this writing
11229          (so through at least 3.2.1) incorrectly generate
11230          DW_TAG_variable tags.  */
11231
11232       const char *physname;
11233
11234       /* Get name of field.  */
11235       fieldname = dwarf2_name (die, cu);
11236       if (fieldname == NULL)
11237         return;
11238
11239       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11240       if (attr
11241           /* Only create a symbol if this is an external value.
11242              new_symbol checks this and puts the value in the global symbol
11243              table, which we want.  If it is not external, new_symbol
11244              will try to put the value in cu->list_in_scope which is wrong.  */
11245           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11246         {
11247           /* A static const member, not much different than an enum as far as
11248              we're concerned, except that we can support more types.  */
11249           new_symbol (die, NULL, cu);
11250         }
11251
11252       /* Get physical name.  */
11253       physname = dwarf2_physname (fieldname, die, cu);
11254
11255       /* The name is already allocated along with this objfile, so we don't
11256          need to duplicate it for the type.  */
11257       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11258       FIELD_TYPE (*fp) = die_type (die, cu);
11259       FIELD_NAME (*fp) = fieldname;
11260     }
11261   else if (die->tag == DW_TAG_inheritance)
11262     {
11263       LONGEST offset;
11264
11265       /* C++ base class field.  */
11266       if (handle_data_member_location (die, cu, &offset))
11267         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11268       FIELD_BITSIZE (*fp) = 0;
11269       FIELD_TYPE (*fp) = die_type (die, cu);
11270       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11271       fip->nbaseclasses++;
11272     }
11273 }
11274
11275 /* Add a typedef defined in the scope of the FIP's class.  */
11276
11277 static void
11278 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11279                     struct dwarf2_cu *cu)
11280 {
11281   struct objfile *objfile = cu->objfile;
11282   struct typedef_field_list *new_field;
11283   struct attribute *attr;
11284   struct typedef_field *fp;
11285   char *fieldname = "";
11286
11287   /* Allocate a new field list entry and link it in.  */
11288   new_field = xzalloc (sizeof (*new_field));
11289   make_cleanup (xfree, new_field);
11290
11291   gdb_assert (die->tag == DW_TAG_typedef);
11292
11293   fp = &new_field->field;
11294
11295   /* Get name of field.  */
11296   fp->name = dwarf2_name (die, cu);
11297   if (fp->name == NULL)
11298     return;
11299
11300   fp->type = read_type_die (die, cu);
11301
11302   new_field->next = fip->typedef_field_list;
11303   fip->typedef_field_list = new_field;
11304   fip->typedef_field_list_count++;
11305 }
11306
11307 /* Create the vector of fields, and attach it to the type.  */
11308
11309 static void
11310 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11311                               struct dwarf2_cu *cu)
11312 {
11313   int nfields = fip->nfields;
11314
11315   /* Record the field count, allocate space for the array of fields,
11316      and create blank accessibility bitfields if necessary.  */
11317   TYPE_NFIELDS (type) = nfields;
11318   TYPE_FIELDS (type) = (struct field *)
11319     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11320   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11321
11322   if (fip->non_public_fields && cu->language != language_ada)
11323     {
11324       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11325
11326       TYPE_FIELD_PRIVATE_BITS (type) =
11327         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11328       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11329
11330       TYPE_FIELD_PROTECTED_BITS (type) =
11331         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11332       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11333
11334       TYPE_FIELD_IGNORE_BITS (type) =
11335         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11336       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11337     }
11338
11339   /* If the type has baseclasses, allocate and clear a bit vector for
11340      TYPE_FIELD_VIRTUAL_BITS.  */
11341   if (fip->nbaseclasses && cu->language != language_ada)
11342     {
11343       int num_bytes = B_BYTES (fip->nbaseclasses);
11344       unsigned char *pointer;
11345
11346       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11347       pointer = TYPE_ALLOC (type, num_bytes);
11348       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11349       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11350       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11351     }
11352
11353   /* Copy the saved-up fields into the field vector.  Start from the head of
11354      the list, adding to the tail of the field array, so that they end up in
11355      the same order in the array in which they were added to the list.  */
11356   while (nfields-- > 0)
11357     {
11358       struct nextfield *fieldp;
11359
11360       if (fip->fields)
11361         {
11362           fieldp = fip->fields;
11363           fip->fields = fieldp->next;
11364         }
11365       else
11366         {
11367           fieldp = fip->baseclasses;
11368           fip->baseclasses = fieldp->next;
11369         }
11370
11371       TYPE_FIELD (type, nfields) = fieldp->field;
11372       switch (fieldp->accessibility)
11373         {
11374         case DW_ACCESS_private:
11375           if (cu->language != language_ada)
11376             SET_TYPE_FIELD_PRIVATE (type, nfields);
11377           break;
11378
11379         case DW_ACCESS_protected:
11380           if (cu->language != language_ada)
11381             SET_TYPE_FIELD_PROTECTED (type, nfields);
11382           break;
11383
11384         case DW_ACCESS_public:
11385           break;
11386
11387         default:
11388           /* Unknown accessibility.  Complain and treat it as public.  */
11389           {
11390             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11391                        fieldp->accessibility);
11392           }
11393           break;
11394         }
11395       if (nfields < fip->nbaseclasses)
11396         {
11397           switch (fieldp->virtuality)
11398             {
11399             case DW_VIRTUALITY_virtual:
11400             case DW_VIRTUALITY_pure_virtual:
11401               if (cu->language == language_ada)
11402                 error (_("unexpected virtuality in component of Ada type"));
11403               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11404               break;
11405             }
11406         }
11407     }
11408 }
11409
11410 /* Return true if this member function is a constructor, false
11411    otherwise.  */
11412
11413 static int
11414 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11415 {
11416   const char *fieldname;
11417   const char *typename;
11418   int len;
11419
11420   if (die->parent == NULL)
11421     return 0;
11422
11423   if (die->parent->tag != DW_TAG_structure_type
11424       && die->parent->tag != DW_TAG_union_type
11425       && die->parent->tag != DW_TAG_class_type)
11426     return 0;
11427
11428   fieldname = dwarf2_name (die, cu);
11429   typename = dwarf2_name (die->parent, cu);
11430   if (fieldname == NULL || typename == NULL)
11431     return 0;
11432
11433   len = strlen (fieldname);
11434   return (strncmp (fieldname, typename, len) == 0
11435           && (typename[len] == '\0' || typename[len] == '<'));
11436 }
11437
11438 /* Add a member function to the proper fieldlist.  */
11439
11440 static void
11441 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11442                       struct type *type, struct dwarf2_cu *cu)
11443 {
11444   struct objfile *objfile = cu->objfile;
11445   struct attribute *attr;
11446   struct fnfieldlist *flp;
11447   int i;
11448   struct fn_field *fnp;
11449   const char *fieldname;
11450   struct nextfnfield *new_fnfield;
11451   struct type *this_type;
11452   enum dwarf_access_attribute accessibility;
11453
11454   if (cu->language == language_ada)
11455     error (_("unexpected member function in Ada type"));
11456
11457   /* Get name of member function.  */
11458   fieldname = dwarf2_name (die, cu);
11459   if (fieldname == NULL)
11460     return;
11461
11462   /* Look up member function name in fieldlist.  */
11463   for (i = 0; i < fip->nfnfields; i++)
11464     {
11465       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11466         break;
11467     }
11468
11469   /* Create new list element if necessary.  */
11470   if (i < fip->nfnfields)
11471     flp = &fip->fnfieldlists[i];
11472   else
11473     {
11474       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11475         {
11476           fip->fnfieldlists = (struct fnfieldlist *)
11477             xrealloc (fip->fnfieldlists,
11478                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11479                       * sizeof (struct fnfieldlist));
11480           if (fip->nfnfields == 0)
11481             make_cleanup (free_current_contents, &fip->fnfieldlists);
11482         }
11483       flp = &fip->fnfieldlists[fip->nfnfields];
11484       flp->name = fieldname;
11485       flp->length = 0;
11486       flp->head = NULL;
11487       i = fip->nfnfields++;
11488     }
11489
11490   /* Create a new member function field and chain it to the field list
11491      entry.  */
11492   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11493   make_cleanup (xfree, new_fnfield);
11494   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11495   new_fnfield->next = flp->head;
11496   flp->head = new_fnfield;
11497   flp->length++;
11498
11499   /* Fill in the member function field info.  */
11500   fnp = &new_fnfield->fnfield;
11501
11502   /* Delay processing of the physname until later.  */
11503   if (cu->language == language_cplus || cu->language == language_java)
11504     {
11505       add_to_method_list (type, i, flp->length - 1, fieldname,
11506                           die, cu);
11507     }
11508   else
11509     {
11510       const char *physname = dwarf2_physname (fieldname, die, cu);
11511       fnp->physname = physname ? physname : "";
11512     }
11513
11514   fnp->type = alloc_type (objfile);
11515   this_type = read_type_die (die, cu);
11516   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11517     {
11518       int nparams = TYPE_NFIELDS (this_type);
11519
11520       /* TYPE is the domain of this method, and THIS_TYPE is the type
11521            of the method itself (TYPE_CODE_METHOD).  */
11522       smash_to_method_type (fnp->type, type,
11523                             TYPE_TARGET_TYPE (this_type),
11524                             TYPE_FIELDS (this_type),
11525                             TYPE_NFIELDS (this_type),
11526                             TYPE_VARARGS (this_type));
11527
11528       /* Handle static member functions.
11529          Dwarf2 has no clean way to discern C++ static and non-static
11530          member functions.  G++ helps GDB by marking the first
11531          parameter for non-static member functions (which is the this
11532          pointer) as artificial.  We obtain this information from
11533          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11534       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11535         fnp->voffset = VOFFSET_STATIC;
11536     }
11537   else
11538     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11539                dwarf2_full_name (fieldname, die, cu));
11540
11541   /* Get fcontext from DW_AT_containing_type if present.  */
11542   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11543     fnp->fcontext = die_containing_type (die, cu);
11544
11545   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11546      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11547
11548   /* Get accessibility.  */
11549   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11550   if (attr)
11551     accessibility = DW_UNSND (attr);
11552   else
11553     accessibility = dwarf2_default_access_attribute (die, cu);
11554   switch (accessibility)
11555     {
11556     case DW_ACCESS_private:
11557       fnp->is_private = 1;
11558       break;
11559     case DW_ACCESS_protected:
11560       fnp->is_protected = 1;
11561       break;
11562     }
11563
11564   /* Check for artificial methods.  */
11565   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11566   if (attr && DW_UNSND (attr) != 0)
11567     fnp->is_artificial = 1;
11568
11569   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11570
11571   /* Get index in virtual function table if it is a virtual member
11572      function.  For older versions of GCC, this is an offset in the
11573      appropriate virtual table, as specified by DW_AT_containing_type.
11574      For everyone else, it is an expression to be evaluated relative
11575      to the object address.  */
11576
11577   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11578   if (attr)
11579     {
11580       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11581         {
11582           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11583             {
11584               /* Old-style GCC.  */
11585               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11586             }
11587           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11588                    || (DW_BLOCK (attr)->size > 1
11589                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11590                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11591             {
11592               struct dwarf_block blk;
11593               int offset;
11594
11595               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11596                         ? 1 : 2);
11597               blk.size = DW_BLOCK (attr)->size - offset;
11598               blk.data = DW_BLOCK (attr)->data + offset;
11599               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11600               if ((fnp->voffset % cu->header.addr_size) != 0)
11601                 dwarf2_complex_location_expr_complaint ();
11602               else
11603                 fnp->voffset /= cu->header.addr_size;
11604               fnp->voffset += 2;
11605             }
11606           else
11607             dwarf2_complex_location_expr_complaint ();
11608
11609           if (!fnp->fcontext)
11610             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11611         }
11612       else if (attr_form_is_section_offset (attr))
11613         {
11614           dwarf2_complex_location_expr_complaint ();
11615         }
11616       else
11617         {
11618           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11619                                                  fieldname);
11620         }
11621     }
11622   else
11623     {
11624       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11625       if (attr && DW_UNSND (attr))
11626         {
11627           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11628           complaint (&symfile_complaints,
11629                      _("Member function \"%s\" (offset %d) is virtual "
11630                        "but the vtable offset is not specified"),
11631                      fieldname, die->offset.sect_off);
11632           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11633           TYPE_CPLUS_DYNAMIC (type) = 1;
11634         }
11635     }
11636 }
11637
11638 /* Create the vector of member function fields, and attach it to the type.  */
11639
11640 static void
11641 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11642                                  struct dwarf2_cu *cu)
11643 {
11644   struct fnfieldlist *flp;
11645   int i;
11646
11647   if (cu->language == language_ada)
11648     error (_("unexpected member functions in Ada type"));
11649
11650   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11651   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11652     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11653
11654   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11655     {
11656       struct nextfnfield *nfp = flp->head;
11657       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11658       int k;
11659
11660       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11661       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11662       fn_flp->fn_fields = (struct fn_field *)
11663         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11664       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11665         fn_flp->fn_fields[k] = nfp->fnfield;
11666     }
11667
11668   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11669 }
11670
11671 /* Returns non-zero if NAME is the name of a vtable member in CU's
11672    language, zero otherwise.  */
11673 static int
11674 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11675 {
11676   static const char vptr[] = "_vptr";
11677   static const char vtable[] = "vtable";
11678
11679   /* Look for the C++ and Java forms of the vtable.  */
11680   if ((cu->language == language_java
11681        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11682        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11683        && is_cplus_marker (name[sizeof (vptr) - 1])))
11684     return 1;
11685
11686   return 0;
11687 }
11688
11689 /* GCC outputs unnamed structures that are really pointers to member
11690    functions, with the ABI-specified layout.  If TYPE describes
11691    such a structure, smash it into a member function type.
11692
11693    GCC shouldn't do this; it should just output pointer to member DIEs.
11694    This is GCC PR debug/28767.  */
11695
11696 static void
11697 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11698 {
11699   struct type *pfn_type, *domain_type, *new_type;
11700
11701   /* Check for a structure with no name and two children.  */
11702   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11703     return;
11704
11705   /* Check for __pfn and __delta members.  */
11706   if (TYPE_FIELD_NAME (type, 0) == NULL
11707       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11708       || TYPE_FIELD_NAME (type, 1) == NULL
11709       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11710     return;
11711
11712   /* Find the type of the method.  */
11713   pfn_type = TYPE_FIELD_TYPE (type, 0);
11714   if (pfn_type == NULL
11715       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11716       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11717     return;
11718
11719   /* Look for the "this" argument.  */
11720   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11721   if (TYPE_NFIELDS (pfn_type) == 0
11722       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11723       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11724     return;
11725
11726   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11727   new_type = alloc_type (objfile);
11728   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11729                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11730                         TYPE_VARARGS (pfn_type));
11731   smash_to_methodptr_type (type, new_type);
11732 }
11733
11734 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11735    (icc).  */
11736
11737 static int
11738 producer_is_icc (struct dwarf2_cu *cu)
11739 {
11740   if (!cu->checked_producer)
11741     check_producer (cu);
11742
11743   return cu->producer_is_icc;
11744 }
11745
11746 /* Called when we find the DIE that starts a structure or union scope
11747    (definition) to create a type for the structure or union.  Fill in
11748    the type's name and general properties; the members will not be
11749    processed until process_structure_scope.
11750
11751    NOTE: we need to call these functions regardless of whether or not the
11752    DIE has a DW_AT_name attribute, since it might be an anonymous
11753    structure or union.  This gets the type entered into our set of
11754    user defined types.
11755
11756    However, if the structure is incomplete (an opaque struct/union)
11757    then suppress creating a symbol table entry for it since gdb only
11758    wants to find the one with the complete definition.  Note that if
11759    it is complete, we just call new_symbol, which does it's own
11760    checking about whether the struct/union is anonymous or not (and
11761    suppresses creating a symbol table entry itself).  */
11762
11763 static struct type *
11764 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11765 {
11766   struct objfile *objfile = cu->objfile;
11767   struct type *type;
11768   struct attribute *attr;
11769   const char *name;
11770
11771   /* If the definition of this type lives in .debug_types, read that type.
11772      Don't follow DW_AT_specification though, that will take us back up
11773      the chain and we want to go down.  */
11774   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11775   if (attr)
11776     {
11777       type = get_DW_AT_signature_type (die, attr, cu);
11778
11779       /* The type's CU may not be the same as CU.
11780          Ensure TYPE is recorded with CU in die_type_hash.  */
11781       return set_die_type (die, type, cu);
11782     }
11783
11784   type = alloc_type (objfile);
11785   INIT_CPLUS_SPECIFIC (type);
11786
11787   name = dwarf2_name (die, cu);
11788   if (name != NULL)
11789     {
11790       if (cu->language == language_cplus
11791           || cu->language == language_java)
11792         {
11793           const char *full_name = dwarf2_full_name (name, die, cu);
11794
11795           /* dwarf2_full_name might have already finished building the DIE's
11796              type.  If so, there is no need to continue.  */
11797           if (get_die_type (die, cu) != NULL)
11798             return get_die_type (die, cu);
11799
11800           TYPE_TAG_NAME (type) = full_name;
11801           if (die->tag == DW_TAG_structure_type
11802               || die->tag == DW_TAG_class_type)
11803             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11804         }
11805       else
11806         {
11807           /* The name is already allocated along with this objfile, so
11808              we don't need to duplicate it for the type.  */
11809           TYPE_TAG_NAME (type) = name;
11810           if (die->tag == DW_TAG_class_type)
11811             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11812         }
11813     }
11814
11815   if (die->tag == DW_TAG_structure_type)
11816     {
11817       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11818     }
11819   else if (die->tag == DW_TAG_union_type)
11820     {
11821       TYPE_CODE (type) = TYPE_CODE_UNION;
11822     }
11823   else
11824     {
11825       TYPE_CODE (type) = TYPE_CODE_CLASS;
11826     }
11827
11828   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11829     TYPE_DECLARED_CLASS (type) = 1;
11830
11831   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11832   if (attr)
11833     {
11834       TYPE_LENGTH (type) = DW_UNSND (attr);
11835     }
11836   else
11837     {
11838       TYPE_LENGTH (type) = 0;
11839     }
11840
11841   if (producer_is_icc (cu))
11842     {
11843       /* ICC does not output the required DW_AT_declaration
11844          on incomplete types, but gives them a size of zero.  */
11845     }
11846   else
11847     TYPE_STUB_SUPPORTED (type) = 1;
11848
11849   if (die_is_declaration (die, cu))
11850     TYPE_STUB (type) = 1;
11851   else if (attr == NULL && die->child == NULL
11852            && producer_is_realview (cu->producer))
11853     /* RealView does not output the required DW_AT_declaration
11854        on incomplete types.  */
11855     TYPE_STUB (type) = 1;
11856
11857   /* We need to add the type field to the die immediately so we don't
11858      infinitely recurse when dealing with pointers to the structure
11859      type within the structure itself.  */
11860   set_die_type (die, type, cu);
11861
11862   /* set_die_type should be already done.  */
11863   set_descriptive_type (type, die, cu);
11864
11865   return type;
11866 }
11867
11868 /* Finish creating a structure or union type, including filling in
11869    its members and creating a symbol for it.  */
11870
11871 static void
11872 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11873 {
11874   struct objfile *objfile = cu->objfile;
11875   struct die_info *child_die = die->child;
11876   struct type *type;
11877
11878   type = get_die_type (die, cu);
11879   if (type == NULL)
11880     type = read_structure_type (die, cu);
11881
11882   if (die->child != NULL && ! die_is_declaration (die, cu))
11883     {
11884       struct field_info fi;
11885       struct die_info *child_die;
11886       VEC (symbolp) *template_args = NULL;
11887       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11888
11889       memset (&fi, 0, sizeof (struct field_info));
11890
11891       child_die = die->child;
11892
11893       while (child_die && child_die->tag)
11894         {
11895           if (child_die->tag == DW_TAG_member
11896               || child_die->tag == DW_TAG_variable)
11897             {
11898               /* NOTE: carlton/2002-11-05: A C++ static data member
11899                  should be a DW_TAG_member that is a declaration, but
11900                  all versions of G++ as of this writing (so through at
11901                  least 3.2.1) incorrectly generate DW_TAG_variable
11902                  tags for them instead.  */
11903               dwarf2_add_field (&fi, child_die, cu);
11904             }
11905           else if (child_die->tag == DW_TAG_subprogram)
11906             {
11907               /* C++ member function.  */
11908               dwarf2_add_member_fn (&fi, child_die, type, cu);
11909             }
11910           else if (child_die->tag == DW_TAG_inheritance)
11911             {
11912               /* C++ base class field.  */
11913               dwarf2_add_field (&fi, child_die, cu);
11914             }
11915           else if (child_die->tag == DW_TAG_typedef)
11916             dwarf2_add_typedef (&fi, child_die, cu);
11917           else if (child_die->tag == DW_TAG_template_type_param
11918                    || child_die->tag == DW_TAG_template_value_param)
11919             {
11920               struct symbol *arg = new_symbol (child_die, NULL, cu);
11921
11922               if (arg != NULL)
11923                 VEC_safe_push (symbolp, template_args, arg);
11924             }
11925
11926           child_die = sibling_die (child_die);
11927         }
11928
11929       /* Attach template arguments to type.  */
11930       if (! VEC_empty (symbolp, template_args))
11931         {
11932           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11933           TYPE_N_TEMPLATE_ARGUMENTS (type)
11934             = VEC_length (symbolp, template_args);
11935           TYPE_TEMPLATE_ARGUMENTS (type)
11936             = obstack_alloc (&objfile->objfile_obstack,
11937                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11938                               * sizeof (struct symbol *)));
11939           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11940                   VEC_address (symbolp, template_args),
11941                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11942                    * sizeof (struct symbol *)));
11943           VEC_free (symbolp, template_args);
11944         }
11945
11946       /* Attach fields and member functions to the type.  */
11947       if (fi.nfields)
11948         dwarf2_attach_fields_to_type (&fi, type, cu);
11949       if (fi.nfnfields)
11950         {
11951           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11952
11953           /* Get the type which refers to the base class (possibly this
11954              class itself) which contains the vtable pointer for the current
11955              class from the DW_AT_containing_type attribute.  This use of
11956              DW_AT_containing_type is a GNU extension.  */
11957
11958           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11959             {
11960               struct type *t = die_containing_type (die, cu);
11961
11962               TYPE_VPTR_BASETYPE (type) = t;
11963               if (type == t)
11964                 {
11965                   int i;
11966
11967                   /* Our own class provides vtbl ptr.  */
11968                   for (i = TYPE_NFIELDS (t) - 1;
11969                        i >= TYPE_N_BASECLASSES (t);
11970                        --i)
11971                     {
11972                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11973
11974                       if (is_vtable_name (fieldname, cu))
11975                         {
11976                           TYPE_VPTR_FIELDNO (type) = i;
11977                           break;
11978                         }
11979                     }
11980
11981                   /* Complain if virtual function table field not found.  */
11982                   if (i < TYPE_N_BASECLASSES (t))
11983                     complaint (&symfile_complaints,
11984                                _("virtual function table pointer "
11985                                  "not found when defining class '%s'"),
11986                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11987                                "");
11988                 }
11989               else
11990                 {
11991                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11992                 }
11993             }
11994           else if (cu->producer
11995                    && strncmp (cu->producer,
11996                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11997             {
11998               /* The IBM XLC compiler does not provide direct indication
11999                  of the containing type, but the vtable pointer is
12000                  always named __vfp.  */
12001
12002               int i;
12003
12004               for (i = TYPE_NFIELDS (type) - 1;
12005                    i >= TYPE_N_BASECLASSES (type);
12006                    --i)
12007                 {
12008                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12009                     {
12010                       TYPE_VPTR_FIELDNO (type) = i;
12011                       TYPE_VPTR_BASETYPE (type) = type;
12012                       break;
12013                     }
12014                 }
12015             }
12016         }
12017
12018       /* Copy fi.typedef_field_list linked list elements content into the
12019          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12020       if (fi.typedef_field_list)
12021         {
12022           int i = fi.typedef_field_list_count;
12023
12024           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12025           TYPE_TYPEDEF_FIELD_ARRAY (type)
12026             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12027           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12028
12029           /* Reverse the list order to keep the debug info elements order.  */
12030           while (--i >= 0)
12031             {
12032               struct typedef_field *dest, *src;
12033
12034               dest = &TYPE_TYPEDEF_FIELD (type, i);
12035               src = &fi.typedef_field_list->field;
12036               fi.typedef_field_list = fi.typedef_field_list->next;
12037               *dest = *src;
12038             }
12039         }
12040
12041       do_cleanups (back_to);
12042
12043       if (HAVE_CPLUS_STRUCT (type))
12044         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12045     }
12046
12047   quirk_gcc_member_function_pointer (type, objfile);
12048
12049   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12050      snapshots) has been known to create a die giving a declaration
12051      for a class that has, as a child, a die giving a definition for a
12052      nested class.  So we have to process our children even if the
12053      current die is a declaration.  Normally, of course, a declaration
12054      won't have any children at all.  */
12055
12056   while (child_die != NULL && child_die->tag)
12057     {
12058       if (child_die->tag == DW_TAG_member
12059           || child_die->tag == DW_TAG_variable
12060           || child_die->tag == DW_TAG_inheritance
12061           || child_die->tag == DW_TAG_template_value_param
12062           || child_die->tag == DW_TAG_template_type_param)
12063         {
12064           /* Do nothing.  */
12065         }
12066       else
12067         process_die (child_die, cu);
12068
12069       child_die = sibling_die (child_die);
12070     }
12071
12072   /* Do not consider external references.  According to the DWARF standard,
12073      these DIEs are identified by the fact that they have no byte_size
12074      attribute, and a declaration attribute.  */
12075   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12076       || !die_is_declaration (die, cu))
12077     new_symbol (die, type, cu);
12078 }
12079
12080 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12081    complete the type's fields yet, or create any symbols.  */
12082
12083 static struct type *
12084 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12085 {
12086   struct objfile *objfile = cu->objfile;
12087   struct type *type;
12088   struct attribute *attr;
12089   const char *name;
12090
12091   /* If the definition of this type lives in .debug_types, read that type.
12092      Don't follow DW_AT_specification though, that will take us back up
12093      the chain and we want to go down.  */
12094   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12095   if (attr)
12096     {
12097       type = get_DW_AT_signature_type (die, attr, cu);
12098
12099       /* The type's CU may not be the same as CU.
12100          Ensure TYPE is recorded with CU in die_type_hash.  */
12101       return set_die_type (die, type, cu);
12102     }
12103
12104   type = alloc_type (objfile);
12105
12106   TYPE_CODE (type) = TYPE_CODE_ENUM;
12107   name = dwarf2_full_name (NULL, die, cu);
12108   if (name != NULL)
12109     TYPE_TAG_NAME (type) = name;
12110
12111   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12112   if (attr)
12113     {
12114       TYPE_LENGTH (type) = DW_UNSND (attr);
12115     }
12116   else
12117     {
12118       TYPE_LENGTH (type) = 0;
12119     }
12120
12121   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12122      declared as private in the package spec, and then defined only
12123      inside the package body.  Such types are known as Taft Amendment
12124      Types.  When another package uses such a type, an incomplete DIE
12125      may be generated by the compiler.  */
12126   if (die_is_declaration (die, cu))
12127     TYPE_STUB (type) = 1;
12128
12129   return set_die_type (die, type, cu);
12130 }
12131
12132 /* Given a pointer to a die which begins an enumeration, process all
12133    the dies that define the members of the enumeration, and create the
12134    symbol for the enumeration type.
12135
12136    NOTE: We reverse the order of the element list.  */
12137
12138 static void
12139 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12140 {
12141   struct type *this_type;
12142
12143   this_type = get_die_type (die, cu);
12144   if (this_type == NULL)
12145     this_type = read_enumeration_type (die, cu);
12146
12147   if (die->child != NULL)
12148     {
12149       struct die_info *child_die;
12150       struct symbol *sym;
12151       struct field *fields = NULL;
12152       int num_fields = 0;
12153       int unsigned_enum = 1;
12154       const char *name;
12155       int flag_enum = 1;
12156       ULONGEST mask = 0;
12157
12158       child_die = die->child;
12159       while (child_die && child_die->tag)
12160         {
12161           if (child_die->tag != DW_TAG_enumerator)
12162             {
12163               process_die (child_die, cu);
12164             }
12165           else
12166             {
12167               name = dwarf2_name (child_die, cu);
12168               if (name)
12169                 {
12170                   sym = new_symbol (child_die, this_type, cu);
12171                   if (SYMBOL_VALUE (sym) < 0)
12172                     {
12173                       unsigned_enum = 0;
12174                       flag_enum = 0;
12175                     }
12176                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12177                     flag_enum = 0;
12178                   else
12179                     mask |= SYMBOL_VALUE (sym);
12180
12181                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12182                     {
12183                       fields = (struct field *)
12184                         xrealloc (fields,
12185                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12186                                   * sizeof (struct field));
12187                     }
12188
12189                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12190                   FIELD_TYPE (fields[num_fields]) = NULL;
12191                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12192                   FIELD_BITSIZE (fields[num_fields]) = 0;
12193
12194                   num_fields++;
12195                 }
12196             }
12197
12198           child_die = sibling_die (child_die);
12199         }
12200
12201       if (num_fields)
12202         {
12203           TYPE_NFIELDS (this_type) = num_fields;
12204           TYPE_FIELDS (this_type) = (struct field *)
12205             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12206           memcpy (TYPE_FIELDS (this_type), fields,
12207                   sizeof (struct field) * num_fields);
12208           xfree (fields);
12209         }
12210       if (unsigned_enum)
12211         TYPE_UNSIGNED (this_type) = 1;
12212       if (flag_enum)
12213         TYPE_FLAG_ENUM (this_type) = 1;
12214     }
12215
12216   /* If we are reading an enum from a .debug_types unit, and the enum
12217      is a declaration, and the enum is not the signatured type in the
12218      unit, then we do not want to add a symbol for it.  Adding a
12219      symbol would in some cases obscure the true definition of the
12220      enum, giving users an incomplete type when the definition is
12221      actually available.  Note that we do not want to do this for all
12222      enums which are just declarations, because C++0x allows forward
12223      enum declarations.  */
12224   if (cu->per_cu->is_debug_types
12225       && die_is_declaration (die, cu))
12226     {
12227       struct signatured_type *sig_type;
12228
12229       sig_type = (struct signatured_type *) cu->per_cu;
12230       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12231       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12232         return;
12233     }
12234
12235   new_symbol (die, this_type, cu);
12236 }
12237
12238 /* Extract all information from a DW_TAG_array_type DIE and put it in
12239    the DIE's type field.  For now, this only handles one dimensional
12240    arrays.  */
12241
12242 static struct type *
12243 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12244 {
12245   struct objfile *objfile = cu->objfile;
12246   struct die_info *child_die;
12247   struct type *type;
12248   struct type *element_type, *range_type, *index_type;
12249   struct type **range_types = NULL;
12250   struct attribute *attr;
12251   int ndim = 0;
12252   struct cleanup *back_to;
12253   const char *name;
12254
12255   element_type = die_type (die, cu);
12256
12257   /* The die_type call above may have already set the type for this DIE.  */
12258   type = get_die_type (die, cu);
12259   if (type)
12260     return type;
12261
12262   /* Irix 6.2 native cc creates array types without children for
12263      arrays with unspecified length.  */
12264   if (die->child == NULL)
12265     {
12266       index_type = objfile_type (objfile)->builtin_int;
12267       range_type = create_range_type (NULL, index_type, 0, -1);
12268       type = create_array_type (NULL, element_type, range_type);
12269       return set_die_type (die, type, cu);
12270     }
12271
12272   back_to = make_cleanup (null_cleanup, NULL);
12273   child_die = die->child;
12274   while (child_die && child_die->tag)
12275     {
12276       if (child_die->tag == DW_TAG_subrange_type)
12277         {
12278           struct type *child_type = read_type_die (child_die, cu);
12279
12280           if (child_type != NULL)
12281             {
12282               /* The range type was succesfully read.  Save it for the
12283                  array type creation.  */
12284               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12285                 {
12286                   range_types = (struct type **)
12287                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12288                               * sizeof (struct type *));
12289                   if (ndim == 0)
12290                     make_cleanup (free_current_contents, &range_types);
12291                 }
12292               range_types[ndim++] = child_type;
12293             }
12294         }
12295       child_die = sibling_die (child_die);
12296     }
12297
12298   /* Dwarf2 dimensions are output from left to right, create the
12299      necessary array types in backwards order.  */
12300
12301   type = element_type;
12302
12303   if (read_array_order (die, cu) == DW_ORD_col_major)
12304     {
12305       int i = 0;
12306
12307       while (i < ndim)
12308         type = create_array_type (NULL, type, range_types[i++]);
12309     }
12310   else
12311     {
12312       while (ndim-- > 0)
12313         type = create_array_type (NULL, type, range_types[ndim]);
12314     }
12315
12316   /* Understand Dwarf2 support for vector types (like they occur on
12317      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12318      array type.  This is not part of the Dwarf2/3 standard yet, but a
12319      custom vendor extension.  The main difference between a regular
12320      array and the vector variant is that vectors are passed by value
12321      to functions.  */
12322   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12323   if (attr)
12324     make_vector_type (type);
12325
12326   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12327      implementation may choose to implement triple vectors using this
12328      attribute.  */
12329   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12330   if (attr)
12331     {
12332       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12333         TYPE_LENGTH (type) = DW_UNSND (attr);
12334       else
12335         complaint (&symfile_complaints,
12336                    _("DW_AT_byte_size for array type smaller "
12337                      "than the total size of elements"));
12338     }
12339
12340   name = dwarf2_name (die, cu);
12341   if (name)
12342     TYPE_NAME (type) = name;
12343
12344   /* Install the type in the die.  */
12345   set_die_type (die, type, cu);
12346
12347   /* set_die_type should be already done.  */
12348   set_descriptive_type (type, die, cu);
12349
12350   do_cleanups (back_to);
12351
12352   return type;
12353 }
12354
12355 static enum dwarf_array_dim_ordering
12356 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12357 {
12358   struct attribute *attr;
12359
12360   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12361
12362   if (attr) return DW_SND (attr);
12363
12364   /* GNU F77 is a special case, as at 08/2004 array type info is the
12365      opposite order to the dwarf2 specification, but data is still
12366      laid out as per normal fortran.
12367
12368      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12369      version checking.  */
12370
12371   if (cu->language == language_fortran
12372       && cu->producer && strstr (cu->producer, "GNU F77"))
12373     {
12374       return DW_ORD_row_major;
12375     }
12376
12377   switch (cu->language_defn->la_array_ordering)
12378     {
12379     case array_column_major:
12380       return DW_ORD_col_major;
12381     case array_row_major:
12382     default:
12383       return DW_ORD_row_major;
12384     };
12385 }
12386
12387 /* Extract all information from a DW_TAG_set_type DIE and put it in
12388    the DIE's type field.  */
12389
12390 static struct type *
12391 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12392 {
12393   struct type *domain_type, *set_type;
12394   struct attribute *attr;
12395
12396   domain_type = die_type (die, cu);
12397
12398   /* The die_type call above may have already set the type for this DIE.  */
12399   set_type = get_die_type (die, cu);
12400   if (set_type)
12401     return set_type;
12402
12403   set_type = create_set_type (NULL, domain_type);
12404
12405   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12406   if (attr)
12407     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12408
12409   return set_die_type (die, set_type, cu);
12410 }
12411
12412 /* A helper for read_common_block that creates a locexpr baton.
12413    SYM is the symbol which we are marking as computed.
12414    COMMON_DIE is the DIE for the common block.
12415    COMMON_LOC is the location expression attribute for the common
12416    block itself.
12417    MEMBER_LOC is the location expression attribute for the particular
12418    member of the common block that we are processing.
12419    CU is the CU from which the above come.  */
12420
12421 static void
12422 mark_common_block_symbol_computed (struct symbol *sym,
12423                                    struct die_info *common_die,
12424                                    struct attribute *common_loc,
12425                                    struct attribute *member_loc,
12426                                    struct dwarf2_cu *cu)
12427 {
12428   struct objfile *objfile = dwarf2_per_objfile->objfile;
12429   struct dwarf2_locexpr_baton *baton;
12430   gdb_byte *ptr;
12431   unsigned int cu_off;
12432   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12433   LONGEST offset = 0;
12434
12435   gdb_assert (common_loc && member_loc);
12436   gdb_assert (attr_form_is_block (common_loc));
12437   gdb_assert (attr_form_is_block (member_loc)
12438               || attr_form_is_constant (member_loc));
12439
12440   baton = obstack_alloc (&objfile->objfile_obstack,
12441                          sizeof (struct dwarf2_locexpr_baton));
12442   baton->per_cu = cu->per_cu;
12443   gdb_assert (baton->per_cu);
12444
12445   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12446
12447   if (attr_form_is_constant (member_loc))
12448     {
12449       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12450       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12451     }
12452   else
12453     baton->size += DW_BLOCK (member_loc)->size;
12454
12455   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12456   baton->data = ptr;
12457
12458   *ptr++ = DW_OP_call4;
12459   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12460   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12461   ptr += 4;
12462
12463   if (attr_form_is_constant (member_loc))
12464     {
12465       *ptr++ = DW_OP_addr;
12466       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12467       ptr += cu->header.addr_size;
12468     }
12469   else
12470     {
12471       /* We have to copy the data here, because DW_OP_call4 will only
12472          use a DW_AT_location attribute.  */
12473       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12474       ptr += DW_BLOCK (member_loc)->size;
12475     }
12476
12477   *ptr++ = DW_OP_plus;
12478   gdb_assert (ptr - baton->data == baton->size);
12479
12480   SYMBOL_LOCATION_BATON (sym) = baton;
12481   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12482 }
12483
12484 /* Create appropriate locally-scoped variables for all the
12485    DW_TAG_common_block entries.  Also create a struct common_block
12486    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12487    is used to sepate the common blocks name namespace from regular
12488    variable names.  */
12489
12490 static void
12491 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12492 {
12493   struct attribute *attr;
12494
12495   attr = dwarf2_attr (die, DW_AT_location, cu);
12496   if (attr)
12497     {
12498       /* Support the .debug_loc offsets.  */
12499       if (attr_form_is_block (attr))
12500         {
12501           /* Ok.  */
12502         }
12503       else if (attr_form_is_section_offset (attr))
12504         {
12505           dwarf2_complex_location_expr_complaint ();
12506           attr = NULL;
12507         }
12508       else
12509         {
12510           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12511                                                  "common block member");
12512           attr = NULL;
12513         }
12514     }
12515
12516   if (die->child != NULL)
12517     {
12518       struct objfile *objfile = cu->objfile;
12519       struct die_info *child_die;
12520       size_t n_entries = 0, size;
12521       struct common_block *common_block;
12522       struct symbol *sym;
12523
12524       for (child_die = die->child;
12525            child_die && child_die->tag;
12526            child_die = sibling_die (child_die))
12527         ++n_entries;
12528
12529       size = (sizeof (struct common_block)
12530               + (n_entries - 1) * sizeof (struct symbol *));
12531       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12532       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12533       common_block->n_entries = 0;
12534
12535       for (child_die = die->child;
12536            child_die && child_die->tag;
12537            child_die = sibling_die (child_die))
12538         {
12539           /* Create the symbol in the DW_TAG_common_block block in the current
12540              symbol scope.  */
12541           sym = new_symbol (child_die, NULL, cu);
12542           if (sym != NULL)
12543             {
12544               struct attribute *member_loc;
12545
12546               common_block->contents[common_block->n_entries++] = sym;
12547
12548               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12549                                         cu);
12550               if (member_loc)
12551                 {
12552                   /* GDB has handled this for a long time, but it is
12553                      not specified by DWARF.  It seems to have been
12554                      emitted by gfortran at least as recently as:
12555                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12556                   complaint (&symfile_complaints,
12557                              _("Variable in common block has "
12558                                "DW_AT_data_member_location "
12559                                "- DIE at 0x%x [in module %s]"),
12560                              child_die->offset.sect_off, cu->objfile->name);
12561
12562                   if (attr_form_is_section_offset (member_loc))
12563                     dwarf2_complex_location_expr_complaint ();
12564                   else if (attr_form_is_constant (member_loc)
12565                            || attr_form_is_block (member_loc))
12566                     {
12567                       if (attr)
12568                         mark_common_block_symbol_computed (sym, die, attr,
12569                                                            member_loc, cu);
12570                     }
12571                   else
12572                     dwarf2_complex_location_expr_complaint ();
12573                 }
12574             }
12575         }
12576
12577       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12578       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12579     }
12580 }
12581
12582 /* Create a type for a C++ namespace.  */
12583
12584 static struct type *
12585 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12586 {
12587   struct objfile *objfile = cu->objfile;
12588   const char *previous_prefix, *name;
12589   int is_anonymous;
12590   struct type *type;
12591
12592   /* For extensions, reuse the type of the original namespace.  */
12593   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12594     {
12595       struct die_info *ext_die;
12596       struct dwarf2_cu *ext_cu = cu;
12597
12598       ext_die = dwarf2_extension (die, &ext_cu);
12599       type = read_type_die (ext_die, ext_cu);
12600
12601       /* EXT_CU may not be the same as CU.
12602          Ensure TYPE is recorded with CU in die_type_hash.  */
12603       return set_die_type (die, type, cu);
12604     }
12605
12606   name = namespace_name (die, &is_anonymous, cu);
12607
12608   /* Now build the name of the current namespace.  */
12609
12610   previous_prefix = determine_prefix (die, cu);
12611   if (previous_prefix[0] != '\0')
12612     name = typename_concat (&objfile->objfile_obstack,
12613                             previous_prefix, name, 0, cu);
12614
12615   /* Create the type.  */
12616   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12617                     objfile);
12618   TYPE_NAME (type) = name;
12619   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12620
12621   return set_die_type (die, type, cu);
12622 }
12623
12624 /* Read a C++ namespace.  */
12625
12626 static void
12627 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12628 {
12629   struct objfile *objfile = cu->objfile;
12630   int is_anonymous;
12631
12632   /* Add a symbol associated to this if we haven't seen the namespace
12633      before.  Also, add a using directive if it's an anonymous
12634      namespace.  */
12635
12636   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12637     {
12638       struct type *type;
12639
12640       type = read_type_die (die, cu);
12641       new_symbol (die, type, cu);
12642
12643       namespace_name (die, &is_anonymous, cu);
12644       if (is_anonymous)
12645         {
12646           const char *previous_prefix = determine_prefix (die, cu);
12647
12648           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12649                                   NULL, NULL, 0, &objfile->objfile_obstack);
12650         }
12651     }
12652
12653   if (die->child != NULL)
12654     {
12655       struct die_info *child_die = die->child;
12656
12657       while (child_die && child_die->tag)
12658         {
12659           process_die (child_die, cu);
12660           child_die = sibling_die (child_die);
12661         }
12662     }
12663 }
12664
12665 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12666    imported module.  Still we need that type as local Fortran "use ... only"
12667    declaration imports depend on the created type in determine_prefix.  */
12668
12669 static struct type *
12670 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12671 {
12672   struct objfile *objfile = cu->objfile;
12673   const char *module_name;
12674   struct type *type;
12675
12676   module_name = dwarf2_name (die, cu);
12677   if (!module_name)
12678     complaint (&symfile_complaints,
12679                _("DW_TAG_module has no name, offset 0x%x"),
12680                die->offset.sect_off);
12681   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12682
12683   /* determine_prefix uses TYPE_TAG_NAME.  */
12684   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12685
12686   return set_die_type (die, type, cu);
12687 }
12688
12689 /* Read a Fortran module.  */
12690
12691 static void
12692 read_module (struct die_info *die, struct dwarf2_cu *cu)
12693 {
12694   struct die_info *child_die = die->child;
12695
12696   while (child_die && child_die->tag)
12697     {
12698       process_die (child_die, cu);
12699       child_die = sibling_die (child_die);
12700     }
12701 }
12702
12703 /* Return the name of the namespace represented by DIE.  Set
12704    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12705    namespace.  */
12706
12707 static const char *
12708 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12709 {
12710   struct die_info *current_die;
12711   const char *name = NULL;
12712
12713   /* Loop through the extensions until we find a name.  */
12714
12715   for (current_die = die;
12716        current_die != NULL;
12717        current_die = dwarf2_extension (die, &cu))
12718     {
12719       name = dwarf2_name (current_die, cu);
12720       if (name != NULL)
12721         break;
12722     }
12723
12724   /* Is it an anonymous namespace?  */
12725
12726   *is_anonymous = (name == NULL);
12727   if (*is_anonymous)
12728     name = CP_ANONYMOUS_NAMESPACE_STR;
12729
12730   return name;
12731 }
12732
12733 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12734    the user defined type vector.  */
12735
12736 static struct type *
12737 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12738 {
12739   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12740   struct comp_unit_head *cu_header = &cu->header;
12741   struct type *type;
12742   struct attribute *attr_byte_size;
12743   struct attribute *attr_address_class;
12744   int byte_size, addr_class;
12745   struct type *target_type;
12746
12747   target_type = die_type (die, cu);
12748
12749   /* The die_type call above may have already set the type for this DIE.  */
12750   type = get_die_type (die, cu);
12751   if (type)
12752     return type;
12753
12754   type = lookup_pointer_type (target_type);
12755
12756   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12757   if (attr_byte_size)
12758     byte_size = DW_UNSND (attr_byte_size);
12759   else
12760     byte_size = cu_header->addr_size;
12761
12762   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12763   if (attr_address_class)
12764     addr_class = DW_UNSND (attr_address_class);
12765   else
12766     addr_class = DW_ADDR_none;
12767
12768   /* If the pointer size or address class is different than the
12769      default, create a type variant marked as such and set the
12770      length accordingly.  */
12771   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12772     {
12773       if (gdbarch_address_class_type_flags_p (gdbarch))
12774         {
12775           int type_flags;
12776
12777           type_flags = gdbarch_address_class_type_flags
12778                          (gdbarch, byte_size, addr_class);
12779           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12780                       == 0);
12781           type = make_type_with_address_space (type, type_flags);
12782         }
12783       else if (TYPE_LENGTH (type) != byte_size)
12784         {
12785           complaint (&symfile_complaints,
12786                      _("invalid pointer size %d"), byte_size);
12787         }
12788       else
12789         {
12790           /* Should we also complain about unhandled address classes?  */
12791         }
12792     }
12793
12794   TYPE_LENGTH (type) = byte_size;
12795   return set_die_type (die, type, cu);
12796 }
12797
12798 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12799    the user defined type vector.  */
12800
12801 static struct type *
12802 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12803 {
12804   struct type *type;
12805   struct type *to_type;
12806   struct type *domain;
12807
12808   to_type = die_type (die, cu);
12809   domain = die_containing_type (die, cu);
12810
12811   /* The calls above may have already set the type for this DIE.  */
12812   type = get_die_type (die, cu);
12813   if (type)
12814     return type;
12815
12816   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12817     type = lookup_methodptr_type (to_type);
12818   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12819     {
12820       struct type *new_type = alloc_type (cu->objfile);
12821
12822       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12823                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12824                             TYPE_VARARGS (to_type));
12825       type = lookup_methodptr_type (new_type);
12826     }
12827   else
12828     type = lookup_memberptr_type (to_type, domain);
12829
12830   return set_die_type (die, type, cu);
12831 }
12832
12833 /* Extract all information from a DW_TAG_reference_type DIE and add to
12834    the user defined type vector.  */
12835
12836 static struct type *
12837 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12838 {
12839   struct comp_unit_head *cu_header = &cu->header;
12840   struct type *type, *target_type;
12841   struct attribute *attr;
12842
12843   target_type = die_type (die, cu);
12844
12845   /* The die_type call above may have already set the type for this DIE.  */
12846   type = get_die_type (die, cu);
12847   if (type)
12848     return type;
12849
12850   type = lookup_reference_type (target_type);
12851   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12852   if (attr)
12853     {
12854       TYPE_LENGTH (type) = DW_UNSND (attr);
12855     }
12856   else
12857     {
12858       TYPE_LENGTH (type) = cu_header->addr_size;
12859     }
12860   return set_die_type (die, type, cu);
12861 }
12862
12863 static struct type *
12864 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12865 {
12866   struct type *base_type, *cv_type;
12867
12868   base_type = die_type (die, cu);
12869
12870   /* The die_type call above may have already set the type for this DIE.  */
12871   cv_type = get_die_type (die, cu);
12872   if (cv_type)
12873     return cv_type;
12874
12875   /* In case the const qualifier is applied to an array type, the element type
12876      is so qualified, not the array type (section 6.7.3 of C99).  */
12877   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12878     {
12879       struct type *el_type, *inner_array;
12880
12881       base_type = copy_type (base_type);
12882       inner_array = base_type;
12883
12884       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12885         {
12886           TYPE_TARGET_TYPE (inner_array) =
12887             copy_type (TYPE_TARGET_TYPE (inner_array));
12888           inner_array = TYPE_TARGET_TYPE (inner_array);
12889         }
12890
12891       el_type = TYPE_TARGET_TYPE (inner_array);
12892       TYPE_TARGET_TYPE (inner_array) =
12893         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12894
12895       return set_die_type (die, base_type, cu);
12896     }
12897
12898   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12899   return set_die_type (die, cv_type, cu);
12900 }
12901
12902 static struct type *
12903 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12904 {
12905   struct type *base_type, *cv_type;
12906
12907   base_type = die_type (die, cu);
12908
12909   /* The die_type call above may have already set the type for this DIE.  */
12910   cv_type = get_die_type (die, cu);
12911   if (cv_type)
12912     return cv_type;
12913
12914   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12915   return set_die_type (die, cv_type, cu);
12916 }
12917
12918 /* Handle DW_TAG_restrict_type.  */
12919
12920 static struct type *
12921 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12922 {
12923   struct type *base_type, *cv_type;
12924
12925   base_type = die_type (die, cu);
12926
12927   /* The die_type call above may have already set the type for this DIE.  */
12928   cv_type = get_die_type (die, cu);
12929   if (cv_type)
12930     return cv_type;
12931
12932   cv_type = make_restrict_type (base_type);
12933   return set_die_type (die, cv_type, cu);
12934 }
12935
12936 /* Extract all information from a DW_TAG_string_type DIE and add to
12937    the user defined type vector.  It isn't really a user defined type,
12938    but it behaves like one, with other DIE's using an AT_user_def_type
12939    attribute to reference it.  */
12940
12941 static struct type *
12942 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12943 {
12944   struct objfile *objfile = cu->objfile;
12945   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12946   struct type *type, *range_type, *index_type, *char_type;
12947   struct attribute *attr;
12948   unsigned int length;
12949
12950   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12951   if (attr)
12952     {
12953       length = DW_UNSND (attr);
12954     }
12955   else
12956     {
12957       /* Check for the DW_AT_byte_size attribute.  */
12958       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12959       if (attr)
12960         {
12961           length = DW_UNSND (attr);
12962         }
12963       else
12964         {
12965           length = 1;
12966         }
12967     }
12968
12969   index_type = objfile_type (objfile)->builtin_int;
12970   range_type = create_range_type (NULL, index_type, 1, length);
12971   char_type = language_string_char_type (cu->language_defn, gdbarch);
12972   type = create_string_type (NULL, char_type, range_type);
12973
12974   return set_die_type (die, type, cu);
12975 }
12976
12977 /* Assuming that DIE corresponds to a function, returns nonzero
12978    if the function is prototyped.  */
12979
12980 static int
12981 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
12982 {
12983   struct attribute *attr;
12984
12985   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12986   if (attr && (DW_UNSND (attr) != 0))
12987     return 1;
12988
12989   /* The DWARF standard implies that the DW_AT_prototyped attribute
12990      is only meaninful for C, but the concept also extends to other
12991      languages that allow unprototyped functions (Eg: Objective C).
12992      For all other languages, assume that functions are always
12993      prototyped.  */
12994   if (cu->language != language_c
12995       && cu->language != language_objc
12996       && cu->language != language_opencl)
12997     return 1;
12998
12999   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13000      prototyped and unprototyped functions; default to prototyped,
13001      since that is more common in modern code (and RealView warns
13002      about unprototyped functions).  */
13003   if (producer_is_realview (cu->producer))
13004     return 1;
13005
13006   return 0;
13007 }
13008
13009 /* Handle DIES due to C code like:
13010
13011    struct foo
13012    {
13013    int (*funcp)(int a, long l);
13014    int b;
13015    };
13016
13017    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13018
13019 static struct type *
13020 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13021 {
13022   struct objfile *objfile = cu->objfile;
13023   struct type *type;            /* Type that this function returns.  */
13024   struct type *ftype;           /* Function that returns above type.  */
13025   struct attribute *attr;
13026
13027   type = die_type (die, cu);
13028
13029   /* The die_type call above may have already set the type for this DIE.  */
13030   ftype = get_die_type (die, cu);
13031   if (ftype)
13032     return ftype;
13033
13034   ftype = lookup_function_type (type);
13035
13036   if (prototyped_function_p (die, cu))
13037     TYPE_PROTOTYPED (ftype) = 1;
13038
13039   /* Store the calling convention in the type if it's available in
13040      the subroutine die.  Otherwise set the calling convention to
13041      the default value DW_CC_normal.  */
13042   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13043   if (attr)
13044     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13045   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13046     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13047   else
13048     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13049
13050   /* We need to add the subroutine type to the die immediately so
13051      we don't infinitely recurse when dealing with parameters
13052      declared as the same subroutine type.  */
13053   set_die_type (die, ftype, cu);
13054
13055   if (die->child != NULL)
13056     {
13057       struct type *void_type = objfile_type (objfile)->builtin_void;
13058       struct die_info *child_die;
13059       int nparams, iparams;
13060
13061       /* Count the number of parameters.
13062          FIXME: GDB currently ignores vararg functions, but knows about
13063          vararg member functions.  */
13064       nparams = 0;
13065       child_die = die->child;
13066       while (child_die && child_die->tag)
13067         {
13068           if (child_die->tag == DW_TAG_formal_parameter)
13069             nparams++;
13070           else if (child_die->tag == DW_TAG_unspecified_parameters)
13071             TYPE_VARARGS (ftype) = 1;
13072           child_die = sibling_die (child_die);
13073         }
13074
13075       /* Allocate storage for parameters and fill them in.  */
13076       TYPE_NFIELDS (ftype) = nparams;
13077       TYPE_FIELDS (ftype) = (struct field *)
13078         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13079
13080       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13081          even if we error out during the parameters reading below.  */
13082       for (iparams = 0; iparams < nparams; iparams++)
13083         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13084
13085       iparams = 0;
13086       child_die = die->child;
13087       while (child_die && child_die->tag)
13088         {
13089           if (child_die->tag == DW_TAG_formal_parameter)
13090             {
13091               struct type *arg_type;
13092
13093               /* DWARF version 2 has no clean way to discern C++
13094                  static and non-static member functions.  G++ helps
13095                  GDB by marking the first parameter for non-static
13096                  member functions (which is the this pointer) as
13097                  artificial.  We pass this information to
13098                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13099
13100                  DWARF version 3 added DW_AT_object_pointer, which GCC
13101                  4.5 does not yet generate.  */
13102               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13103               if (attr)
13104                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13105               else
13106                 {
13107                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13108
13109                   /* GCC/43521: In java, the formal parameter
13110                      "this" is sometimes not marked with DW_AT_artificial.  */
13111                   if (cu->language == language_java)
13112                     {
13113                       const char *name = dwarf2_name (child_die, cu);
13114
13115                       if (name && !strcmp (name, "this"))
13116                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13117                     }
13118                 }
13119               arg_type = die_type (child_die, cu);
13120
13121               /* RealView does not mark THIS as const, which the testsuite
13122                  expects.  GCC marks THIS as const in method definitions,
13123                  but not in the class specifications (GCC PR 43053).  */
13124               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13125                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13126                 {
13127                   int is_this = 0;
13128                   struct dwarf2_cu *arg_cu = cu;
13129                   const char *name = dwarf2_name (child_die, cu);
13130
13131                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13132                   if (attr)
13133                     {
13134                       /* If the compiler emits this, use it.  */
13135                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13136                         is_this = 1;
13137                     }
13138                   else if (name && strcmp (name, "this") == 0)
13139                     /* Function definitions will have the argument names.  */
13140                     is_this = 1;
13141                   else if (name == NULL && iparams == 0)
13142                     /* Declarations may not have the names, so like
13143                        elsewhere in GDB, assume an artificial first
13144                        argument is "this".  */
13145                     is_this = 1;
13146
13147                   if (is_this)
13148                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13149                                              arg_type, 0);
13150                 }
13151
13152               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13153               iparams++;
13154             }
13155           child_die = sibling_die (child_die);
13156         }
13157     }
13158
13159   return ftype;
13160 }
13161
13162 static struct type *
13163 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13164 {
13165   struct objfile *objfile = cu->objfile;
13166   const char *name = NULL;
13167   struct type *this_type, *target_type;
13168
13169   name = dwarf2_full_name (NULL, die, cu);
13170   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13171                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13172   TYPE_NAME (this_type) = name;
13173   set_die_type (die, this_type, cu);
13174   target_type = die_type (die, cu);
13175   if (target_type != this_type)
13176     TYPE_TARGET_TYPE (this_type) = target_type;
13177   else
13178     {
13179       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13180          spec and cause infinite loops in GDB.  */
13181       complaint (&symfile_complaints,
13182                  _("Self-referential DW_TAG_typedef "
13183                    "- DIE at 0x%x [in module %s]"),
13184                  die->offset.sect_off, objfile->name);
13185       TYPE_TARGET_TYPE (this_type) = NULL;
13186     }
13187   return this_type;
13188 }
13189
13190 /* Find a representation of a given base type and install
13191    it in the TYPE field of the die.  */
13192
13193 static struct type *
13194 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13195 {
13196   struct objfile *objfile = cu->objfile;
13197   struct type *type;
13198   struct attribute *attr;
13199   int encoding = 0, size = 0;
13200   const char *name;
13201   enum type_code code = TYPE_CODE_INT;
13202   int type_flags = 0;
13203   struct type *target_type = NULL;
13204
13205   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13206   if (attr)
13207     {
13208       encoding = DW_UNSND (attr);
13209     }
13210   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13211   if (attr)
13212     {
13213       size = DW_UNSND (attr);
13214     }
13215   name = dwarf2_name (die, cu);
13216   if (!name)
13217     {
13218       complaint (&symfile_complaints,
13219                  _("DW_AT_name missing from DW_TAG_base_type"));
13220     }
13221
13222   switch (encoding)
13223     {
13224       case DW_ATE_address:
13225         /* Turn DW_ATE_address into a void * pointer.  */
13226         code = TYPE_CODE_PTR;
13227         type_flags |= TYPE_FLAG_UNSIGNED;
13228         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13229         break;
13230       case DW_ATE_boolean:
13231         code = TYPE_CODE_BOOL;
13232         type_flags |= TYPE_FLAG_UNSIGNED;
13233         break;
13234       case DW_ATE_complex_float:
13235         code = TYPE_CODE_COMPLEX;
13236         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13237         break;
13238       case DW_ATE_decimal_float:
13239         code = TYPE_CODE_DECFLOAT;
13240         break;
13241       case DW_ATE_float:
13242         code = TYPE_CODE_FLT;
13243         break;
13244       case DW_ATE_signed:
13245         break;
13246       case DW_ATE_unsigned:
13247         type_flags |= TYPE_FLAG_UNSIGNED;
13248         if (cu->language == language_fortran
13249             && name
13250             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13251           code = TYPE_CODE_CHAR;
13252         break;
13253       case DW_ATE_signed_char:
13254         if (cu->language == language_ada || cu->language == language_m2
13255             || cu->language == language_pascal
13256             || cu->language == language_fortran)
13257           code = TYPE_CODE_CHAR;
13258         break;
13259       case DW_ATE_unsigned_char:
13260         if (cu->language == language_ada || cu->language == language_m2
13261             || cu->language == language_pascal
13262             || cu->language == language_fortran)
13263           code = TYPE_CODE_CHAR;
13264         type_flags |= TYPE_FLAG_UNSIGNED;
13265         break;
13266       case DW_ATE_UTF:
13267         /* We just treat this as an integer and then recognize the
13268            type by name elsewhere.  */
13269         break;
13270
13271       default:
13272         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13273                    dwarf_type_encoding_name (encoding));
13274         break;
13275     }
13276
13277   type = init_type (code, size, type_flags, NULL, objfile);
13278   TYPE_NAME (type) = name;
13279   TYPE_TARGET_TYPE (type) = target_type;
13280
13281   if (name && strcmp (name, "char") == 0)
13282     TYPE_NOSIGN (type) = 1;
13283
13284   return set_die_type (die, type, cu);
13285 }
13286
13287 /* Read the given DW_AT_subrange DIE.  */
13288
13289 static struct type *
13290 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13291 {
13292   struct type *base_type, *orig_base_type;
13293   struct type *range_type;
13294   struct attribute *attr;
13295   LONGEST low, high;
13296   int low_default_is_valid;
13297   const char *name;
13298   LONGEST negative_mask;
13299
13300   orig_base_type = die_type (die, cu);
13301   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13302      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13303      creating the range type, but we use the result of check_typedef
13304      when examining properties of the type.  */
13305   base_type = check_typedef (orig_base_type);
13306
13307   /* The die_type call above may have already set the type for this DIE.  */
13308   range_type = get_die_type (die, cu);
13309   if (range_type)
13310     return range_type;
13311
13312   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13313      omitting DW_AT_lower_bound.  */
13314   switch (cu->language)
13315     {
13316     case language_c:
13317     case language_cplus:
13318       low = 0;
13319       low_default_is_valid = 1;
13320       break;
13321     case language_fortran:
13322       low = 1;
13323       low_default_is_valid = 1;
13324       break;
13325     case language_d:
13326     case language_java:
13327     case language_objc:
13328       low = 0;
13329       low_default_is_valid = (cu->header.version >= 4);
13330       break;
13331     case language_ada:
13332     case language_m2:
13333     case language_pascal:
13334       low = 1;
13335       low_default_is_valid = (cu->header.version >= 4);
13336       break;
13337     default:
13338       low = 0;
13339       low_default_is_valid = 0;
13340       break;
13341     }
13342
13343   /* FIXME: For variable sized arrays either of these could be
13344      a variable rather than a constant value.  We'll allow it,
13345      but we don't know how to handle it.  */
13346   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13347   if (attr)
13348     low = dwarf2_get_attr_constant_value (attr, low);
13349   else if (!low_default_is_valid)
13350     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13351                                       "- DIE at 0x%x [in module %s]"),
13352                die->offset.sect_off, cu->objfile->name);
13353
13354   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13355   if (attr)
13356     {
13357       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
13358         {
13359           /* GCC encodes arrays with unspecified or dynamic length
13360              with a DW_FORM_block1 attribute or a reference attribute.
13361              FIXME: GDB does not yet know how to handle dynamic
13362              arrays properly, treat them as arrays with unspecified
13363              length for now.
13364
13365              FIXME: jimb/2003-09-22: GDB does not really know
13366              how to handle arrays of unspecified length
13367              either; we just represent them as zero-length
13368              arrays.  Choose an appropriate upper bound given
13369              the lower bound we've computed above.  */
13370           high = low - 1;
13371         }
13372       else
13373         high = dwarf2_get_attr_constant_value (attr, 1);
13374     }
13375   else
13376     {
13377       attr = dwarf2_attr (die, DW_AT_count, cu);
13378       if (attr)
13379         {
13380           int count = dwarf2_get_attr_constant_value (attr, 1);
13381           high = low + count - 1;
13382         }
13383       else
13384         {
13385           /* Unspecified array length.  */
13386           high = low - 1;
13387         }
13388     }
13389
13390   /* Dwarf-2 specifications explicitly allows to create subrange types
13391      without specifying a base type.
13392      In that case, the base type must be set to the type of
13393      the lower bound, upper bound or count, in that order, if any of these
13394      three attributes references an object that has a type.
13395      If no base type is found, the Dwarf-2 specifications say that
13396      a signed integer type of size equal to the size of an address should
13397      be used.
13398      For the following C code: `extern char gdb_int [];'
13399      GCC produces an empty range DIE.
13400      FIXME: muller/2010-05-28: Possible references to object for low bound,
13401      high bound or count are not yet handled by this code.  */
13402   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13403     {
13404       struct objfile *objfile = cu->objfile;
13405       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13406       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13407       struct type *int_type = objfile_type (objfile)->builtin_int;
13408
13409       /* Test "int", "long int", and "long long int" objfile types,
13410          and select the first one having a size above or equal to the
13411          architecture address size.  */
13412       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13413         base_type = int_type;
13414       else
13415         {
13416           int_type = objfile_type (objfile)->builtin_long;
13417           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13418             base_type = int_type;
13419           else
13420             {
13421               int_type = objfile_type (objfile)->builtin_long_long;
13422               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13423                 base_type = int_type;
13424             }
13425         }
13426     }
13427
13428   negative_mask =
13429     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13430   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13431     low |= negative_mask;
13432   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13433     high |= negative_mask;
13434
13435   range_type = create_range_type (NULL, orig_base_type, low, high);
13436
13437   /* Mark arrays with dynamic length at least as an array of unspecified
13438      length.  GDB could check the boundary but before it gets implemented at
13439      least allow accessing the array elements.  */
13440   if (attr && attr_form_is_block (attr))
13441     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13442
13443   /* Ada expects an empty array on no boundary attributes.  */
13444   if (attr == NULL && cu->language != language_ada)
13445     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13446
13447   name = dwarf2_name (die, cu);
13448   if (name)
13449     TYPE_NAME (range_type) = name;
13450
13451   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13452   if (attr)
13453     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13454
13455   set_die_type (die, range_type, cu);
13456
13457   /* set_die_type should be already done.  */
13458   set_descriptive_type (range_type, die, cu);
13459
13460   return range_type;
13461 }
13462
13463 static struct type *
13464 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13465 {
13466   struct type *type;
13467
13468   /* For now, we only support the C meaning of an unspecified type: void.  */
13469
13470   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13471   TYPE_NAME (type) = dwarf2_name (die, cu);
13472
13473   return set_die_type (die, type, cu);
13474 }
13475
13476 /* Read a single die and all its descendents.  Set the die's sibling
13477    field to NULL; set other fields in the die correctly, and set all
13478    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13479    location of the info_ptr after reading all of those dies.  PARENT
13480    is the parent of the die in question.  */
13481
13482 static struct die_info *
13483 read_die_and_children (const struct die_reader_specs *reader,
13484                        const gdb_byte *info_ptr,
13485                        const gdb_byte **new_info_ptr,
13486                        struct die_info *parent)
13487 {
13488   struct die_info *die;
13489   const gdb_byte *cur_ptr;
13490   int has_children;
13491
13492   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13493   if (die == NULL)
13494     {
13495       *new_info_ptr = cur_ptr;
13496       return NULL;
13497     }
13498   store_in_ref_table (die, reader->cu);
13499
13500   if (has_children)
13501     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13502   else
13503     {
13504       die->child = NULL;
13505       *new_info_ptr = cur_ptr;
13506     }
13507
13508   die->sibling = NULL;
13509   die->parent = parent;
13510   return die;
13511 }
13512
13513 /* Read a die, all of its descendents, and all of its siblings; set
13514    all of the fields of all of the dies correctly.  Arguments are as
13515    in read_die_and_children.  */
13516
13517 static struct die_info *
13518 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13519                          const gdb_byte *info_ptr,
13520                          const gdb_byte **new_info_ptr,
13521                          struct die_info *parent)
13522 {
13523   struct die_info *first_die, *last_sibling;
13524   const gdb_byte *cur_ptr;
13525
13526   cur_ptr = info_ptr;
13527   first_die = last_sibling = NULL;
13528
13529   while (1)
13530     {
13531       struct die_info *die
13532         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13533
13534       if (die == NULL)
13535         {
13536           *new_info_ptr = cur_ptr;
13537           return first_die;
13538         }
13539
13540       if (!first_die)
13541         first_die = die;
13542       else
13543         last_sibling->sibling = die;
13544
13545       last_sibling = die;
13546     }
13547 }
13548
13549 /* Read a die, all of its descendents, and all of its siblings; set
13550    all of the fields of all of the dies correctly.  Arguments are as
13551    in read_die_and_children.
13552    This the main entry point for reading a DIE and all its children.  */
13553
13554 static struct die_info *
13555 read_die_and_siblings (const struct die_reader_specs *reader,
13556                        const gdb_byte *info_ptr,
13557                        const gdb_byte **new_info_ptr,
13558                        struct die_info *parent)
13559 {
13560   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13561                                                   new_info_ptr, parent);
13562
13563   if (dwarf2_die_debug)
13564     {
13565       fprintf_unfiltered (gdb_stdlog,
13566                           "Read die from %s@0x%x of %s:\n",
13567                           bfd_section_name (reader->abfd,
13568                                             reader->die_section->asection),
13569                           (unsigned) (info_ptr - reader->die_section->buffer),
13570                           bfd_get_filename (reader->abfd));
13571       dump_die (die, dwarf2_die_debug);
13572     }
13573
13574   return die;
13575 }
13576
13577 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13578    attributes.
13579    The caller is responsible for filling in the extra attributes
13580    and updating (*DIEP)->num_attrs.
13581    Set DIEP to point to a newly allocated die with its information,
13582    except for its child, sibling, and parent fields.
13583    Set HAS_CHILDREN to tell whether the die has children or not.  */
13584
13585 static const gdb_byte *
13586 read_full_die_1 (const struct die_reader_specs *reader,
13587                  struct die_info **diep, const gdb_byte *info_ptr,
13588                  int *has_children, int num_extra_attrs)
13589 {
13590   unsigned int abbrev_number, bytes_read, i;
13591   sect_offset offset;
13592   struct abbrev_info *abbrev;
13593   struct die_info *die;
13594   struct dwarf2_cu *cu = reader->cu;
13595   bfd *abfd = reader->abfd;
13596
13597   offset.sect_off = info_ptr - reader->buffer;
13598   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13599   info_ptr += bytes_read;
13600   if (!abbrev_number)
13601     {
13602       *diep = NULL;
13603       *has_children = 0;
13604       return info_ptr;
13605     }
13606
13607   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13608   if (!abbrev)
13609     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13610            abbrev_number,
13611            bfd_get_filename (abfd));
13612
13613   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13614   die->offset = offset;
13615   die->tag = abbrev->tag;
13616   die->abbrev = abbrev_number;
13617
13618   /* Make the result usable.
13619      The caller needs to update num_attrs after adding the extra
13620      attributes.  */
13621   die->num_attrs = abbrev->num_attrs;
13622
13623   for (i = 0; i < abbrev->num_attrs; ++i)
13624     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13625                                info_ptr);
13626
13627   *diep = die;
13628   *has_children = abbrev->has_children;
13629   return info_ptr;
13630 }
13631
13632 /* Read a die and all its attributes.
13633    Set DIEP to point to a newly allocated die with its information,
13634    except for its child, sibling, and parent fields.
13635    Set HAS_CHILDREN to tell whether the die has children or not.  */
13636
13637 static const gdb_byte *
13638 read_full_die (const struct die_reader_specs *reader,
13639                struct die_info **diep, const gdb_byte *info_ptr,
13640                int *has_children)
13641 {
13642   const gdb_byte *result;
13643
13644   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13645
13646   if (dwarf2_die_debug)
13647     {
13648       fprintf_unfiltered (gdb_stdlog,
13649                           "Read die from %s@0x%x of %s:\n",
13650                           bfd_section_name (reader->abfd,
13651                                             reader->die_section->asection),
13652                           (unsigned) (info_ptr - reader->die_section->buffer),
13653                           bfd_get_filename (reader->abfd));
13654       dump_die (*diep, dwarf2_die_debug);
13655     }
13656
13657   return result;
13658 }
13659 \f
13660 /* Abbreviation tables.
13661
13662    In DWARF version 2, the description of the debugging information is
13663    stored in a separate .debug_abbrev section.  Before we read any
13664    dies from a section we read in all abbreviations and install them
13665    in a hash table.  */
13666
13667 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13668
13669 static struct abbrev_info *
13670 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13671 {
13672   struct abbrev_info *abbrev;
13673
13674   abbrev = (struct abbrev_info *)
13675     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13676   memset (abbrev, 0, sizeof (struct abbrev_info));
13677   return abbrev;
13678 }
13679
13680 /* Add an abbreviation to the table.  */
13681
13682 static void
13683 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13684                          unsigned int abbrev_number,
13685                          struct abbrev_info *abbrev)
13686 {
13687   unsigned int hash_number;
13688
13689   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13690   abbrev->next = abbrev_table->abbrevs[hash_number];
13691   abbrev_table->abbrevs[hash_number] = abbrev;
13692 }
13693
13694 /* Look up an abbrev in the table.
13695    Returns NULL if the abbrev is not found.  */
13696
13697 static struct abbrev_info *
13698 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13699                             unsigned int abbrev_number)
13700 {
13701   unsigned int hash_number;
13702   struct abbrev_info *abbrev;
13703
13704   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13705   abbrev = abbrev_table->abbrevs[hash_number];
13706
13707   while (abbrev)
13708     {
13709       if (abbrev->number == abbrev_number)
13710         return abbrev;
13711       abbrev = abbrev->next;
13712     }
13713   return NULL;
13714 }
13715
13716 /* Read in an abbrev table.  */
13717
13718 static struct abbrev_table *
13719 abbrev_table_read_table (struct dwarf2_section_info *section,
13720                          sect_offset offset)
13721 {
13722   struct objfile *objfile = dwarf2_per_objfile->objfile;
13723   bfd *abfd = section->asection->owner;
13724   struct abbrev_table *abbrev_table;
13725   const gdb_byte *abbrev_ptr;
13726   struct abbrev_info *cur_abbrev;
13727   unsigned int abbrev_number, bytes_read, abbrev_name;
13728   unsigned int abbrev_form;
13729   struct attr_abbrev *cur_attrs;
13730   unsigned int allocated_attrs;
13731
13732   abbrev_table = XMALLOC (struct abbrev_table);
13733   abbrev_table->offset = offset;
13734   obstack_init (&abbrev_table->abbrev_obstack);
13735   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13736                                          (ABBREV_HASH_SIZE
13737                                           * sizeof (struct abbrev_info *)));
13738   memset (abbrev_table->abbrevs, 0,
13739           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13740
13741   dwarf2_read_section (objfile, section);
13742   abbrev_ptr = section->buffer + offset.sect_off;
13743   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13744   abbrev_ptr += bytes_read;
13745
13746   allocated_attrs = ATTR_ALLOC_CHUNK;
13747   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13748
13749   /* Loop until we reach an abbrev number of 0.  */
13750   while (abbrev_number)
13751     {
13752       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13753
13754       /* read in abbrev header */
13755       cur_abbrev->number = abbrev_number;
13756       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13757       abbrev_ptr += bytes_read;
13758       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13759       abbrev_ptr += 1;
13760
13761       /* now read in declarations */
13762       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13763       abbrev_ptr += bytes_read;
13764       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13765       abbrev_ptr += bytes_read;
13766       while (abbrev_name)
13767         {
13768           if (cur_abbrev->num_attrs == allocated_attrs)
13769             {
13770               allocated_attrs += ATTR_ALLOC_CHUNK;
13771               cur_attrs
13772                 = xrealloc (cur_attrs, (allocated_attrs
13773                                         * sizeof (struct attr_abbrev)));
13774             }
13775
13776           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13777           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13778           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13779           abbrev_ptr += bytes_read;
13780           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13781           abbrev_ptr += bytes_read;
13782         }
13783
13784       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13785                                          (cur_abbrev->num_attrs
13786                                           * sizeof (struct attr_abbrev)));
13787       memcpy (cur_abbrev->attrs, cur_attrs,
13788               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13789
13790       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13791
13792       /* Get next abbreviation.
13793          Under Irix6 the abbreviations for a compilation unit are not
13794          always properly terminated with an abbrev number of 0.
13795          Exit loop if we encounter an abbreviation which we have
13796          already read (which means we are about to read the abbreviations
13797          for the next compile unit) or if the end of the abbreviation
13798          table is reached.  */
13799       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13800         break;
13801       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13802       abbrev_ptr += bytes_read;
13803       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13804         break;
13805     }
13806
13807   xfree (cur_attrs);
13808   return abbrev_table;
13809 }
13810
13811 /* Free the resources held by ABBREV_TABLE.  */
13812
13813 static void
13814 abbrev_table_free (struct abbrev_table *abbrev_table)
13815 {
13816   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13817   xfree (abbrev_table);
13818 }
13819
13820 /* Same as abbrev_table_free but as a cleanup.
13821    We pass in a pointer to the pointer to the table so that we can
13822    set the pointer to NULL when we're done.  It also simplifies
13823    build_type_unit_groups.  */
13824
13825 static void
13826 abbrev_table_free_cleanup (void *table_ptr)
13827 {
13828   struct abbrev_table **abbrev_table_ptr = table_ptr;
13829
13830   if (*abbrev_table_ptr != NULL)
13831     abbrev_table_free (*abbrev_table_ptr);
13832   *abbrev_table_ptr = NULL;
13833 }
13834
13835 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13836
13837 static void
13838 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13839                      struct dwarf2_section_info *abbrev_section)
13840 {
13841   cu->abbrev_table =
13842     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13843 }
13844
13845 /* Release the memory used by the abbrev table for a compilation unit.  */
13846
13847 static void
13848 dwarf2_free_abbrev_table (void *ptr_to_cu)
13849 {
13850   struct dwarf2_cu *cu = ptr_to_cu;
13851
13852   if (cu->abbrev_table != NULL)
13853     abbrev_table_free (cu->abbrev_table);
13854   /* Set this to NULL so that we SEGV if we try to read it later,
13855      and also because free_comp_unit verifies this is NULL.  */
13856   cu->abbrev_table = NULL;
13857 }
13858 \f
13859 /* Returns nonzero if TAG represents a type that we might generate a partial
13860    symbol for.  */
13861
13862 static int
13863 is_type_tag_for_partial (int tag)
13864 {
13865   switch (tag)
13866     {
13867 #if 0
13868     /* Some types that would be reasonable to generate partial symbols for,
13869        that we don't at present.  */
13870     case DW_TAG_array_type:
13871     case DW_TAG_file_type:
13872     case DW_TAG_ptr_to_member_type:
13873     case DW_TAG_set_type:
13874     case DW_TAG_string_type:
13875     case DW_TAG_subroutine_type:
13876 #endif
13877     case DW_TAG_base_type:
13878     case DW_TAG_class_type:
13879     case DW_TAG_interface_type:
13880     case DW_TAG_enumeration_type:
13881     case DW_TAG_structure_type:
13882     case DW_TAG_subrange_type:
13883     case DW_TAG_typedef:
13884     case DW_TAG_union_type:
13885       return 1;
13886     default:
13887       return 0;
13888     }
13889 }
13890
13891 /* Load all DIEs that are interesting for partial symbols into memory.  */
13892
13893 static struct partial_die_info *
13894 load_partial_dies (const struct die_reader_specs *reader,
13895                    const gdb_byte *info_ptr, int building_psymtab)
13896 {
13897   struct dwarf2_cu *cu = reader->cu;
13898   struct objfile *objfile = cu->objfile;
13899   struct partial_die_info *part_die;
13900   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13901   struct abbrev_info *abbrev;
13902   unsigned int bytes_read;
13903   unsigned int load_all = 0;
13904   int nesting_level = 1;
13905
13906   parent_die = NULL;
13907   last_die = NULL;
13908
13909   gdb_assert (cu->per_cu != NULL);
13910   if (cu->per_cu->load_all_dies)
13911     load_all = 1;
13912
13913   cu->partial_dies
13914     = htab_create_alloc_ex (cu->header.length / 12,
13915                             partial_die_hash,
13916                             partial_die_eq,
13917                             NULL,
13918                             &cu->comp_unit_obstack,
13919                             hashtab_obstack_allocate,
13920                             dummy_obstack_deallocate);
13921
13922   part_die = obstack_alloc (&cu->comp_unit_obstack,
13923                             sizeof (struct partial_die_info));
13924
13925   while (1)
13926     {
13927       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13928
13929       /* A NULL abbrev means the end of a series of children.  */
13930       if (abbrev == NULL)
13931         {
13932           if (--nesting_level == 0)
13933             {
13934               /* PART_DIE was probably the last thing allocated on the
13935                  comp_unit_obstack, so we could call obstack_free
13936                  here.  We don't do that because the waste is small,
13937                  and will be cleaned up when we're done with this
13938                  compilation unit.  This way, we're also more robust
13939                  against other users of the comp_unit_obstack.  */
13940               return first_die;
13941             }
13942           info_ptr += bytes_read;
13943           last_die = parent_die;
13944           parent_die = parent_die->die_parent;
13945           continue;
13946         }
13947
13948       /* Check for template arguments.  We never save these; if
13949          they're seen, we just mark the parent, and go on our way.  */
13950       if (parent_die != NULL
13951           && cu->language == language_cplus
13952           && (abbrev->tag == DW_TAG_template_type_param
13953               || abbrev->tag == DW_TAG_template_value_param))
13954         {
13955           parent_die->has_template_arguments = 1;
13956
13957           if (!load_all)
13958             {
13959               /* We don't need a partial DIE for the template argument.  */
13960               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13961               continue;
13962             }
13963         }
13964
13965       /* We only recurse into c++ subprograms looking for template arguments.
13966          Skip their other children.  */
13967       if (!load_all
13968           && cu->language == language_cplus
13969           && parent_die != NULL
13970           && parent_die->tag == DW_TAG_subprogram)
13971         {
13972           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13973           continue;
13974         }
13975
13976       /* Check whether this DIE is interesting enough to save.  Normally
13977          we would not be interested in members here, but there may be
13978          later variables referencing them via DW_AT_specification (for
13979          static members).  */
13980       if (!load_all
13981           && !is_type_tag_for_partial (abbrev->tag)
13982           && abbrev->tag != DW_TAG_constant
13983           && abbrev->tag != DW_TAG_enumerator
13984           && abbrev->tag != DW_TAG_subprogram
13985           && abbrev->tag != DW_TAG_lexical_block
13986           && abbrev->tag != DW_TAG_variable
13987           && abbrev->tag != DW_TAG_namespace
13988           && abbrev->tag != DW_TAG_module
13989           && abbrev->tag != DW_TAG_member
13990           && abbrev->tag != DW_TAG_imported_unit)
13991         {
13992           /* Otherwise we skip to the next sibling, if any.  */
13993           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13994           continue;
13995         }
13996
13997       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13998                                    info_ptr);
13999
14000       /* This two-pass algorithm for processing partial symbols has a
14001          high cost in cache pressure.  Thus, handle some simple cases
14002          here which cover the majority of C partial symbols.  DIEs
14003          which neither have specification tags in them, nor could have
14004          specification tags elsewhere pointing at them, can simply be
14005          processed and discarded.
14006
14007          This segment is also optional; scan_partial_symbols and
14008          add_partial_symbol will handle these DIEs if we chain
14009          them in normally.  When compilers which do not emit large
14010          quantities of duplicate debug information are more common,
14011          this code can probably be removed.  */
14012
14013       /* Any complete simple types at the top level (pretty much all
14014          of them, for a language without namespaces), can be processed
14015          directly.  */
14016       if (parent_die == NULL
14017           && part_die->has_specification == 0
14018           && part_die->is_declaration == 0
14019           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14020               || part_die->tag == DW_TAG_base_type
14021               || part_die->tag == DW_TAG_subrange_type))
14022         {
14023           if (building_psymtab && part_die->name != NULL)
14024             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14025                                  VAR_DOMAIN, LOC_TYPEDEF,
14026                                  &objfile->static_psymbols,
14027                                  0, (CORE_ADDR) 0, cu->language, objfile);
14028           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14029           continue;
14030         }
14031
14032       /* The exception for DW_TAG_typedef with has_children above is
14033          a workaround of GCC PR debug/47510.  In the case of this complaint
14034          type_name_no_tag_or_error will error on such types later.
14035
14036          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14037          it could not find the child DIEs referenced later, this is checked
14038          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14039
14040       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14041         complaint (&symfile_complaints,
14042                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14043                      "- DIE at 0x%x [in module %s]"),
14044                    part_die->offset.sect_off, objfile->name);
14045
14046       /* If we're at the second level, and we're an enumerator, and
14047          our parent has no specification (meaning possibly lives in a
14048          namespace elsewhere), then we can add the partial symbol now
14049          instead of queueing it.  */
14050       if (part_die->tag == DW_TAG_enumerator
14051           && parent_die != NULL
14052           && parent_die->die_parent == NULL
14053           && parent_die->tag == DW_TAG_enumeration_type
14054           && parent_die->has_specification == 0)
14055         {
14056           if (part_die->name == NULL)
14057             complaint (&symfile_complaints,
14058                        _("malformed enumerator DIE ignored"));
14059           else if (building_psymtab)
14060             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14061                                  VAR_DOMAIN, LOC_CONST,
14062                                  (cu->language == language_cplus
14063                                   || cu->language == language_java)
14064                                  ? &objfile->global_psymbols
14065                                  : &objfile->static_psymbols,
14066                                  0, (CORE_ADDR) 0, cu->language, objfile);
14067
14068           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14069           continue;
14070         }
14071
14072       /* We'll save this DIE so link it in.  */
14073       part_die->die_parent = parent_die;
14074       part_die->die_sibling = NULL;
14075       part_die->die_child = NULL;
14076
14077       if (last_die && last_die == parent_die)
14078         last_die->die_child = part_die;
14079       else if (last_die)
14080         last_die->die_sibling = part_die;
14081
14082       last_die = part_die;
14083
14084       if (first_die == NULL)
14085         first_die = part_die;
14086
14087       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14088          find interesting need to be in the hash table, because we
14089          also have the parent/sibling/child chains; only those that we
14090          might refer to by offset later during partial symbol reading.
14091
14092          For now this means things that might have be the target of a
14093          DW_AT_specification, DW_AT_abstract_origin, or
14094          DW_AT_extension.  DW_AT_extension will refer only to
14095          namespaces; DW_AT_abstract_origin refers to functions (and
14096          many things under the function DIE, but we do not recurse
14097          into function DIEs during partial symbol reading) and
14098          possibly variables as well; DW_AT_specification refers to
14099          declarations.  Declarations ought to have the DW_AT_declaration
14100          flag.  It happens that GCC forgets to put it in sometimes, but
14101          only for functions, not for types.
14102
14103          Adding more things than necessary to the hash table is harmless
14104          except for the performance cost.  Adding too few will result in
14105          wasted time in find_partial_die, when we reread the compilation
14106          unit with load_all_dies set.  */
14107
14108       if (load_all
14109           || abbrev->tag == DW_TAG_constant
14110           || abbrev->tag == DW_TAG_subprogram
14111           || abbrev->tag == DW_TAG_variable
14112           || abbrev->tag == DW_TAG_namespace
14113           || part_die->is_declaration)
14114         {
14115           void **slot;
14116
14117           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14118                                            part_die->offset.sect_off, INSERT);
14119           *slot = part_die;
14120         }
14121
14122       part_die = obstack_alloc (&cu->comp_unit_obstack,
14123                                 sizeof (struct partial_die_info));
14124
14125       /* For some DIEs we want to follow their children (if any).  For C
14126          we have no reason to follow the children of structures; for other
14127          languages we have to, so that we can get at method physnames
14128          to infer fully qualified class names, for DW_AT_specification,
14129          and for C++ template arguments.  For C++, we also look one level
14130          inside functions to find template arguments (if the name of the
14131          function does not already contain the template arguments).
14132
14133          For Ada, we need to scan the children of subprograms and lexical
14134          blocks as well because Ada allows the definition of nested
14135          entities that could be interesting for the debugger, such as
14136          nested subprograms for instance.  */
14137       if (last_die->has_children
14138           && (load_all
14139               || last_die->tag == DW_TAG_namespace
14140               || last_die->tag == DW_TAG_module
14141               || last_die->tag == DW_TAG_enumeration_type
14142               || (cu->language == language_cplus
14143                   && last_die->tag == DW_TAG_subprogram
14144                   && (last_die->name == NULL
14145                       || strchr (last_die->name, '<') == NULL))
14146               || (cu->language != language_c
14147                   && (last_die->tag == DW_TAG_class_type
14148                       || last_die->tag == DW_TAG_interface_type
14149                       || last_die->tag == DW_TAG_structure_type
14150                       || last_die->tag == DW_TAG_union_type))
14151               || (cu->language == language_ada
14152                   && (last_die->tag == DW_TAG_subprogram
14153                       || last_die->tag == DW_TAG_lexical_block))))
14154         {
14155           nesting_level++;
14156           parent_die = last_die;
14157           continue;
14158         }
14159
14160       /* Otherwise we skip to the next sibling, if any.  */
14161       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14162
14163       /* Back to the top, do it again.  */
14164     }
14165 }
14166
14167 /* Read a minimal amount of information into the minimal die structure.  */
14168
14169 static const gdb_byte *
14170 read_partial_die (const struct die_reader_specs *reader,
14171                   struct partial_die_info *part_die,
14172                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14173                   const gdb_byte *info_ptr)
14174 {
14175   struct dwarf2_cu *cu = reader->cu;
14176   struct objfile *objfile = cu->objfile;
14177   const gdb_byte *buffer = reader->buffer;
14178   unsigned int i;
14179   struct attribute attr;
14180   int has_low_pc_attr = 0;
14181   int has_high_pc_attr = 0;
14182   int high_pc_relative = 0;
14183
14184   memset (part_die, 0, sizeof (struct partial_die_info));
14185
14186   part_die->offset.sect_off = info_ptr - buffer;
14187
14188   info_ptr += abbrev_len;
14189
14190   if (abbrev == NULL)
14191     return info_ptr;
14192
14193   part_die->tag = abbrev->tag;
14194   part_die->has_children = abbrev->has_children;
14195
14196   for (i = 0; i < abbrev->num_attrs; ++i)
14197     {
14198       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14199
14200       /* Store the data if it is of an attribute we want to keep in a
14201          partial symbol table.  */
14202       switch (attr.name)
14203         {
14204         case DW_AT_name:
14205           switch (part_die->tag)
14206             {
14207             case DW_TAG_compile_unit:
14208             case DW_TAG_partial_unit:
14209             case DW_TAG_type_unit:
14210               /* Compilation units have a DW_AT_name that is a filename, not
14211                  a source language identifier.  */
14212             case DW_TAG_enumeration_type:
14213             case DW_TAG_enumerator:
14214               /* These tags always have simple identifiers already; no need
14215                  to canonicalize them.  */
14216               part_die->name = DW_STRING (&attr);
14217               break;
14218             default:
14219               part_die->name
14220                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14221                                             &objfile->objfile_obstack);
14222               break;
14223             }
14224           break;
14225         case DW_AT_linkage_name:
14226         case DW_AT_MIPS_linkage_name:
14227           /* Note that both forms of linkage name might appear.  We
14228              assume they will be the same, and we only store the last
14229              one we see.  */
14230           if (cu->language == language_ada)
14231             part_die->name = DW_STRING (&attr);
14232           part_die->linkage_name = DW_STRING (&attr);
14233           break;
14234         case DW_AT_low_pc:
14235           has_low_pc_attr = 1;
14236           part_die->lowpc = DW_ADDR (&attr);
14237           break;
14238         case DW_AT_high_pc:
14239           has_high_pc_attr = 1;
14240           if (attr.form == DW_FORM_addr
14241               || attr.form == DW_FORM_GNU_addr_index)
14242             part_die->highpc = DW_ADDR (&attr);
14243           else
14244             {
14245               high_pc_relative = 1;
14246               part_die->highpc = DW_UNSND (&attr);
14247             }
14248           break;
14249         case DW_AT_location:
14250           /* Support the .debug_loc offsets.  */
14251           if (attr_form_is_block (&attr))
14252             {
14253                part_die->d.locdesc = DW_BLOCK (&attr);
14254             }
14255           else if (attr_form_is_section_offset (&attr))
14256             {
14257               dwarf2_complex_location_expr_complaint ();
14258             }
14259           else
14260             {
14261               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14262                                                      "partial symbol information");
14263             }
14264           break;
14265         case DW_AT_external:
14266           part_die->is_external = DW_UNSND (&attr);
14267           break;
14268         case DW_AT_declaration:
14269           part_die->is_declaration = DW_UNSND (&attr);
14270           break;
14271         case DW_AT_type:
14272           part_die->has_type = 1;
14273           break;
14274         case DW_AT_abstract_origin:
14275         case DW_AT_specification:
14276         case DW_AT_extension:
14277           part_die->has_specification = 1;
14278           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14279           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14280                                    || cu->per_cu->is_dwz);
14281           break;
14282         case DW_AT_sibling:
14283           /* Ignore absolute siblings, they might point outside of
14284              the current compile unit.  */
14285           if (attr.form == DW_FORM_ref_addr)
14286             complaint (&symfile_complaints,
14287                        _("ignoring absolute DW_AT_sibling"));
14288           else
14289             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14290           break;
14291         case DW_AT_byte_size:
14292           part_die->has_byte_size = 1;
14293           break;
14294         case DW_AT_calling_convention:
14295           /* DWARF doesn't provide a way to identify a program's source-level
14296              entry point.  DW_AT_calling_convention attributes are only meant
14297              to describe functions' calling conventions.
14298
14299              However, because it's a necessary piece of information in
14300              Fortran, and because DW_CC_program is the only piece of debugging
14301              information whose definition refers to a 'main program' at all,
14302              several compilers have begun marking Fortran main programs with
14303              DW_CC_program --- even when those functions use the standard
14304              calling conventions.
14305
14306              So until DWARF specifies a way to provide this information and
14307              compilers pick up the new representation, we'll support this
14308              practice.  */
14309           if (DW_UNSND (&attr) == DW_CC_program
14310               && cu->language == language_fortran)
14311             {
14312               set_main_name (part_die->name);
14313
14314               /* As this DIE has a static linkage the name would be difficult
14315                  to look up later.  */
14316               language_of_main = language_fortran;
14317             }
14318           break;
14319         case DW_AT_inline:
14320           if (DW_UNSND (&attr) == DW_INL_inlined
14321               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14322             part_die->may_be_inlined = 1;
14323           break;
14324
14325         case DW_AT_import:
14326           if (part_die->tag == DW_TAG_imported_unit)
14327             {
14328               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14329               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14330                                   || cu->per_cu->is_dwz);
14331             }
14332           break;
14333
14334         default:
14335           break;
14336         }
14337     }
14338
14339   if (high_pc_relative)
14340     part_die->highpc += part_die->lowpc;
14341
14342   if (has_low_pc_attr && has_high_pc_attr)
14343     {
14344       /* When using the GNU linker, .gnu.linkonce. sections are used to
14345          eliminate duplicate copies of functions and vtables and such.
14346          The linker will arbitrarily choose one and discard the others.
14347          The AT_*_pc values for such functions refer to local labels in
14348          these sections.  If the section from that file was discarded, the
14349          labels are not in the output, so the relocs get a value of 0.
14350          If this is a discarded function, mark the pc bounds as invalid,
14351          so that GDB will ignore it.  */
14352       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14353         {
14354           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14355
14356           complaint (&symfile_complaints,
14357                      _("DW_AT_low_pc %s is zero "
14358                        "for DIE at 0x%x [in module %s]"),
14359                      paddress (gdbarch, part_die->lowpc),
14360                      part_die->offset.sect_off, objfile->name);
14361         }
14362       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14363       else if (part_die->lowpc >= part_die->highpc)
14364         {
14365           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14366
14367           complaint (&symfile_complaints,
14368                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14369                        "for DIE at 0x%x [in module %s]"),
14370                      paddress (gdbarch, part_die->lowpc),
14371                      paddress (gdbarch, part_die->highpc),
14372                      part_die->offset.sect_off, objfile->name);
14373         }
14374       else
14375         part_die->has_pc_info = 1;
14376     }
14377
14378   return info_ptr;
14379 }
14380
14381 /* Find a cached partial DIE at OFFSET in CU.  */
14382
14383 static struct partial_die_info *
14384 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14385 {
14386   struct partial_die_info *lookup_die = NULL;
14387   struct partial_die_info part_die;
14388
14389   part_die.offset = offset;
14390   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14391                                     offset.sect_off);
14392
14393   return lookup_die;
14394 }
14395
14396 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14397    except in the case of .debug_types DIEs which do not reference
14398    outside their CU (they do however referencing other types via
14399    DW_FORM_ref_sig8).  */
14400
14401 static struct partial_die_info *
14402 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14403 {
14404   struct objfile *objfile = cu->objfile;
14405   struct dwarf2_per_cu_data *per_cu = NULL;
14406   struct partial_die_info *pd = NULL;
14407
14408   if (offset_in_dwz == cu->per_cu->is_dwz
14409       && offset_in_cu_p (&cu->header, offset))
14410     {
14411       pd = find_partial_die_in_comp_unit (offset, cu);
14412       if (pd != NULL)
14413         return pd;
14414       /* We missed recording what we needed.
14415          Load all dies and try again.  */
14416       per_cu = cu->per_cu;
14417     }
14418   else
14419     {
14420       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14421       if (cu->per_cu->is_debug_types)
14422         {
14423           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14424                    " external reference to offset 0x%lx [in module %s].\n"),
14425                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14426                  bfd_get_filename (objfile->obfd));
14427         }
14428       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14429                                                  objfile);
14430
14431       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14432         load_partial_comp_unit (per_cu);
14433
14434       per_cu->cu->last_used = 0;
14435       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14436     }
14437
14438   /* If we didn't find it, and not all dies have been loaded,
14439      load them all and try again.  */
14440
14441   if (pd == NULL && per_cu->load_all_dies == 0)
14442     {
14443       per_cu->load_all_dies = 1;
14444
14445       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14446          THIS_CU->cu may already be in use.  So we can't just free it and
14447          replace its DIEs with the ones we read in.  Instead, we leave those
14448          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14449          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14450          set.  */
14451       load_partial_comp_unit (per_cu);
14452
14453       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14454     }
14455
14456   if (pd == NULL)
14457     internal_error (__FILE__, __LINE__,
14458                     _("could not find partial DIE 0x%x "
14459                       "in cache [from module %s]\n"),
14460                     offset.sect_off, bfd_get_filename (objfile->obfd));
14461   return pd;
14462 }
14463
14464 /* See if we can figure out if the class lives in a namespace.  We do
14465    this by looking for a member function; its demangled name will
14466    contain namespace info, if there is any.  */
14467
14468 static void
14469 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14470                                   struct dwarf2_cu *cu)
14471 {
14472   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14473      what template types look like, because the demangler
14474      frequently doesn't give the same name as the debug info.  We
14475      could fix this by only using the demangled name to get the
14476      prefix (but see comment in read_structure_type).  */
14477
14478   struct partial_die_info *real_pdi;
14479   struct partial_die_info *child_pdi;
14480
14481   /* If this DIE (this DIE's specification, if any) has a parent, then
14482      we should not do this.  We'll prepend the parent's fully qualified
14483      name when we create the partial symbol.  */
14484
14485   real_pdi = struct_pdi;
14486   while (real_pdi->has_specification)
14487     real_pdi = find_partial_die (real_pdi->spec_offset,
14488                                  real_pdi->spec_is_dwz, cu);
14489
14490   if (real_pdi->die_parent != NULL)
14491     return;
14492
14493   for (child_pdi = struct_pdi->die_child;
14494        child_pdi != NULL;
14495        child_pdi = child_pdi->die_sibling)
14496     {
14497       if (child_pdi->tag == DW_TAG_subprogram
14498           && child_pdi->linkage_name != NULL)
14499         {
14500           char *actual_class_name
14501             = language_class_name_from_physname (cu->language_defn,
14502                                                  child_pdi->linkage_name);
14503           if (actual_class_name != NULL)
14504             {
14505               struct_pdi->name
14506                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14507                                  actual_class_name,
14508                                  strlen (actual_class_name));
14509               xfree (actual_class_name);
14510             }
14511           break;
14512         }
14513     }
14514 }
14515
14516 /* Adjust PART_DIE before generating a symbol for it.  This function
14517    may set the is_external flag or change the DIE's name.  */
14518
14519 static void
14520 fixup_partial_die (struct partial_die_info *part_die,
14521                    struct dwarf2_cu *cu)
14522 {
14523   /* Once we've fixed up a die, there's no point in doing so again.
14524      This also avoids a memory leak if we were to call
14525      guess_partial_die_structure_name multiple times.  */
14526   if (part_die->fixup_called)
14527     return;
14528
14529   /* If we found a reference attribute and the DIE has no name, try
14530      to find a name in the referred to DIE.  */
14531
14532   if (part_die->name == NULL && part_die->has_specification)
14533     {
14534       struct partial_die_info *spec_die;
14535
14536       spec_die = find_partial_die (part_die->spec_offset,
14537                                    part_die->spec_is_dwz, cu);
14538
14539       fixup_partial_die (spec_die, cu);
14540
14541       if (spec_die->name)
14542         {
14543           part_die->name = spec_die->name;
14544
14545           /* Copy DW_AT_external attribute if it is set.  */
14546           if (spec_die->is_external)
14547             part_die->is_external = spec_die->is_external;
14548         }
14549     }
14550
14551   /* Set default names for some unnamed DIEs.  */
14552
14553   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14554     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14555
14556   /* If there is no parent die to provide a namespace, and there are
14557      children, see if we can determine the namespace from their linkage
14558      name.  */
14559   if (cu->language == language_cplus
14560       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14561       && part_die->die_parent == NULL
14562       && part_die->has_children
14563       && (part_die->tag == DW_TAG_class_type
14564           || part_die->tag == DW_TAG_structure_type
14565           || part_die->tag == DW_TAG_union_type))
14566     guess_partial_die_structure_name (part_die, cu);
14567
14568   /* GCC might emit a nameless struct or union that has a linkage
14569      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14570   if (part_die->name == NULL
14571       && (part_die->tag == DW_TAG_class_type
14572           || part_die->tag == DW_TAG_interface_type
14573           || part_die->tag == DW_TAG_structure_type
14574           || part_die->tag == DW_TAG_union_type)
14575       && part_die->linkage_name != NULL)
14576     {
14577       char *demangled;
14578
14579       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14580       if (demangled)
14581         {
14582           const char *base;
14583
14584           /* Strip any leading namespaces/classes, keep only the base name.
14585              DW_AT_name for named DIEs does not contain the prefixes.  */
14586           base = strrchr (demangled, ':');
14587           if (base && base > demangled && base[-1] == ':')
14588             base++;
14589           else
14590             base = demangled;
14591
14592           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14593                                           base, strlen (base));
14594           xfree (demangled);
14595         }
14596     }
14597
14598   part_die->fixup_called = 1;
14599 }
14600
14601 /* Read an attribute value described by an attribute form.  */
14602
14603 static const gdb_byte *
14604 read_attribute_value (const struct die_reader_specs *reader,
14605                       struct attribute *attr, unsigned form,
14606                       const gdb_byte *info_ptr)
14607 {
14608   struct dwarf2_cu *cu = reader->cu;
14609   bfd *abfd = reader->abfd;
14610   struct comp_unit_head *cu_header = &cu->header;
14611   unsigned int bytes_read;
14612   struct dwarf_block *blk;
14613
14614   attr->form = form;
14615   switch (form)
14616     {
14617     case DW_FORM_ref_addr:
14618       if (cu->header.version == 2)
14619         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14620       else
14621         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14622                                        &cu->header, &bytes_read);
14623       info_ptr += bytes_read;
14624       break;
14625     case DW_FORM_GNU_ref_alt:
14626       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14627       info_ptr += bytes_read;
14628       break;
14629     case DW_FORM_addr:
14630       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14631       info_ptr += bytes_read;
14632       break;
14633     case DW_FORM_block2:
14634       blk = dwarf_alloc_block (cu);
14635       blk->size = read_2_bytes (abfd, info_ptr);
14636       info_ptr += 2;
14637       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14638       info_ptr += blk->size;
14639       DW_BLOCK (attr) = blk;
14640       break;
14641     case DW_FORM_block4:
14642       blk = dwarf_alloc_block (cu);
14643       blk->size = read_4_bytes (abfd, info_ptr);
14644       info_ptr += 4;
14645       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14646       info_ptr += blk->size;
14647       DW_BLOCK (attr) = blk;
14648       break;
14649     case DW_FORM_data2:
14650       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14651       info_ptr += 2;
14652       break;
14653     case DW_FORM_data4:
14654       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14655       info_ptr += 4;
14656       break;
14657     case DW_FORM_data8:
14658       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14659       info_ptr += 8;
14660       break;
14661     case DW_FORM_sec_offset:
14662       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14663       info_ptr += bytes_read;
14664       break;
14665     case DW_FORM_string:
14666       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14667       DW_STRING_IS_CANONICAL (attr) = 0;
14668       info_ptr += bytes_read;
14669       break;
14670     case DW_FORM_strp:
14671       if (!cu->per_cu->is_dwz)
14672         {
14673           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14674                                                    &bytes_read);
14675           DW_STRING_IS_CANONICAL (attr) = 0;
14676           info_ptr += bytes_read;
14677           break;
14678         }
14679       /* FALLTHROUGH */
14680     case DW_FORM_GNU_strp_alt:
14681       {
14682         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14683         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14684                                           &bytes_read);
14685
14686         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14687         DW_STRING_IS_CANONICAL (attr) = 0;
14688         info_ptr += bytes_read;
14689       }
14690       break;
14691     case DW_FORM_exprloc:
14692     case DW_FORM_block:
14693       blk = dwarf_alloc_block (cu);
14694       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14695       info_ptr += bytes_read;
14696       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14697       info_ptr += blk->size;
14698       DW_BLOCK (attr) = blk;
14699       break;
14700     case DW_FORM_block1:
14701       blk = dwarf_alloc_block (cu);
14702       blk->size = read_1_byte (abfd, info_ptr);
14703       info_ptr += 1;
14704       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14705       info_ptr += blk->size;
14706       DW_BLOCK (attr) = blk;
14707       break;
14708     case DW_FORM_data1:
14709       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14710       info_ptr += 1;
14711       break;
14712     case DW_FORM_flag:
14713       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14714       info_ptr += 1;
14715       break;
14716     case DW_FORM_flag_present:
14717       DW_UNSND (attr) = 1;
14718       break;
14719     case DW_FORM_sdata:
14720       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14721       info_ptr += bytes_read;
14722       break;
14723     case DW_FORM_udata:
14724       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14725       info_ptr += bytes_read;
14726       break;
14727     case DW_FORM_ref1:
14728       DW_UNSND (attr) = (cu->header.offset.sect_off
14729                          + read_1_byte (abfd, info_ptr));
14730       info_ptr += 1;
14731       break;
14732     case DW_FORM_ref2:
14733       DW_UNSND (attr) = (cu->header.offset.sect_off
14734                          + read_2_bytes (abfd, info_ptr));
14735       info_ptr += 2;
14736       break;
14737     case DW_FORM_ref4:
14738       DW_UNSND (attr) = (cu->header.offset.sect_off
14739                          + read_4_bytes (abfd, info_ptr));
14740       info_ptr += 4;
14741       break;
14742     case DW_FORM_ref8:
14743       DW_UNSND (attr) = (cu->header.offset.sect_off
14744                          + read_8_bytes (abfd, info_ptr));
14745       info_ptr += 8;
14746       break;
14747     case DW_FORM_ref_sig8:
14748       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14749       info_ptr += 8;
14750       break;
14751     case DW_FORM_ref_udata:
14752       DW_UNSND (attr) = (cu->header.offset.sect_off
14753                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14754       info_ptr += bytes_read;
14755       break;
14756     case DW_FORM_indirect:
14757       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14758       info_ptr += bytes_read;
14759       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14760       break;
14761     case DW_FORM_GNU_addr_index:
14762       if (reader->dwo_file == NULL)
14763         {
14764           /* For now flag a hard error.
14765              Later we can turn this into a complaint.  */
14766           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14767                  dwarf_form_name (form),
14768                  bfd_get_filename (abfd));
14769         }
14770       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14771       info_ptr += bytes_read;
14772       break;
14773     case DW_FORM_GNU_str_index:
14774       if (reader->dwo_file == NULL)
14775         {
14776           /* For now flag a hard error.
14777              Later we can turn this into a complaint if warranted.  */
14778           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14779                  dwarf_form_name (form),
14780                  bfd_get_filename (abfd));
14781         }
14782       {
14783         ULONGEST str_index =
14784           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14785
14786         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14787         DW_STRING_IS_CANONICAL (attr) = 0;
14788         info_ptr += bytes_read;
14789       }
14790       break;
14791     default:
14792       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14793              dwarf_form_name (form),
14794              bfd_get_filename (abfd));
14795     }
14796
14797   /* Super hack.  */
14798   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
14799     attr->form = DW_FORM_GNU_ref_alt;
14800
14801   /* We have seen instances where the compiler tried to emit a byte
14802      size attribute of -1 which ended up being encoded as an unsigned
14803      0xffffffff.  Although 0xffffffff is technically a valid size value,
14804      an object of this size seems pretty unlikely so we can relatively
14805      safely treat these cases as if the size attribute was invalid and
14806      treat them as zero by default.  */
14807   if (attr->name == DW_AT_byte_size
14808       && form == DW_FORM_data4
14809       && DW_UNSND (attr) >= 0xffffffff)
14810     {
14811       complaint
14812         (&symfile_complaints,
14813          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14814          hex_string (DW_UNSND (attr)));
14815       DW_UNSND (attr) = 0;
14816     }
14817
14818   return info_ptr;
14819 }
14820
14821 /* Read an attribute described by an abbreviated attribute.  */
14822
14823 static const gdb_byte *
14824 read_attribute (const struct die_reader_specs *reader,
14825                 struct attribute *attr, struct attr_abbrev *abbrev,
14826                 const gdb_byte *info_ptr)
14827 {
14828   attr->name = abbrev->name;
14829   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14830 }
14831
14832 /* Read dwarf information from a buffer.  */
14833
14834 static unsigned int
14835 read_1_byte (bfd *abfd, const gdb_byte *buf)
14836 {
14837   return bfd_get_8 (abfd, buf);
14838 }
14839
14840 static int
14841 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14842 {
14843   return bfd_get_signed_8 (abfd, buf);
14844 }
14845
14846 static unsigned int
14847 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14848 {
14849   return bfd_get_16 (abfd, buf);
14850 }
14851
14852 static int
14853 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14854 {
14855   return bfd_get_signed_16 (abfd, buf);
14856 }
14857
14858 static unsigned int
14859 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14860 {
14861   return bfd_get_32 (abfd, buf);
14862 }
14863
14864 static int
14865 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14866 {
14867   return bfd_get_signed_32 (abfd, buf);
14868 }
14869
14870 static ULONGEST
14871 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14872 {
14873   return bfd_get_64 (abfd, buf);
14874 }
14875
14876 static CORE_ADDR
14877 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14878               unsigned int *bytes_read)
14879 {
14880   struct comp_unit_head *cu_header = &cu->header;
14881   CORE_ADDR retval = 0;
14882
14883   if (cu_header->signed_addr_p)
14884     {
14885       switch (cu_header->addr_size)
14886         {
14887         case 2:
14888           retval = bfd_get_signed_16 (abfd, buf);
14889           break;
14890         case 4:
14891           retval = bfd_get_signed_32 (abfd, buf);
14892           break;
14893         case 8:
14894           retval = bfd_get_signed_64 (abfd, buf);
14895           break;
14896         default:
14897           internal_error (__FILE__, __LINE__,
14898                           _("read_address: bad switch, signed [in module %s]"),
14899                           bfd_get_filename (abfd));
14900         }
14901     }
14902   else
14903     {
14904       switch (cu_header->addr_size)
14905         {
14906         case 2:
14907           retval = bfd_get_16 (abfd, buf);
14908           break;
14909         case 4:
14910           retval = bfd_get_32 (abfd, buf);
14911           break;
14912         case 8:
14913           retval = bfd_get_64 (abfd, buf);
14914           break;
14915         default:
14916           internal_error (__FILE__, __LINE__,
14917                           _("read_address: bad switch, "
14918                             "unsigned [in module %s]"),
14919                           bfd_get_filename (abfd));
14920         }
14921     }
14922
14923   *bytes_read = cu_header->addr_size;
14924   return retval;
14925 }
14926
14927 /* Read the initial length from a section.  The (draft) DWARF 3
14928    specification allows the initial length to take up either 4 bytes
14929    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14930    bytes describe the length and all offsets will be 8 bytes in length
14931    instead of 4.
14932
14933    An older, non-standard 64-bit format is also handled by this
14934    function.  The older format in question stores the initial length
14935    as an 8-byte quantity without an escape value.  Lengths greater
14936    than 2^32 aren't very common which means that the initial 4 bytes
14937    is almost always zero.  Since a length value of zero doesn't make
14938    sense for the 32-bit format, this initial zero can be considered to
14939    be an escape value which indicates the presence of the older 64-bit
14940    format.  As written, the code can't detect (old format) lengths
14941    greater than 4GB.  If it becomes necessary to handle lengths
14942    somewhat larger than 4GB, we could allow other small values (such
14943    as the non-sensical values of 1, 2, and 3) to also be used as
14944    escape values indicating the presence of the old format.
14945
14946    The value returned via bytes_read should be used to increment the
14947    relevant pointer after calling read_initial_length().
14948
14949    [ Note:  read_initial_length() and read_offset() are based on the
14950      document entitled "DWARF Debugging Information Format", revision
14951      3, draft 8, dated November 19, 2001.  This document was obtained
14952      from:
14953
14954         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14955
14956      This document is only a draft and is subject to change.  (So beware.)
14957
14958      Details regarding the older, non-standard 64-bit format were
14959      determined empirically by examining 64-bit ELF files produced by
14960      the SGI toolchain on an IRIX 6.5 machine.
14961
14962      - Kevin, July 16, 2002
14963    ] */
14964
14965 static LONGEST
14966 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
14967 {
14968   LONGEST length = bfd_get_32 (abfd, buf);
14969
14970   if (length == 0xffffffff)
14971     {
14972       length = bfd_get_64 (abfd, buf + 4);
14973       *bytes_read = 12;
14974     }
14975   else if (length == 0)
14976     {
14977       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14978       length = bfd_get_64 (abfd, buf);
14979       *bytes_read = 8;
14980     }
14981   else
14982     {
14983       *bytes_read = 4;
14984     }
14985
14986   return length;
14987 }
14988
14989 /* Cover function for read_initial_length.
14990    Returns the length of the object at BUF, and stores the size of the
14991    initial length in *BYTES_READ and stores the size that offsets will be in
14992    *OFFSET_SIZE.
14993    If the initial length size is not equivalent to that specified in
14994    CU_HEADER then issue a complaint.
14995    This is useful when reading non-comp-unit headers.  */
14996
14997 static LONGEST
14998 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
14999                                         const struct comp_unit_head *cu_header,
15000                                         unsigned int *bytes_read,
15001                                         unsigned int *offset_size)
15002 {
15003   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15004
15005   gdb_assert (cu_header->initial_length_size == 4
15006               || cu_header->initial_length_size == 8
15007               || cu_header->initial_length_size == 12);
15008
15009   if (cu_header->initial_length_size != *bytes_read)
15010     complaint (&symfile_complaints,
15011                _("intermixed 32-bit and 64-bit DWARF sections"));
15012
15013   *offset_size = (*bytes_read == 4) ? 4 : 8;
15014   return length;
15015 }
15016
15017 /* Read an offset from the data stream.  The size of the offset is
15018    given by cu_header->offset_size.  */
15019
15020 static LONGEST
15021 read_offset (bfd *abfd, const gdb_byte *buf,
15022              const struct comp_unit_head *cu_header,
15023              unsigned int *bytes_read)
15024 {
15025   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15026
15027   *bytes_read = cu_header->offset_size;
15028   return offset;
15029 }
15030
15031 /* Read an offset from the data stream.  */
15032
15033 static LONGEST
15034 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15035 {
15036   LONGEST retval = 0;
15037
15038   switch (offset_size)
15039     {
15040     case 4:
15041       retval = bfd_get_32 (abfd, buf);
15042       break;
15043     case 8:
15044       retval = bfd_get_64 (abfd, buf);
15045       break;
15046     default:
15047       internal_error (__FILE__, __LINE__,
15048                       _("read_offset_1: bad switch [in module %s]"),
15049                       bfd_get_filename (abfd));
15050     }
15051
15052   return retval;
15053 }
15054
15055 static const gdb_byte *
15056 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15057 {
15058   /* If the size of a host char is 8 bits, we can return a pointer
15059      to the buffer, otherwise we have to copy the data to a buffer
15060      allocated on the temporary obstack.  */
15061   gdb_assert (HOST_CHAR_BIT == 8);
15062   return buf;
15063 }
15064
15065 static const char *
15066 read_direct_string (bfd *abfd, const gdb_byte *buf,
15067                     unsigned int *bytes_read_ptr)
15068 {
15069   /* If the size of a host char is 8 bits, we can return a pointer
15070      to the string, otherwise we have to copy the string to a buffer
15071      allocated on the temporary obstack.  */
15072   gdb_assert (HOST_CHAR_BIT == 8);
15073   if (*buf == '\0')
15074     {
15075       *bytes_read_ptr = 1;
15076       return NULL;
15077     }
15078   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15079   return (const char *) buf;
15080 }
15081
15082 static const char *
15083 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15084 {
15085   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15086   if (dwarf2_per_objfile->str.buffer == NULL)
15087     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15088            bfd_get_filename (abfd));
15089   if (str_offset >= dwarf2_per_objfile->str.size)
15090     error (_("DW_FORM_strp pointing outside of "
15091              ".debug_str section [in module %s]"),
15092            bfd_get_filename (abfd));
15093   gdb_assert (HOST_CHAR_BIT == 8);
15094   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15095     return NULL;
15096   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15097 }
15098
15099 /* Read a string at offset STR_OFFSET in the .debug_str section from
15100    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15101    the string consists of a single NUL byte, return NULL; otherwise
15102    return a pointer to the string.  */
15103
15104 static const char *
15105 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15106 {
15107   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15108
15109   if (dwz->str.buffer == NULL)
15110     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15111              "section [in module %s]"),
15112            bfd_get_filename (dwz->dwz_bfd));
15113   if (str_offset >= dwz->str.size)
15114     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15115              ".debug_str section [in module %s]"),
15116            bfd_get_filename (dwz->dwz_bfd));
15117   gdb_assert (HOST_CHAR_BIT == 8);
15118   if (dwz->str.buffer[str_offset] == '\0')
15119     return NULL;
15120   return (const char *) (dwz->str.buffer + str_offset);
15121 }
15122
15123 static const char *
15124 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15125                       const struct comp_unit_head *cu_header,
15126                       unsigned int *bytes_read_ptr)
15127 {
15128   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15129
15130   return read_indirect_string_at_offset (abfd, str_offset);
15131 }
15132
15133 static ULONGEST
15134 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15135                       unsigned int *bytes_read_ptr)
15136 {
15137   ULONGEST result;
15138   unsigned int num_read;
15139   int i, shift;
15140   unsigned char byte;
15141
15142   result = 0;
15143   shift = 0;
15144   num_read = 0;
15145   i = 0;
15146   while (1)
15147     {
15148       byte = bfd_get_8 (abfd, buf);
15149       buf++;
15150       num_read++;
15151       result |= ((ULONGEST) (byte & 127) << shift);
15152       if ((byte & 128) == 0)
15153         {
15154           break;
15155         }
15156       shift += 7;
15157     }
15158   *bytes_read_ptr = num_read;
15159   return result;
15160 }
15161
15162 static LONGEST
15163 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15164                     unsigned int *bytes_read_ptr)
15165 {
15166   LONGEST result;
15167   int i, shift, num_read;
15168   unsigned char byte;
15169
15170   result = 0;
15171   shift = 0;
15172   num_read = 0;
15173   i = 0;
15174   while (1)
15175     {
15176       byte = bfd_get_8 (abfd, buf);
15177       buf++;
15178       num_read++;
15179       result |= ((LONGEST) (byte & 127) << shift);
15180       shift += 7;
15181       if ((byte & 128) == 0)
15182         {
15183           break;
15184         }
15185     }
15186   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15187     result |= -(((LONGEST) 1) << shift);
15188   *bytes_read_ptr = num_read;
15189   return result;
15190 }
15191
15192 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15193    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15194    ADDR_SIZE is the size of addresses from the CU header.  */
15195
15196 static CORE_ADDR
15197 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15198 {
15199   struct objfile *objfile = dwarf2_per_objfile->objfile;
15200   bfd *abfd = objfile->obfd;
15201   const gdb_byte *info_ptr;
15202
15203   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15204   if (dwarf2_per_objfile->addr.buffer == NULL)
15205     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15206            objfile->name);
15207   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15208     error (_("DW_FORM_addr_index pointing outside of "
15209              ".debug_addr section [in module %s]"),
15210            objfile->name);
15211   info_ptr = (dwarf2_per_objfile->addr.buffer
15212               + addr_base + addr_index * addr_size);
15213   if (addr_size == 4)
15214     return bfd_get_32 (abfd, info_ptr);
15215   else
15216     return bfd_get_64 (abfd, info_ptr);
15217 }
15218
15219 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15220
15221 static CORE_ADDR
15222 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15223 {
15224   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15225 }
15226
15227 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15228
15229 static CORE_ADDR
15230 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15231                              unsigned int *bytes_read)
15232 {
15233   bfd *abfd = cu->objfile->obfd;
15234   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15235
15236   return read_addr_index (cu, addr_index);
15237 }
15238
15239 /* Data structure to pass results from dwarf2_read_addr_index_reader
15240    back to dwarf2_read_addr_index.  */
15241
15242 struct dwarf2_read_addr_index_data
15243 {
15244   ULONGEST addr_base;
15245   int addr_size;
15246 };
15247
15248 /* die_reader_func for dwarf2_read_addr_index.  */
15249
15250 static void
15251 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15252                                const gdb_byte *info_ptr,
15253                                struct die_info *comp_unit_die,
15254                                int has_children,
15255                                void *data)
15256 {
15257   struct dwarf2_cu *cu = reader->cu;
15258   struct dwarf2_read_addr_index_data *aidata =
15259     (struct dwarf2_read_addr_index_data *) data;
15260
15261   aidata->addr_base = cu->addr_base;
15262   aidata->addr_size = cu->header.addr_size;
15263 }
15264
15265 /* Given an index in .debug_addr, fetch the value.
15266    NOTE: This can be called during dwarf expression evaluation,
15267    long after the debug information has been read, and thus per_cu->cu
15268    may no longer exist.  */
15269
15270 CORE_ADDR
15271 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15272                         unsigned int addr_index)
15273 {
15274   struct objfile *objfile = per_cu->objfile;
15275   struct dwarf2_cu *cu = per_cu->cu;
15276   ULONGEST addr_base;
15277   int addr_size;
15278
15279   /* This is intended to be called from outside this file.  */
15280   dw2_setup (objfile);
15281
15282   /* We need addr_base and addr_size.
15283      If we don't have PER_CU->cu, we have to get it.
15284      Nasty, but the alternative is storing the needed info in PER_CU,
15285      which at this point doesn't seem justified: it's not clear how frequently
15286      it would get used and it would increase the size of every PER_CU.
15287      Entry points like dwarf2_per_cu_addr_size do a similar thing
15288      so we're not in uncharted territory here.
15289      Alas we need to be a bit more complicated as addr_base is contained
15290      in the DIE.
15291
15292      We don't need to read the entire CU(/TU).
15293      We just need the header and top level die.
15294
15295      IWBN to use the aging mechanism to let us lazily later discard the CU.
15296      For now we skip this optimization.  */
15297
15298   if (cu != NULL)
15299     {
15300       addr_base = cu->addr_base;
15301       addr_size = cu->header.addr_size;
15302     }
15303   else
15304     {
15305       struct dwarf2_read_addr_index_data aidata;
15306
15307       /* Note: We can't use init_cutu_and_read_dies_simple here,
15308          we need addr_base.  */
15309       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15310                                dwarf2_read_addr_index_reader, &aidata);
15311       addr_base = aidata.addr_base;
15312       addr_size = aidata.addr_size;
15313     }
15314
15315   return read_addr_index_1 (addr_index, addr_base, addr_size);
15316 }
15317
15318 /* Given a DW_AT_str_index, fetch the string.  */
15319
15320 static const char *
15321 read_str_index (const struct die_reader_specs *reader,
15322                 struct dwarf2_cu *cu, ULONGEST str_index)
15323 {
15324   struct objfile *objfile = dwarf2_per_objfile->objfile;
15325   const char *dwo_name = objfile->name;
15326   bfd *abfd = objfile->obfd;
15327   struct dwo_sections *sections = &reader->dwo_file->sections;
15328   const gdb_byte *info_ptr;
15329   ULONGEST str_offset;
15330
15331   dwarf2_read_section (objfile, &sections->str);
15332   dwarf2_read_section (objfile, &sections->str_offsets);
15333   if (sections->str.buffer == NULL)
15334     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15335              " in CU at offset 0x%lx [in module %s]"),
15336            (long) cu->header.offset.sect_off, dwo_name);
15337   if (sections->str_offsets.buffer == NULL)
15338     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15339              " in CU at offset 0x%lx [in module %s]"),
15340            (long) cu->header.offset.sect_off, dwo_name);
15341   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15342     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15343              " section in CU at offset 0x%lx [in module %s]"),
15344            (long) cu->header.offset.sect_off, dwo_name);
15345   info_ptr = (sections->str_offsets.buffer
15346               + str_index * cu->header.offset_size);
15347   if (cu->header.offset_size == 4)
15348     str_offset = bfd_get_32 (abfd, info_ptr);
15349   else
15350     str_offset = bfd_get_64 (abfd, info_ptr);
15351   if (str_offset >= sections->str.size)
15352     error (_("Offset from DW_FORM_str_index pointing outside of"
15353              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15354            (long) cu->header.offset.sect_off, dwo_name);
15355   return (const char *) (sections->str.buffer + str_offset);
15356 }
15357
15358 /* Return the length of an LEB128 number in BUF.  */
15359
15360 static int
15361 leb128_size (const gdb_byte *buf)
15362 {
15363   const gdb_byte *begin = buf;
15364   gdb_byte byte;
15365
15366   while (1)
15367     {
15368       byte = *buf++;
15369       if ((byte & 128) == 0)
15370         return buf - begin;
15371     }
15372 }
15373
15374 static void
15375 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15376 {
15377   switch (lang)
15378     {
15379     case DW_LANG_C89:
15380     case DW_LANG_C99:
15381     case DW_LANG_C:
15382     case DW_LANG_UPC:
15383       cu->language = language_c;
15384       break;
15385     case DW_LANG_C_plus_plus:
15386       cu->language = language_cplus;
15387       break;
15388     case DW_LANG_D:
15389       cu->language = language_d;
15390       break;
15391     case DW_LANG_Fortran77:
15392     case DW_LANG_Fortran90:
15393     case DW_LANG_Fortran95:
15394       cu->language = language_fortran;
15395       break;
15396     case DW_LANG_Go:
15397       cu->language = language_go;
15398       break;
15399     case DW_LANG_Mips_Assembler:
15400       cu->language = language_asm;
15401       break;
15402     case DW_LANG_Java:
15403       cu->language = language_java;
15404       break;
15405     case DW_LANG_Ada83:
15406     case DW_LANG_Ada95:
15407       cu->language = language_ada;
15408       break;
15409     case DW_LANG_Modula2:
15410       cu->language = language_m2;
15411       break;
15412     case DW_LANG_Pascal83:
15413       cu->language = language_pascal;
15414       break;
15415     case DW_LANG_ObjC:
15416       cu->language = language_objc;
15417       break;
15418     case DW_LANG_Cobol74:
15419     case DW_LANG_Cobol85:
15420     default:
15421       cu->language = language_minimal;
15422       break;
15423     }
15424   cu->language_defn = language_def (cu->language);
15425 }
15426
15427 /* Return the named attribute or NULL if not there.  */
15428
15429 static struct attribute *
15430 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15431 {
15432   for (;;)
15433     {
15434       unsigned int i;
15435       struct attribute *spec = NULL;
15436
15437       for (i = 0; i < die->num_attrs; ++i)
15438         {
15439           if (die->attrs[i].name == name)
15440             return &die->attrs[i];
15441           if (die->attrs[i].name == DW_AT_specification
15442               || die->attrs[i].name == DW_AT_abstract_origin)
15443             spec = &die->attrs[i];
15444         }
15445
15446       if (!spec)
15447         break;
15448
15449       die = follow_die_ref (die, spec, &cu);
15450     }
15451
15452   return NULL;
15453 }
15454
15455 /* Return the named attribute or NULL if not there,
15456    but do not follow DW_AT_specification, etc.
15457    This is for use in contexts where we're reading .debug_types dies.
15458    Following DW_AT_specification, DW_AT_abstract_origin will take us
15459    back up the chain, and we want to go down.  */
15460
15461 static struct attribute *
15462 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15463 {
15464   unsigned int i;
15465
15466   for (i = 0; i < die->num_attrs; ++i)
15467     if (die->attrs[i].name == name)
15468       return &die->attrs[i];
15469
15470   return NULL;
15471 }
15472
15473 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15474    and holds a non-zero value.  This function should only be used for
15475    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15476
15477 static int
15478 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15479 {
15480   struct attribute *attr = dwarf2_attr (die, name, cu);
15481
15482   return (attr && DW_UNSND (attr));
15483 }
15484
15485 static int
15486 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15487 {
15488   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15489      which value is non-zero.  However, we have to be careful with
15490      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15491      (via dwarf2_flag_true_p) follows this attribute.  So we may
15492      end up accidently finding a declaration attribute that belongs
15493      to a different DIE referenced by the specification attribute,
15494      even though the given DIE does not have a declaration attribute.  */
15495   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15496           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15497 }
15498
15499 /* Return the die giving the specification for DIE, if there is
15500    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15501    containing the return value on output.  If there is no
15502    specification, but there is an abstract origin, that is
15503    returned.  */
15504
15505 static struct die_info *
15506 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15507 {
15508   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15509                                              *spec_cu);
15510
15511   if (spec_attr == NULL)
15512     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15513
15514   if (spec_attr == NULL)
15515     return NULL;
15516   else
15517     return follow_die_ref (die, spec_attr, spec_cu);
15518 }
15519
15520 /* Free the line_header structure *LH, and any arrays and strings it
15521    refers to.
15522    NOTE: This is also used as a "cleanup" function.  */
15523
15524 static void
15525 free_line_header (struct line_header *lh)
15526 {
15527   if (lh->standard_opcode_lengths)
15528     xfree (lh->standard_opcode_lengths);
15529
15530   /* Remember that all the lh->file_names[i].name pointers are
15531      pointers into debug_line_buffer, and don't need to be freed.  */
15532   if (lh->file_names)
15533     xfree (lh->file_names);
15534
15535   /* Similarly for the include directory names.  */
15536   if (lh->include_dirs)
15537     xfree (lh->include_dirs);
15538
15539   xfree (lh);
15540 }
15541
15542 /* Add an entry to LH's include directory table.  */
15543
15544 static void
15545 add_include_dir (struct line_header *lh, const char *include_dir)
15546 {
15547   /* Grow the array if necessary.  */
15548   if (lh->include_dirs_size == 0)
15549     {
15550       lh->include_dirs_size = 1; /* for testing */
15551       lh->include_dirs = xmalloc (lh->include_dirs_size
15552                                   * sizeof (*lh->include_dirs));
15553     }
15554   else if (lh->num_include_dirs >= lh->include_dirs_size)
15555     {
15556       lh->include_dirs_size *= 2;
15557       lh->include_dirs = xrealloc (lh->include_dirs,
15558                                    (lh->include_dirs_size
15559                                     * sizeof (*lh->include_dirs)));
15560     }
15561
15562   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15563 }
15564
15565 /* Add an entry to LH's file name table.  */
15566
15567 static void
15568 add_file_name (struct line_header *lh,
15569                const char *name,
15570                unsigned int dir_index,
15571                unsigned int mod_time,
15572                unsigned int length)
15573 {
15574   struct file_entry *fe;
15575
15576   /* Grow the array if necessary.  */
15577   if (lh->file_names_size == 0)
15578     {
15579       lh->file_names_size = 1; /* for testing */
15580       lh->file_names = xmalloc (lh->file_names_size
15581                                 * sizeof (*lh->file_names));
15582     }
15583   else if (lh->num_file_names >= lh->file_names_size)
15584     {
15585       lh->file_names_size *= 2;
15586       lh->file_names = xrealloc (lh->file_names,
15587                                  (lh->file_names_size
15588                                   * sizeof (*lh->file_names)));
15589     }
15590
15591   fe = &lh->file_names[lh->num_file_names++];
15592   fe->name = name;
15593   fe->dir_index = dir_index;
15594   fe->mod_time = mod_time;
15595   fe->length = length;
15596   fe->included_p = 0;
15597   fe->symtab = NULL;
15598 }
15599
15600 /* A convenience function to find the proper .debug_line section for a
15601    CU.  */
15602
15603 static struct dwarf2_section_info *
15604 get_debug_line_section (struct dwarf2_cu *cu)
15605 {
15606   struct dwarf2_section_info *section;
15607
15608   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15609      DWO file.  */
15610   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15611     section = &cu->dwo_unit->dwo_file->sections.line;
15612   else if (cu->per_cu->is_dwz)
15613     {
15614       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15615
15616       section = &dwz->line;
15617     }
15618   else
15619     section = &dwarf2_per_objfile->line;
15620
15621   return section;
15622 }
15623
15624 /* Read the statement program header starting at OFFSET in
15625    .debug_line, or .debug_line.dwo.  Return a pointer
15626    to a struct line_header, allocated using xmalloc.
15627
15628    NOTE: the strings in the include directory and file name tables of
15629    the returned object point into the dwarf line section buffer,
15630    and must not be freed.  */
15631
15632 static struct line_header *
15633 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15634 {
15635   struct cleanup *back_to;
15636   struct line_header *lh;
15637   const gdb_byte *line_ptr;
15638   unsigned int bytes_read, offset_size;
15639   int i;
15640   const char *cur_dir, *cur_file;
15641   struct dwarf2_section_info *section;
15642   bfd *abfd;
15643
15644   section = get_debug_line_section (cu);
15645   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15646   if (section->buffer == NULL)
15647     {
15648       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15649         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15650       else
15651         complaint (&symfile_complaints, _("missing .debug_line section"));
15652       return 0;
15653     }
15654
15655   /* We can't do this until we know the section is non-empty.
15656      Only then do we know we have such a section.  */
15657   abfd = section->asection->owner;
15658
15659   /* Make sure that at least there's room for the total_length field.
15660      That could be 12 bytes long, but we're just going to fudge that.  */
15661   if (offset + 4 >= section->size)
15662     {
15663       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15664       return 0;
15665     }
15666
15667   lh = xmalloc (sizeof (*lh));
15668   memset (lh, 0, sizeof (*lh));
15669   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15670                           (void *) lh);
15671
15672   line_ptr = section->buffer + offset;
15673
15674   /* Read in the header.  */
15675   lh->total_length =
15676     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15677                                             &bytes_read, &offset_size);
15678   line_ptr += bytes_read;
15679   if (line_ptr + lh->total_length > (section->buffer + section->size))
15680     {
15681       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15682       do_cleanups (back_to);
15683       return 0;
15684     }
15685   lh->statement_program_end = line_ptr + lh->total_length;
15686   lh->version = read_2_bytes (abfd, line_ptr);
15687   line_ptr += 2;
15688   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15689   line_ptr += offset_size;
15690   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15691   line_ptr += 1;
15692   if (lh->version >= 4)
15693     {
15694       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15695       line_ptr += 1;
15696     }
15697   else
15698     lh->maximum_ops_per_instruction = 1;
15699
15700   if (lh->maximum_ops_per_instruction == 0)
15701     {
15702       lh->maximum_ops_per_instruction = 1;
15703       complaint (&symfile_complaints,
15704                  _("invalid maximum_ops_per_instruction "
15705                    "in `.debug_line' section"));
15706     }
15707
15708   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15709   line_ptr += 1;
15710   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15711   line_ptr += 1;
15712   lh->line_range = read_1_byte (abfd, line_ptr);
15713   line_ptr += 1;
15714   lh->opcode_base = read_1_byte (abfd, line_ptr);
15715   line_ptr += 1;
15716   lh->standard_opcode_lengths
15717     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15718
15719   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15720   for (i = 1; i < lh->opcode_base; ++i)
15721     {
15722       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15723       line_ptr += 1;
15724     }
15725
15726   /* Read directory table.  */
15727   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15728     {
15729       line_ptr += bytes_read;
15730       add_include_dir (lh, cur_dir);
15731     }
15732   line_ptr += bytes_read;
15733
15734   /* Read file name table.  */
15735   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15736     {
15737       unsigned int dir_index, mod_time, length;
15738
15739       line_ptr += bytes_read;
15740       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15741       line_ptr += bytes_read;
15742       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15743       line_ptr += bytes_read;
15744       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15745       line_ptr += bytes_read;
15746
15747       add_file_name (lh, cur_file, dir_index, mod_time, length);
15748     }
15749   line_ptr += bytes_read;
15750   lh->statement_program_start = line_ptr;
15751
15752   if (line_ptr > (section->buffer + section->size))
15753     complaint (&symfile_complaints,
15754                _("line number info header doesn't "
15755                  "fit in `.debug_line' section"));
15756
15757   discard_cleanups (back_to);
15758   return lh;
15759 }
15760
15761 /* Subroutine of dwarf_decode_lines to simplify it.
15762    Return the file name of the psymtab for included file FILE_INDEX
15763    in line header LH of PST.
15764    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15765    If space for the result is malloc'd, it will be freed by a cleanup.
15766    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15767
15768    The function creates dangling cleanup registration.  */
15769
15770 static const char *
15771 psymtab_include_file_name (const struct line_header *lh, int file_index,
15772                            const struct partial_symtab *pst,
15773                            const char *comp_dir)
15774 {
15775   const struct file_entry fe = lh->file_names [file_index];
15776   const char *include_name = fe.name;
15777   const char *include_name_to_compare = include_name;
15778   const char *dir_name = NULL;
15779   const char *pst_filename;
15780   char *copied_name = NULL;
15781   int file_is_pst;
15782
15783   if (fe.dir_index)
15784     dir_name = lh->include_dirs[fe.dir_index - 1];
15785
15786   if (!IS_ABSOLUTE_PATH (include_name)
15787       && (dir_name != NULL || comp_dir != NULL))
15788     {
15789       /* Avoid creating a duplicate psymtab for PST.
15790          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15791          Before we do the comparison, however, we need to account
15792          for DIR_NAME and COMP_DIR.
15793          First prepend dir_name (if non-NULL).  If we still don't
15794          have an absolute path prepend comp_dir (if non-NULL).
15795          However, the directory we record in the include-file's
15796          psymtab does not contain COMP_DIR (to match the
15797          corresponding symtab(s)).
15798
15799          Example:
15800
15801          bash$ cd /tmp
15802          bash$ gcc -g ./hello.c
15803          include_name = "hello.c"
15804          dir_name = "."
15805          DW_AT_comp_dir = comp_dir = "/tmp"
15806          DW_AT_name = "./hello.c"  */
15807
15808       if (dir_name != NULL)
15809         {
15810           char *tem = concat (dir_name, SLASH_STRING,
15811                               include_name, (char *)NULL);
15812
15813           make_cleanup (xfree, tem);
15814           include_name = tem;
15815           include_name_to_compare = include_name;
15816         }
15817       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15818         {
15819           char *tem = concat (comp_dir, SLASH_STRING,
15820                               include_name, (char *)NULL);
15821
15822           make_cleanup (xfree, tem);
15823           include_name_to_compare = tem;
15824         }
15825     }
15826
15827   pst_filename = pst->filename;
15828   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15829     {
15830       copied_name = concat (pst->dirname, SLASH_STRING,
15831                             pst_filename, (char *)NULL);
15832       pst_filename = copied_name;
15833     }
15834
15835   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15836
15837   if (copied_name != NULL)
15838     xfree (copied_name);
15839
15840   if (file_is_pst)
15841     return NULL;
15842   return include_name;
15843 }
15844
15845 /* Ignore this record_line request.  */
15846
15847 static void
15848 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15849 {
15850   return;
15851 }
15852
15853 /* Subroutine of dwarf_decode_lines to simplify it.
15854    Process the line number information in LH.  */
15855
15856 static void
15857 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15858                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15859 {
15860   const gdb_byte *line_ptr, *extended_end;
15861   const gdb_byte *line_end;
15862   unsigned int bytes_read, extended_len;
15863   unsigned char op_code, extended_op, adj_opcode;
15864   CORE_ADDR baseaddr;
15865   struct objfile *objfile = cu->objfile;
15866   bfd *abfd = objfile->obfd;
15867   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15868   const int decode_for_pst_p = (pst != NULL);
15869   struct subfile *last_subfile = NULL;
15870   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15871     = record_line;
15872
15873   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15874
15875   line_ptr = lh->statement_program_start;
15876   line_end = lh->statement_program_end;
15877
15878   /* Read the statement sequences until there's nothing left.  */
15879   while (line_ptr < line_end)
15880     {
15881       /* state machine registers  */
15882       CORE_ADDR address = 0;
15883       unsigned int file = 1;
15884       unsigned int line = 1;
15885       unsigned int column = 0;
15886       int is_stmt = lh->default_is_stmt;
15887       int basic_block = 0;
15888       int end_sequence = 0;
15889       CORE_ADDR addr;
15890       unsigned char op_index = 0;
15891
15892       if (!decode_for_pst_p && lh->num_file_names >= file)
15893         {
15894           /* Start a subfile for the current file of the state machine.  */
15895           /* lh->include_dirs and lh->file_names are 0-based, but the
15896              directory and file name numbers in the statement program
15897              are 1-based.  */
15898           struct file_entry *fe = &lh->file_names[file - 1];
15899           const char *dir = NULL;
15900
15901           if (fe->dir_index)
15902             dir = lh->include_dirs[fe->dir_index - 1];
15903
15904           dwarf2_start_subfile (fe->name, dir, comp_dir);
15905         }
15906
15907       /* Decode the table.  */
15908       while (!end_sequence)
15909         {
15910           op_code = read_1_byte (abfd, line_ptr);
15911           line_ptr += 1;
15912           if (line_ptr > line_end)
15913             {
15914               dwarf2_debug_line_missing_end_sequence_complaint ();
15915               break;
15916             }
15917
15918           if (op_code >= lh->opcode_base)
15919             {
15920               /* Special operand.  */
15921               adj_opcode = op_code - lh->opcode_base;
15922               address += (((op_index + (adj_opcode / lh->line_range))
15923                            / lh->maximum_ops_per_instruction)
15924                           * lh->minimum_instruction_length);
15925               op_index = ((op_index + (adj_opcode / lh->line_range))
15926                           % lh->maximum_ops_per_instruction);
15927               line += lh->line_base + (adj_opcode % lh->line_range);
15928               if (lh->num_file_names < file || file == 0)
15929                 dwarf2_debug_line_missing_file_complaint ();
15930               /* For now we ignore lines not starting on an
15931                  instruction boundary.  */
15932               else if (op_index == 0)
15933                 {
15934                   lh->file_names[file - 1].included_p = 1;
15935                   if (!decode_for_pst_p && is_stmt)
15936                     {
15937                       if (last_subfile != current_subfile)
15938                         {
15939                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15940                           if (last_subfile)
15941                             (*p_record_line) (last_subfile, 0, addr);
15942                           last_subfile = current_subfile;
15943                         }
15944                       /* Append row to matrix using current values.  */
15945                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15946                       (*p_record_line) (current_subfile, line, addr);
15947                     }
15948                 }
15949               basic_block = 0;
15950             }
15951           else switch (op_code)
15952             {
15953             case DW_LNS_extended_op:
15954               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15955                                                    &bytes_read);
15956               line_ptr += bytes_read;
15957               extended_end = line_ptr + extended_len;
15958               extended_op = read_1_byte (abfd, line_ptr);
15959               line_ptr += 1;
15960               switch (extended_op)
15961                 {
15962                 case DW_LNE_end_sequence:
15963                   p_record_line = record_line;
15964                   end_sequence = 1;
15965                   break;
15966                 case DW_LNE_set_address:
15967                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15968
15969                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15970                     {
15971                       /* This line table is for a function which has been
15972                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15973
15974                       long line_offset
15975                         = line_ptr - get_debug_line_section (cu)->buffer;
15976
15977                       complaint (&symfile_complaints,
15978                                  _(".debug_line address at offset 0x%lx is 0 "
15979                                    "[in module %s]"),
15980                                  line_offset, objfile->name);
15981                       p_record_line = noop_record_line;
15982                     }
15983
15984                   op_index = 0;
15985                   line_ptr += bytes_read;
15986                   address += baseaddr;
15987                   break;
15988                 case DW_LNE_define_file:
15989                   {
15990                     const char *cur_file;
15991                     unsigned int dir_index, mod_time, length;
15992
15993                     cur_file = read_direct_string (abfd, line_ptr,
15994                                                    &bytes_read);
15995                     line_ptr += bytes_read;
15996                     dir_index =
15997                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15998                     line_ptr += bytes_read;
15999                     mod_time =
16000                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16001                     line_ptr += bytes_read;
16002                     length =
16003                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16004                     line_ptr += bytes_read;
16005                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16006                   }
16007                   break;
16008                 case DW_LNE_set_discriminator:
16009                   /* The discriminator is not interesting to the debugger;
16010                      just ignore it.  */
16011                   line_ptr = extended_end;
16012                   break;
16013                 default:
16014                   complaint (&symfile_complaints,
16015                              _("mangled .debug_line section"));
16016                   return;
16017                 }
16018               /* Make sure that we parsed the extended op correctly.  If e.g.
16019                  we expected a different address size than the producer used,
16020                  we may have read the wrong number of bytes.  */
16021               if (line_ptr != extended_end)
16022                 {
16023                   complaint (&symfile_complaints,
16024                              _("mangled .debug_line section"));
16025                   return;
16026                 }
16027               break;
16028             case DW_LNS_copy:
16029               if (lh->num_file_names < file || file == 0)
16030                 dwarf2_debug_line_missing_file_complaint ();
16031               else
16032                 {
16033                   lh->file_names[file - 1].included_p = 1;
16034                   if (!decode_for_pst_p && is_stmt)
16035                     {
16036                       if (last_subfile != current_subfile)
16037                         {
16038                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16039                           if (last_subfile)
16040                             (*p_record_line) (last_subfile, 0, addr);
16041                           last_subfile = current_subfile;
16042                         }
16043                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16044                       (*p_record_line) (current_subfile, line, addr);
16045                     }
16046                 }
16047               basic_block = 0;
16048               break;
16049             case DW_LNS_advance_pc:
16050               {
16051                 CORE_ADDR adjust
16052                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16053
16054                 address += (((op_index + adjust)
16055                              / lh->maximum_ops_per_instruction)
16056                             * lh->minimum_instruction_length);
16057                 op_index = ((op_index + adjust)
16058                             % lh->maximum_ops_per_instruction);
16059                 line_ptr += bytes_read;
16060               }
16061               break;
16062             case DW_LNS_advance_line:
16063               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16064               line_ptr += bytes_read;
16065               break;
16066             case DW_LNS_set_file:
16067               {
16068                 /* The arrays lh->include_dirs and lh->file_names are
16069                    0-based, but the directory and file name numbers in
16070                    the statement program are 1-based.  */
16071                 struct file_entry *fe;
16072                 const char *dir = NULL;
16073
16074                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16075                 line_ptr += bytes_read;
16076                 if (lh->num_file_names < file || file == 0)
16077                   dwarf2_debug_line_missing_file_complaint ();
16078                 else
16079                   {
16080                     fe = &lh->file_names[file - 1];
16081                     if (fe->dir_index)
16082                       dir = lh->include_dirs[fe->dir_index - 1];
16083                     if (!decode_for_pst_p)
16084                       {
16085                         last_subfile = current_subfile;
16086                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16087                       }
16088                   }
16089               }
16090               break;
16091             case DW_LNS_set_column:
16092               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16093               line_ptr += bytes_read;
16094               break;
16095             case DW_LNS_negate_stmt:
16096               is_stmt = (!is_stmt);
16097               break;
16098             case DW_LNS_set_basic_block:
16099               basic_block = 1;
16100               break;
16101             /* Add to the address register of the state machine the
16102                address increment value corresponding to special opcode
16103                255.  I.e., this value is scaled by the minimum
16104                instruction length since special opcode 255 would have
16105                scaled the increment.  */
16106             case DW_LNS_const_add_pc:
16107               {
16108                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16109
16110                 address += (((op_index + adjust)
16111                              / lh->maximum_ops_per_instruction)
16112                             * lh->minimum_instruction_length);
16113                 op_index = ((op_index + adjust)
16114                             % lh->maximum_ops_per_instruction);
16115               }
16116               break;
16117             case DW_LNS_fixed_advance_pc:
16118               address += read_2_bytes (abfd, line_ptr);
16119               op_index = 0;
16120               line_ptr += 2;
16121               break;
16122             default:
16123               {
16124                 /* Unknown standard opcode, ignore it.  */
16125                 int i;
16126
16127                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16128                   {
16129                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16130                     line_ptr += bytes_read;
16131                   }
16132               }
16133             }
16134         }
16135       if (lh->num_file_names < file || file == 0)
16136         dwarf2_debug_line_missing_file_complaint ();
16137       else
16138         {
16139           lh->file_names[file - 1].included_p = 1;
16140           if (!decode_for_pst_p)
16141             {
16142               addr = gdbarch_addr_bits_remove (gdbarch, address);
16143               (*p_record_line) (current_subfile, 0, addr);
16144             }
16145         }
16146     }
16147 }
16148
16149 /* Decode the Line Number Program (LNP) for the given line_header
16150    structure and CU.  The actual information extracted and the type
16151    of structures created from the LNP depends on the value of PST.
16152
16153    1. If PST is NULL, then this procedure uses the data from the program
16154       to create all necessary symbol tables, and their linetables.
16155
16156    2. If PST is not NULL, this procedure reads the program to determine
16157       the list of files included by the unit represented by PST, and
16158       builds all the associated partial symbol tables.
16159
16160    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16161    It is used for relative paths in the line table.
16162    NOTE: When processing partial symtabs (pst != NULL),
16163    comp_dir == pst->dirname.
16164
16165    NOTE: It is important that psymtabs have the same file name (via strcmp)
16166    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16167    symtab we don't use it in the name of the psymtabs we create.
16168    E.g. expand_line_sal requires this when finding psymtabs to expand.
16169    A good testcase for this is mb-inline.exp.  */
16170
16171 static void
16172 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16173                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16174                     int want_line_info)
16175 {
16176   struct objfile *objfile = cu->objfile;
16177   const int decode_for_pst_p = (pst != NULL);
16178   struct subfile *first_subfile = current_subfile;
16179
16180   if (want_line_info)
16181     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16182
16183   if (decode_for_pst_p)
16184     {
16185       int file_index;
16186
16187       /* Now that we're done scanning the Line Header Program, we can
16188          create the psymtab of each included file.  */
16189       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16190         if (lh->file_names[file_index].included_p == 1)
16191           {
16192             const char *include_name =
16193               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16194             if (include_name != NULL)
16195               dwarf2_create_include_psymtab (include_name, pst, objfile);
16196           }
16197     }
16198   else
16199     {
16200       /* Make sure a symtab is created for every file, even files
16201          which contain only variables (i.e. no code with associated
16202          line numbers).  */
16203       int i;
16204
16205       for (i = 0; i < lh->num_file_names; i++)
16206         {
16207           const char *dir = NULL;
16208           struct file_entry *fe;
16209
16210           fe = &lh->file_names[i];
16211           if (fe->dir_index)
16212             dir = lh->include_dirs[fe->dir_index - 1];
16213           dwarf2_start_subfile (fe->name, dir, comp_dir);
16214
16215           /* Skip the main file; we don't need it, and it must be
16216              allocated last, so that it will show up before the
16217              non-primary symtabs in the objfile's symtab list.  */
16218           if (current_subfile == first_subfile)
16219             continue;
16220
16221           if (current_subfile->symtab == NULL)
16222             current_subfile->symtab = allocate_symtab (current_subfile->name,
16223                                                        objfile);
16224           fe->symtab = current_subfile->symtab;
16225         }
16226     }
16227 }
16228
16229 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16230    DIRNAME the name of the source directory which contains FILENAME
16231    or NULL if not known.  COMP_DIR is the compilation directory for the
16232    linetable's compilation unit or NULL if not known.
16233    This routine tries to keep line numbers from identical absolute and
16234    relative file names in a common subfile.
16235
16236    Using the `list' example from the GDB testsuite, which resides in
16237    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16238    of /srcdir/list0.c yields the following debugging information for list0.c:
16239
16240    DW_AT_name:          /srcdir/list0.c
16241    DW_AT_comp_dir:              /compdir
16242    files.files[0].name: list0.h
16243    files.files[0].dir:  /srcdir
16244    files.files[1].name: list0.c
16245    files.files[1].dir:  /srcdir
16246
16247    The line number information for list0.c has to end up in a single
16248    subfile, so that `break /srcdir/list0.c:1' works as expected.
16249    start_subfile will ensure that this happens provided that we pass the
16250    concatenation of files.files[1].dir and files.files[1].name as the
16251    subfile's name.  */
16252
16253 static void
16254 dwarf2_start_subfile (const char *filename, const char *dirname,
16255                       const char *comp_dir)
16256 {
16257   char *copy = NULL;
16258
16259   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16260      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16261      second argument to start_subfile.  To be consistent, we do the
16262      same here.  In order not to lose the line information directory,
16263      we concatenate it to the filename when it makes sense.
16264      Note that the Dwarf3 standard says (speaking of filenames in line
16265      information): ``The directory index is ignored for file names
16266      that represent full path names''.  Thus ignoring dirname in the
16267      `else' branch below isn't an issue.  */
16268
16269   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16270     {
16271       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16272       filename = copy;
16273     }
16274
16275   start_subfile (filename, comp_dir);
16276
16277   if (copy != NULL)
16278     xfree (copy);
16279 }
16280
16281 /* Start a symtab for DWARF.
16282    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16283
16284 static void
16285 dwarf2_start_symtab (struct dwarf2_cu *cu,
16286                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16287 {
16288   start_symtab (name, comp_dir, low_pc);
16289   record_debugformat ("DWARF 2");
16290   record_producer (cu->producer);
16291
16292   /* We assume that we're processing GCC output.  */
16293   processing_gcc_compilation = 2;
16294
16295   cu->processing_has_namespace_info = 0;
16296 }
16297
16298 static void
16299 var_decode_location (struct attribute *attr, struct symbol *sym,
16300                      struct dwarf2_cu *cu)
16301 {
16302   struct objfile *objfile = cu->objfile;
16303   struct comp_unit_head *cu_header = &cu->header;
16304
16305   /* NOTE drow/2003-01-30: There used to be a comment and some special
16306      code here to turn a symbol with DW_AT_external and a
16307      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16308      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16309      with some versions of binutils) where shared libraries could have
16310      relocations against symbols in their debug information - the
16311      minimal symbol would have the right address, but the debug info
16312      would not.  It's no longer necessary, because we will explicitly
16313      apply relocations when we read in the debug information now.  */
16314
16315   /* A DW_AT_location attribute with no contents indicates that a
16316      variable has been optimized away.  */
16317   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16318     {
16319       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16320       return;
16321     }
16322
16323   /* Handle one degenerate form of location expression specially, to
16324      preserve GDB's previous behavior when section offsets are
16325      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16326      then mark this symbol as LOC_STATIC.  */
16327
16328   if (attr_form_is_block (attr)
16329       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16330            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16331           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16332               && (DW_BLOCK (attr)->size
16333                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16334     {
16335       unsigned int dummy;
16336
16337       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16338         SYMBOL_VALUE_ADDRESS (sym) =
16339           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16340       else
16341         SYMBOL_VALUE_ADDRESS (sym) =
16342           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16343       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16344       fixup_symbol_section (sym, objfile);
16345       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16346                                               SYMBOL_SECTION (sym));
16347       return;
16348     }
16349
16350   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16351      expression evaluator, and use LOC_COMPUTED only when necessary
16352      (i.e. when the value of a register or memory location is
16353      referenced, or a thread-local block, etc.).  Then again, it might
16354      not be worthwhile.  I'm assuming that it isn't unless performance
16355      or memory numbers show me otherwise.  */
16356
16357   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16358
16359   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16360     cu->has_loclist = 1;
16361 }
16362
16363 /* Given a pointer to a DWARF information entry, figure out if we need
16364    to make a symbol table entry for it, and if so, create a new entry
16365    and return a pointer to it.
16366    If TYPE is NULL, determine symbol type from the die, otherwise
16367    used the passed type.
16368    If SPACE is not NULL, use it to hold the new symbol.  If it is
16369    NULL, allocate a new symbol on the objfile's obstack.  */
16370
16371 static struct symbol *
16372 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16373                  struct symbol *space)
16374 {
16375   struct objfile *objfile = cu->objfile;
16376   struct symbol *sym = NULL;
16377   const char *name;
16378   struct attribute *attr = NULL;
16379   struct attribute *attr2 = NULL;
16380   CORE_ADDR baseaddr;
16381   struct pending **list_to_add = NULL;
16382
16383   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16384
16385   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16386
16387   name = dwarf2_name (die, cu);
16388   if (name)
16389     {
16390       const char *linkagename;
16391       int suppress_add = 0;
16392
16393       if (space)
16394         sym = space;
16395       else
16396         sym = allocate_symbol (objfile);
16397       OBJSTAT (objfile, n_syms++);
16398
16399       /* Cache this symbol's name and the name's demangled form (if any).  */
16400       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16401       linkagename = dwarf2_physname (name, die, cu);
16402       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16403
16404       /* Fortran does not have mangling standard and the mangling does differ
16405          between gfortran, iFort etc.  */
16406       if (cu->language == language_fortran
16407           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16408         symbol_set_demangled_name (&(sym->ginfo),
16409                                    dwarf2_full_name (name, die, cu),
16410                                    NULL);
16411
16412       /* Default assumptions.
16413          Use the passed type or decode it from the die.  */
16414       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16415       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16416       if (type != NULL)
16417         SYMBOL_TYPE (sym) = type;
16418       else
16419         SYMBOL_TYPE (sym) = die_type (die, cu);
16420       attr = dwarf2_attr (die,
16421                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16422                           cu);
16423       if (attr)
16424         {
16425           SYMBOL_LINE (sym) = DW_UNSND (attr);
16426         }
16427
16428       attr = dwarf2_attr (die,
16429                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16430                           cu);
16431       if (attr)
16432         {
16433           int file_index = DW_UNSND (attr);
16434
16435           if (cu->line_header == NULL
16436               || file_index > cu->line_header->num_file_names)
16437             complaint (&symfile_complaints,
16438                        _("file index out of range"));
16439           else if (file_index > 0)
16440             {
16441               struct file_entry *fe;
16442
16443               fe = &cu->line_header->file_names[file_index - 1];
16444               SYMBOL_SYMTAB (sym) = fe->symtab;
16445             }
16446         }
16447
16448       switch (die->tag)
16449         {
16450         case DW_TAG_label:
16451           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16452           if (attr)
16453             {
16454               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16455             }
16456           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16457           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16458           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16459           add_symbol_to_list (sym, cu->list_in_scope);
16460           break;
16461         case DW_TAG_subprogram:
16462           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16463              finish_block.  */
16464           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16465           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16466           if ((attr2 && (DW_UNSND (attr2) != 0))
16467               || cu->language == language_ada)
16468             {
16469               /* Subprograms marked external are stored as a global symbol.
16470                  Ada subprograms, whether marked external or not, are always
16471                  stored as a global symbol, because we want to be able to
16472                  access them globally.  For instance, we want to be able
16473                  to break on a nested subprogram without having to
16474                  specify the context.  */
16475               list_to_add = &global_symbols;
16476             }
16477           else
16478             {
16479               list_to_add = cu->list_in_scope;
16480             }
16481           break;
16482         case DW_TAG_inlined_subroutine:
16483           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16484              finish_block.  */
16485           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16486           SYMBOL_INLINED (sym) = 1;
16487           list_to_add = cu->list_in_scope;
16488           break;
16489         case DW_TAG_template_value_param:
16490           suppress_add = 1;
16491           /* Fall through.  */
16492         case DW_TAG_constant:
16493         case DW_TAG_variable:
16494         case DW_TAG_member:
16495           /* Compilation with minimal debug info may result in
16496              variables with missing type entries.  Change the
16497              misleading `void' type to something sensible.  */
16498           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16499             SYMBOL_TYPE (sym)
16500               = objfile_type (objfile)->nodebug_data_symbol;
16501
16502           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16503           /* In the case of DW_TAG_member, we should only be called for
16504              static const members.  */
16505           if (die->tag == DW_TAG_member)
16506             {
16507               /* dwarf2_add_field uses die_is_declaration,
16508                  so we do the same.  */
16509               gdb_assert (die_is_declaration (die, cu));
16510               gdb_assert (attr);
16511             }
16512           if (attr)
16513             {
16514               dwarf2_const_value (attr, sym, cu);
16515               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16516               if (!suppress_add)
16517                 {
16518                   if (attr2 && (DW_UNSND (attr2) != 0))
16519                     list_to_add = &global_symbols;
16520                   else
16521                     list_to_add = cu->list_in_scope;
16522                 }
16523               break;
16524             }
16525           attr = dwarf2_attr (die, DW_AT_location, cu);
16526           if (attr)
16527             {
16528               var_decode_location (attr, sym, cu);
16529               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16530
16531               /* Fortran explicitly imports any global symbols to the local
16532                  scope by DW_TAG_common_block.  */
16533               if (cu->language == language_fortran && die->parent
16534                   && die->parent->tag == DW_TAG_common_block)
16535                 attr2 = NULL;
16536
16537               if (SYMBOL_CLASS (sym) == LOC_STATIC
16538                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16539                   && !dwarf2_per_objfile->has_section_at_zero)
16540                 {
16541                   /* When a static variable is eliminated by the linker,
16542                      the corresponding debug information is not stripped
16543                      out, but the variable address is set to null;
16544                      do not add such variables into symbol table.  */
16545                 }
16546               else if (attr2 && (DW_UNSND (attr2) != 0))
16547                 {
16548                   /* Workaround gfortran PR debug/40040 - it uses
16549                      DW_AT_location for variables in -fPIC libraries which may
16550                      get overriden by other libraries/executable and get
16551                      a different address.  Resolve it by the minimal symbol
16552                      which may come from inferior's executable using copy
16553                      relocation.  Make this workaround only for gfortran as for
16554                      other compilers GDB cannot guess the minimal symbol
16555                      Fortran mangling kind.  */
16556                   if (cu->language == language_fortran && die->parent
16557                       && die->parent->tag == DW_TAG_module
16558                       && cu->producer
16559                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16560                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16561
16562                   /* A variable with DW_AT_external is never static,
16563                      but it may be block-scoped.  */
16564                   list_to_add = (cu->list_in_scope == &file_symbols
16565                                  ? &global_symbols : cu->list_in_scope);
16566                 }
16567               else
16568                 list_to_add = cu->list_in_scope;
16569             }
16570           else
16571             {
16572               /* We do not know the address of this symbol.
16573                  If it is an external symbol and we have type information
16574                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16575                  The address of the variable will then be determined from
16576                  the minimal symbol table whenever the variable is
16577                  referenced.  */
16578               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16579
16580               /* Fortran explicitly imports any global symbols to the local
16581                  scope by DW_TAG_common_block.  */
16582               if (cu->language == language_fortran && die->parent
16583                   && die->parent->tag == DW_TAG_common_block)
16584                 {
16585                   /* SYMBOL_CLASS doesn't matter here because
16586                      read_common_block is going to reset it.  */
16587                   if (!suppress_add)
16588                     list_to_add = cu->list_in_scope;
16589                 }
16590               else if (attr2 && (DW_UNSND (attr2) != 0)
16591                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16592                 {
16593                   /* A variable with DW_AT_external is never static, but it
16594                      may be block-scoped.  */
16595                   list_to_add = (cu->list_in_scope == &file_symbols
16596                                  ? &global_symbols : cu->list_in_scope);
16597
16598                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16599                 }
16600               else if (!die_is_declaration (die, cu))
16601                 {
16602                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16603                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16604                   if (!suppress_add)
16605                     list_to_add = cu->list_in_scope;
16606                 }
16607             }
16608           break;
16609         case DW_TAG_formal_parameter:
16610           /* If we are inside a function, mark this as an argument.  If
16611              not, we might be looking at an argument to an inlined function
16612              when we do not have enough information to show inlined frames;
16613              pretend it's a local variable in that case so that the user can
16614              still see it.  */
16615           if (context_stack_depth > 0
16616               && context_stack[context_stack_depth - 1].name != NULL)
16617             SYMBOL_IS_ARGUMENT (sym) = 1;
16618           attr = dwarf2_attr (die, DW_AT_location, cu);
16619           if (attr)
16620             {
16621               var_decode_location (attr, sym, cu);
16622             }
16623           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16624           if (attr)
16625             {
16626               dwarf2_const_value (attr, sym, cu);
16627             }
16628
16629           list_to_add = cu->list_in_scope;
16630           break;
16631         case DW_TAG_unspecified_parameters:
16632           /* From varargs functions; gdb doesn't seem to have any
16633              interest in this information, so just ignore it for now.
16634              (FIXME?) */
16635           break;
16636         case DW_TAG_template_type_param:
16637           suppress_add = 1;
16638           /* Fall through.  */
16639         case DW_TAG_class_type:
16640         case DW_TAG_interface_type:
16641         case DW_TAG_structure_type:
16642         case DW_TAG_union_type:
16643         case DW_TAG_set_type:
16644         case DW_TAG_enumeration_type:
16645           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16646           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16647
16648           {
16649             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16650                really ever be static objects: otherwise, if you try
16651                to, say, break of a class's method and you're in a file
16652                which doesn't mention that class, it won't work unless
16653                the check for all static symbols in lookup_symbol_aux
16654                saves you.  See the OtherFileClass tests in
16655                gdb.c++/namespace.exp.  */
16656
16657             if (!suppress_add)
16658               {
16659                 list_to_add = (cu->list_in_scope == &file_symbols
16660                                && (cu->language == language_cplus
16661                                    || cu->language == language_java)
16662                                ? &global_symbols : cu->list_in_scope);
16663
16664                 /* The semantics of C++ state that "struct foo {
16665                    ... }" also defines a typedef for "foo".  A Java
16666                    class declaration also defines a typedef for the
16667                    class.  */
16668                 if (cu->language == language_cplus
16669                     || cu->language == language_java
16670                     || cu->language == language_ada)
16671                   {
16672                     /* The symbol's name is already allocated along
16673                        with this objfile, so we don't need to
16674                        duplicate it for the type.  */
16675                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16676                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16677                   }
16678               }
16679           }
16680           break;
16681         case DW_TAG_typedef:
16682           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16683           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16684           list_to_add = cu->list_in_scope;
16685           break;
16686         case DW_TAG_base_type:
16687         case DW_TAG_subrange_type:
16688           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16689           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16690           list_to_add = cu->list_in_scope;
16691           break;
16692         case DW_TAG_enumerator:
16693           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16694           if (attr)
16695             {
16696               dwarf2_const_value (attr, sym, cu);
16697             }
16698           {
16699             /* NOTE: carlton/2003-11-10: See comment above in the
16700                DW_TAG_class_type, etc. block.  */
16701
16702             list_to_add = (cu->list_in_scope == &file_symbols
16703                            && (cu->language == language_cplus
16704                                || cu->language == language_java)
16705                            ? &global_symbols : cu->list_in_scope);
16706           }
16707           break;
16708         case DW_TAG_namespace:
16709           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16710           list_to_add = &global_symbols;
16711           break;
16712         case DW_TAG_common_block:
16713           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16714           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16715           add_symbol_to_list (sym, cu->list_in_scope);
16716           break;
16717         default:
16718           /* Not a tag we recognize.  Hopefully we aren't processing
16719              trash data, but since we must specifically ignore things
16720              we don't recognize, there is nothing else we should do at
16721              this point.  */
16722           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16723                      dwarf_tag_name (die->tag));
16724           break;
16725         }
16726
16727       if (suppress_add)
16728         {
16729           sym->hash_next = objfile->template_symbols;
16730           objfile->template_symbols = sym;
16731           list_to_add = NULL;
16732         }
16733
16734       if (list_to_add != NULL)
16735         add_symbol_to_list (sym, list_to_add);
16736
16737       /* For the benefit of old versions of GCC, check for anonymous
16738          namespaces based on the demangled name.  */
16739       if (!cu->processing_has_namespace_info
16740           && cu->language == language_cplus)
16741         cp_scan_for_anonymous_namespaces (sym, objfile);
16742     }
16743   return (sym);
16744 }
16745
16746 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16747
16748 static struct symbol *
16749 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16750 {
16751   return new_symbol_full (die, type, cu, NULL);
16752 }
16753
16754 /* Given an attr with a DW_FORM_dataN value in host byte order,
16755    zero-extend it as appropriate for the symbol's type.  The DWARF
16756    standard (v4) is not entirely clear about the meaning of using
16757    DW_FORM_dataN for a constant with a signed type, where the type is
16758    wider than the data.  The conclusion of a discussion on the DWARF
16759    list was that this is unspecified.  We choose to always zero-extend
16760    because that is the interpretation long in use by GCC.  */
16761
16762 static gdb_byte *
16763 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
16764                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16765 {
16766   struct objfile *objfile = cu->objfile;
16767   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16768                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16769   LONGEST l = DW_UNSND (attr);
16770
16771   if (bits < sizeof (*value) * 8)
16772     {
16773       l &= ((LONGEST) 1 << bits) - 1;
16774       *value = l;
16775     }
16776   else if (bits == sizeof (*value) * 8)
16777     *value = l;
16778   else
16779     {
16780       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16781       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16782       return bytes;
16783     }
16784
16785   return NULL;
16786 }
16787
16788 /* Read a constant value from an attribute.  Either set *VALUE, or if
16789    the value does not fit in *VALUE, set *BYTES - either already
16790    allocated on the objfile obstack, or newly allocated on OBSTACK,
16791    or, set *BATON, if we translated the constant to a location
16792    expression.  */
16793
16794 static void
16795 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
16796                          const char *name, struct obstack *obstack,
16797                          struct dwarf2_cu *cu,
16798                          LONGEST *value, const gdb_byte **bytes,
16799                          struct dwarf2_locexpr_baton **baton)
16800 {
16801   struct objfile *objfile = cu->objfile;
16802   struct comp_unit_head *cu_header = &cu->header;
16803   struct dwarf_block *blk;
16804   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16805                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16806
16807   *value = 0;
16808   *bytes = NULL;
16809   *baton = NULL;
16810
16811   switch (attr->form)
16812     {
16813     case DW_FORM_addr:
16814     case DW_FORM_GNU_addr_index:
16815       {
16816         gdb_byte *data;
16817
16818         if (TYPE_LENGTH (type) != cu_header->addr_size)
16819           dwarf2_const_value_length_mismatch_complaint (name,
16820                                                         cu_header->addr_size,
16821                                                         TYPE_LENGTH (type));
16822         /* Symbols of this form are reasonably rare, so we just
16823            piggyback on the existing location code rather than writing
16824            a new implementation of symbol_computed_ops.  */
16825         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16826         (*baton)->per_cu = cu->per_cu;
16827         gdb_assert ((*baton)->per_cu);
16828
16829         (*baton)->size = 2 + cu_header->addr_size;
16830         data = obstack_alloc (obstack, (*baton)->size);
16831         (*baton)->data = data;
16832
16833         data[0] = DW_OP_addr;
16834         store_unsigned_integer (&data[1], cu_header->addr_size,
16835                                 byte_order, DW_ADDR (attr));
16836         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16837       }
16838       break;
16839     case DW_FORM_string:
16840     case DW_FORM_strp:
16841     case DW_FORM_GNU_str_index:
16842     case DW_FORM_GNU_strp_alt:
16843       /* DW_STRING is already allocated on the objfile obstack, point
16844          directly to it.  */
16845       *bytes = (const gdb_byte *) DW_STRING (attr);
16846       break;
16847     case DW_FORM_block1:
16848     case DW_FORM_block2:
16849     case DW_FORM_block4:
16850     case DW_FORM_block:
16851     case DW_FORM_exprloc:
16852       blk = DW_BLOCK (attr);
16853       if (TYPE_LENGTH (type) != blk->size)
16854         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16855                                                       TYPE_LENGTH (type));
16856       *bytes = blk->data;
16857       break;
16858
16859       /* The DW_AT_const_value attributes are supposed to carry the
16860          symbol's value "represented as it would be on the target
16861          architecture."  By the time we get here, it's already been
16862          converted to host endianness, so we just need to sign- or
16863          zero-extend it as appropriate.  */
16864     case DW_FORM_data1:
16865       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16866       break;
16867     case DW_FORM_data2:
16868       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16869       break;
16870     case DW_FORM_data4:
16871       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16872       break;
16873     case DW_FORM_data8:
16874       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16875       break;
16876
16877     case DW_FORM_sdata:
16878       *value = DW_SND (attr);
16879       break;
16880
16881     case DW_FORM_udata:
16882       *value = DW_UNSND (attr);
16883       break;
16884
16885     default:
16886       complaint (&symfile_complaints,
16887                  _("unsupported const value attribute form: '%s'"),
16888                  dwarf_form_name (attr->form));
16889       *value = 0;
16890       break;
16891     }
16892 }
16893
16894
16895 /* Copy constant value from an attribute to a symbol.  */
16896
16897 static void
16898 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
16899                     struct dwarf2_cu *cu)
16900 {
16901   struct objfile *objfile = cu->objfile;
16902   struct comp_unit_head *cu_header = &cu->header;
16903   LONGEST value;
16904   const gdb_byte *bytes;
16905   struct dwarf2_locexpr_baton *baton;
16906
16907   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16908                            SYMBOL_PRINT_NAME (sym),
16909                            &objfile->objfile_obstack, cu,
16910                            &value, &bytes, &baton);
16911
16912   if (baton != NULL)
16913     {
16914       SYMBOL_LOCATION_BATON (sym) = baton;
16915       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16916     }
16917   else if (bytes != NULL)
16918      {
16919       SYMBOL_VALUE_BYTES (sym) = bytes;
16920       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16921     }
16922   else
16923     {
16924       SYMBOL_VALUE (sym) = value;
16925       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16926     }
16927 }
16928
16929 /* Return the type of the die in question using its DW_AT_type attribute.  */
16930
16931 static struct type *
16932 die_type (struct die_info *die, struct dwarf2_cu *cu)
16933 {
16934   struct attribute *type_attr;
16935
16936   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16937   if (!type_attr)
16938     {
16939       /* A missing DW_AT_type represents a void type.  */
16940       return objfile_type (cu->objfile)->builtin_void;
16941     }
16942
16943   return lookup_die_type (die, type_attr, cu);
16944 }
16945
16946 /* True iff CU's producer generates GNAT Ada auxiliary information
16947    that allows to find parallel types through that information instead
16948    of having to do expensive parallel lookups by type name.  */
16949
16950 static int
16951 need_gnat_info (struct dwarf2_cu *cu)
16952 {
16953   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16954      of GNAT produces this auxiliary information, without any indication
16955      that it is produced.  Part of enhancing the FSF version of GNAT
16956      to produce that information will be to put in place an indicator
16957      that we can use in order to determine whether the descriptive type
16958      info is available or not.  One suggestion that has been made is
16959      to use a new attribute, attached to the CU die.  For now, assume
16960      that the descriptive type info is not available.  */
16961   return 0;
16962 }
16963
16964 /* Return the auxiliary type of the die in question using its
16965    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16966    attribute is not present.  */
16967
16968 static struct type *
16969 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16970 {
16971   struct attribute *type_attr;
16972
16973   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16974   if (!type_attr)
16975     return NULL;
16976
16977   return lookup_die_type (die, type_attr, cu);
16978 }
16979
16980 /* If DIE has a descriptive_type attribute, then set the TYPE's
16981    descriptive type accordingly.  */
16982
16983 static void
16984 set_descriptive_type (struct type *type, struct die_info *die,
16985                       struct dwarf2_cu *cu)
16986 {
16987   struct type *descriptive_type = die_descriptive_type (die, cu);
16988
16989   if (descriptive_type)
16990     {
16991       ALLOCATE_GNAT_AUX_TYPE (type);
16992       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16993     }
16994 }
16995
16996 /* Return the containing type of the die in question using its
16997    DW_AT_containing_type attribute.  */
16998
16999 static struct type *
17000 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17001 {
17002   struct attribute *type_attr;
17003
17004   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17005   if (!type_attr)
17006     error (_("Dwarf Error: Problem turning containing type into gdb type "
17007              "[in module %s]"), cu->objfile->name);
17008
17009   return lookup_die_type (die, type_attr, cu);
17010 }
17011
17012 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17013
17014 static struct type *
17015 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17016 {
17017   struct objfile *objfile = dwarf2_per_objfile->objfile;
17018   char *message, *saved;
17019
17020   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17021                         objfile->name,
17022                         cu->header.offset.sect_off,
17023                         die->offset.sect_off);
17024   saved = obstack_copy0 (&objfile->objfile_obstack,
17025                          message, strlen (message));
17026   xfree (message);
17027
17028   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17029 }
17030
17031 /* Look up the type of DIE in CU using its type attribute ATTR.
17032    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17033    DW_AT_containing_type.
17034    If there is no type substitute an error marker.  */
17035
17036 static struct type *
17037 lookup_die_type (struct die_info *die, const struct attribute *attr,
17038                  struct dwarf2_cu *cu)
17039 {
17040   struct objfile *objfile = cu->objfile;
17041   struct type *this_type;
17042
17043   gdb_assert (attr->name == DW_AT_type
17044               || attr->name == DW_AT_GNAT_descriptive_type
17045               || attr->name == DW_AT_containing_type);
17046
17047   /* First see if we have it cached.  */
17048
17049   if (attr->form == DW_FORM_GNU_ref_alt)
17050     {
17051       struct dwarf2_per_cu_data *per_cu;
17052       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17053
17054       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17055       this_type = get_die_type_at_offset (offset, per_cu);
17056     }
17057   else if (attr_form_is_ref (attr))
17058     {
17059       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17060
17061       this_type = get_die_type_at_offset (offset, cu->per_cu);
17062     }
17063   else if (attr->form == DW_FORM_ref_sig8)
17064     {
17065       ULONGEST signature = DW_SIGNATURE (attr);
17066
17067       return get_signatured_type (die, signature, cu);
17068     }
17069   else
17070     {
17071       complaint (&symfile_complaints,
17072                  _("Dwarf Error: Bad type attribute %s in DIE"
17073                    " at 0x%x [in module %s]"),
17074                  dwarf_attr_name (attr->name), die->offset.sect_off,
17075                  objfile->name);
17076       return build_error_marker_type (cu, die);
17077     }
17078
17079   /* If not cached we need to read it in.  */
17080
17081   if (this_type == NULL)
17082     {
17083       struct die_info *type_die = NULL;
17084       struct dwarf2_cu *type_cu = cu;
17085
17086       if (attr_form_is_ref (attr))
17087         type_die = follow_die_ref (die, attr, &type_cu);
17088       if (type_die == NULL)
17089         return build_error_marker_type (cu, die);
17090       /* If we find the type now, it's probably because the type came
17091          from an inter-CU reference and the type's CU got expanded before
17092          ours.  */
17093       this_type = read_type_die (type_die, type_cu);
17094     }
17095
17096   /* If we still don't have a type use an error marker.  */
17097
17098   if (this_type == NULL)
17099     return build_error_marker_type (cu, die);
17100
17101   return this_type;
17102 }
17103
17104 /* Return the type in DIE, CU.
17105    Returns NULL for invalid types.
17106
17107    This first does a lookup in die_type_hash,
17108    and only reads the die in if necessary.
17109
17110    NOTE: This can be called when reading in partial or full symbols.  */
17111
17112 static struct type *
17113 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17114 {
17115   struct type *this_type;
17116
17117   this_type = get_die_type (die, cu);
17118   if (this_type)
17119     return this_type;
17120
17121   return read_type_die_1 (die, cu);
17122 }
17123
17124 /* Read the type in DIE, CU.
17125    Returns NULL for invalid types.  */
17126
17127 static struct type *
17128 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17129 {
17130   struct type *this_type = NULL;
17131
17132   switch (die->tag)
17133     {
17134     case DW_TAG_class_type:
17135     case DW_TAG_interface_type:
17136     case DW_TAG_structure_type:
17137     case DW_TAG_union_type:
17138       this_type = read_structure_type (die, cu);
17139       break;
17140     case DW_TAG_enumeration_type:
17141       this_type = read_enumeration_type (die, cu);
17142       break;
17143     case DW_TAG_subprogram:
17144     case DW_TAG_subroutine_type:
17145     case DW_TAG_inlined_subroutine:
17146       this_type = read_subroutine_type (die, cu);
17147       break;
17148     case DW_TAG_array_type:
17149       this_type = read_array_type (die, cu);
17150       break;
17151     case DW_TAG_set_type:
17152       this_type = read_set_type (die, cu);
17153       break;
17154     case DW_TAG_pointer_type:
17155       this_type = read_tag_pointer_type (die, cu);
17156       break;
17157     case DW_TAG_ptr_to_member_type:
17158       this_type = read_tag_ptr_to_member_type (die, cu);
17159       break;
17160     case DW_TAG_reference_type:
17161       this_type = read_tag_reference_type (die, cu);
17162       break;
17163     case DW_TAG_const_type:
17164       this_type = read_tag_const_type (die, cu);
17165       break;
17166     case DW_TAG_volatile_type:
17167       this_type = read_tag_volatile_type (die, cu);
17168       break;
17169     case DW_TAG_restrict_type:
17170       this_type = read_tag_restrict_type (die, cu);
17171       break;
17172     case DW_TAG_string_type:
17173       this_type = read_tag_string_type (die, cu);
17174       break;
17175     case DW_TAG_typedef:
17176       this_type = read_typedef (die, cu);
17177       break;
17178     case DW_TAG_subrange_type:
17179       this_type = read_subrange_type (die, cu);
17180       break;
17181     case DW_TAG_base_type:
17182       this_type = read_base_type (die, cu);
17183       break;
17184     case DW_TAG_unspecified_type:
17185       this_type = read_unspecified_type (die, cu);
17186       break;
17187     case DW_TAG_namespace:
17188       this_type = read_namespace_type (die, cu);
17189       break;
17190     case DW_TAG_module:
17191       this_type = read_module_type (die, cu);
17192       break;
17193     default:
17194       complaint (&symfile_complaints,
17195                  _("unexpected tag in read_type_die: '%s'"),
17196                  dwarf_tag_name (die->tag));
17197       break;
17198     }
17199
17200   return this_type;
17201 }
17202
17203 /* See if we can figure out if the class lives in a namespace.  We do
17204    this by looking for a member function; its demangled name will
17205    contain namespace info, if there is any.
17206    Return the computed name or NULL.
17207    Space for the result is allocated on the objfile's obstack.
17208    This is the full-die version of guess_partial_die_structure_name.
17209    In this case we know DIE has no useful parent.  */
17210
17211 static char *
17212 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17213 {
17214   struct die_info *spec_die;
17215   struct dwarf2_cu *spec_cu;
17216   struct die_info *child;
17217
17218   spec_cu = cu;
17219   spec_die = die_specification (die, &spec_cu);
17220   if (spec_die != NULL)
17221     {
17222       die = spec_die;
17223       cu = spec_cu;
17224     }
17225
17226   for (child = die->child;
17227        child != NULL;
17228        child = child->sibling)
17229     {
17230       if (child->tag == DW_TAG_subprogram)
17231         {
17232           struct attribute *attr;
17233
17234           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17235           if (attr == NULL)
17236             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17237           if (attr != NULL)
17238             {
17239               char *actual_name
17240                 = language_class_name_from_physname (cu->language_defn,
17241                                                      DW_STRING (attr));
17242               char *name = NULL;
17243
17244               if (actual_name != NULL)
17245                 {
17246                   const char *die_name = dwarf2_name (die, cu);
17247
17248                   if (die_name != NULL
17249                       && strcmp (die_name, actual_name) != 0)
17250                     {
17251                       /* Strip off the class name from the full name.
17252                          We want the prefix.  */
17253                       int die_name_len = strlen (die_name);
17254                       int actual_name_len = strlen (actual_name);
17255
17256                       /* Test for '::' as a sanity check.  */
17257                       if (actual_name_len > die_name_len + 2
17258                           && actual_name[actual_name_len
17259                                          - die_name_len - 1] == ':')
17260                         name =
17261                           obstack_copy0 (&cu->objfile->objfile_obstack,
17262                                          actual_name,
17263                                          actual_name_len - die_name_len - 2);
17264                     }
17265                 }
17266               xfree (actual_name);
17267               return name;
17268             }
17269         }
17270     }
17271
17272   return NULL;
17273 }
17274
17275 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17276    prefix part in such case.  See
17277    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17278
17279 static char *
17280 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17281 {
17282   struct attribute *attr;
17283   char *base;
17284
17285   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17286       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17287     return NULL;
17288
17289   attr = dwarf2_attr (die, DW_AT_name, cu);
17290   if (attr != NULL && DW_STRING (attr) != NULL)
17291     return NULL;
17292
17293   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17294   if (attr == NULL)
17295     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17296   if (attr == NULL || DW_STRING (attr) == NULL)
17297     return NULL;
17298
17299   /* dwarf2_name had to be already called.  */
17300   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17301
17302   /* Strip the base name, keep any leading namespaces/classes.  */
17303   base = strrchr (DW_STRING (attr), ':');
17304   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17305     return "";
17306
17307   return obstack_copy0 (&cu->objfile->objfile_obstack,
17308                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17309 }
17310
17311 /* Return the name of the namespace/class that DIE is defined within,
17312    or "" if we can't tell.  The caller should not xfree the result.
17313
17314    For example, if we're within the method foo() in the following
17315    code:
17316
17317    namespace N {
17318      class C {
17319        void foo () {
17320        }
17321      };
17322    }
17323
17324    then determine_prefix on foo's die will return "N::C".  */
17325
17326 static const char *
17327 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17328 {
17329   struct die_info *parent, *spec_die;
17330   struct dwarf2_cu *spec_cu;
17331   struct type *parent_type;
17332   char *retval;
17333
17334   if (cu->language != language_cplus && cu->language != language_java
17335       && cu->language != language_fortran)
17336     return "";
17337
17338   retval = anonymous_struct_prefix (die, cu);
17339   if (retval)
17340     return retval;
17341
17342   /* We have to be careful in the presence of DW_AT_specification.
17343      For example, with GCC 3.4, given the code
17344
17345      namespace N {
17346        void foo() {
17347          // Definition of N::foo.
17348        }
17349      }
17350
17351      then we'll have a tree of DIEs like this:
17352
17353      1: DW_TAG_compile_unit
17354        2: DW_TAG_namespace        // N
17355          3: DW_TAG_subprogram     // declaration of N::foo
17356        4: DW_TAG_subprogram       // definition of N::foo
17357             DW_AT_specification   // refers to die #3
17358
17359      Thus, when processing die #4, we have to pretend that we're in
17360      the context of its DW_AT_specification, namely the contex of die
17361      #3.  */
17362   spec_cu = cu;
17363   spec_die = die_specification (die, &spec_cu);
17364   if (spec_die == NULL)
17365     parent = die->parent;
17366   else
17367     {
17368       parent = spec_die->parent;
17369       cu = spec_cu;
17370     }
17371
17372   if (parent == NULL)
17373     return "";
17374   else if (parent->building_fullname)
17375     {
17376       const char *name;
17377       const char *parent_name;
17378
17379       /* It has been seen on RealView 2.2 built binaries,
17380          DW_TAG_template_type_param types actually _defined_ as
17381          children of the parent class:
17382
17383          enum E {};
17384          template class <class Enum> Class{};
17385          Class<enum E> class_e;
17386
17387          1: DW_TAG_class_type (Class)
17388            2: DW_TAG_enumeration_type (E)
17389              3: DW_TAG_enumerator (enum1:0)
17390              3: DW_TAG_enumerator (enum2:1)
17391              ...
17392            2: DW_TAG_template_type_param
17393               DW_AT_type  DW_FORM_ref_udata (E)
17394
17395          Besides being broken debug info, it can put GDB into an
17396          infinite loop.  Consider:
17397
17398          When we're building the full name for Class<E>, we'll start
17399          at Class, and go look over its template type parameters,
17400          finding E.  We'll then try to build the full name of E, and
17401          reach here.  We're now trying to build the full name of E,
17402          and look over the parent DIE for containing scope.  In the
17403          broken case, if we followed the parent DIE of E, we'd again
17404          find Class, and once again go look at its template type
17405          arguments, etc., etc.  Simply don't consider such parent die
17406          as source-level parent of this die (it can't be, the language
17407          doesn't allow it), and break the loop here.  */
17408       name = dwarf2_name (die, cu);
17409       parent_name = dwarf2_name (parent, cu);
17410       complaint (&symfile_complaints,
17411                  _("template param type '%s' defined within parent '%s'"),
17412                  name ? name : "<unknown>",
17413                  parent_name ? parent_name : "<unknown>");
17414       return "";
17415     }
17416   else
17417     switch (parent->tag)
17418       {
17419       case DW_TAG_namespace:
17420         parent_type = read_type_die (parent, cu);
17421         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17422            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17423            Work around this problem here.  */
17424         if (cu->language == language_cplus
17425             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17426           return "";
17427         /* We give a name to even anonymous namespaces.  */
17428         return TYPE_TAG_NAME (parent_type);
17429       case DW_TAG_class_type:
17430       case DW_TAG_interface_type:
17431       case DW_TAG_structure_type:
17432       case DW_TAG_union_type:
17433       case DW_TAG_module:
17434         parent_type = read_type_die (parent, cu);
17435         if (TYPE_TAG_NAME (parent_type) != NULL)
17436           return TYPE_TAG_NAME (parent_type);
17437         else
17438           /* An anonymous structure is only allowed non-static data
17439              members; no typedefs, no member functions, et cetera.
17440              So it does not need a prefix.  */
17441           return "";
17442       case DW_TAG_compile_unit:
17443       case DW_TAG_partial_unit:
17444         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17445         if (cu->language == language_cplus
17446             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17447             && die->child != NULL
17448             && (die->tag == DW_TAG_class_type
17449                 || die->tag == DW_TAG_structure_type
17450                 || die->tag == DW_TAG_union_type))
17451           {
17452             char *name = guess_full_die_structure_name (die, cu);
17453             if (name != NULL)
17454               return name;
17455           }
17456         return "";
17457       default:
17458         return determine_prefix (parent, cu);
17459       }
17460 }
17461
17462 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17463    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17464    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17465    an obconcat, otherwise allocate storage for the result.  The CU argument is
17466    used to determine the language and hence, the appropriate separator.  */
17467
17468 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17469
17470 static char *
17471 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17472                  int physname, struct dwarf2_cu *cu)
17473 {
17474   const char *lead = "";
17475   const char *sep;
17476
17477   if (suffix == NULL || suffix[0] == '\0'
17478       || prefix == NULL || prefix[0] == '\0')
17479     sep = "";
17480   else if (cu->language == language_java)
17481     sep = ".";
17482   else if (cu->language == language_fortran && physname)
17483     {
17484       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17485          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17486
17487       lead = "__";
17488       sep = "_MOD_";
17489     }
17490   else
17491     sep = "::";
17492
17493   if (prefix == NULL)
17494     prefix = "";
17495   if (suffix == NULL)
17496     suffix = "";
17497
17498   if (obs == NULL)
17499     {
17500       char *retval
17501         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17502
17503       strcpy (retval, lead);
17504       strcat (retval, prefix);
17505       strcat (retval, sep);
17506       strcat (retval, suffix);
17507       return retval;
17508     }
17509   else
17510     {
17511       /* We have an obstack.  */
17512       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17513     }
17514 }
17515
17516 /* Return sibling of die, NULL if no sibling.  */
17517
17518 static struct die_info *
17519 sibling_die (struct die_info *die)
17520 {
17521   return die->sibling;
17522 }
17523
17524 /* Get name of a die, return NULL if not found.  */
17525
17526 static const char *
17527 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17528                           struct obstack *obstack)
17529 {
17530   if (name && cu->language == language_cplus)
17531     {
17532       char *canon_name = cp_canonicalize_string (name);
17533
17534       if (canon_name != NULL)
17535         {
17536           if (strcmp (canon_name, name) != 0)
17537             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17538           xfree (canon_name);
17539         }
17540     }
17541
17542   return name;
17543 }
17544
17545 /* Get name of a die, return NULL if not found.  */
17546
17547 static const char *
17548 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17549 {
17550   struct attribute *attr;
17551
17552   attr = dwarf2_attr (die, DW_AT_name, cu);
17553   if ((!attr || !DW_STRING (attr))
17554       && die->tag != DW_TAG_class_type
17555       && die->tag != DW_TAG_interface_type
17556       && die->tag != DW_TAG_structure_type
17557       && die->tag != DW_TAG_union_type)
17558     return NULL;
17559
17560   switch (die->tag)
17561     {
17562     case DW_TAG_compile_unit:
17563     case DW_TAG_partial_unit:
17564       /* Compilation units have a DW_AT_name that is a filename, not
17565          a source language identifier.  */
17566     case DW_TAG_enumeration_type:
17567     case DW_TAG_enumerator:
17568       /* These tags always have simple identifiers already; no need
17569          to canonicalize them.  */
17570       return DW_STRING (attr);
17571
17572     case DW_TAG_subprogram:
17573       /* Java constructors will all be named "<init>", so return
17574          the class name when we see this special case.  */
17575       if (cu->language == language_java
17576           && DW_STRING (attr) != NULL
17577           && strcmp (DW_STRING (attr), "<init>") == 0)
17578         {
17579           struct dwarf2_cu *spec_cu = cu;
17580           struct die_info *spec_die;
17581
17582           /* GCJ will output '<init>' for Java constructor names.
17583              For this special case, return the name of the parent class.  */
17584
17585           /* GCJ may output suprogram DIEs with AT_specification set.
17586              If so, use the name of the specified DIE.  */
17587           spec_die = die_specification (die, &spec_cu);
17588           if (spec_die != NULL)
17589             return dwarf2_name (spec_die, spec_cu);
17590
17591           do
17592             {
17593               die = die->parent;
17594               if (die->tag == DW_TAG_class_type)
17595                 return dwarf2_name (die, cu);
17596             }
17597           while (die->tag != DW_TAG_compile_unit
17598                  && die->tag != DW_TAG_partial_unit);
17599         }
17600       break;
17601
17602     case DW_TAG_class_type:
17603     case DW_TAG_interface_type:
17604     case DW_TAG_structure_type:
17605     case DW_TAG_union_type:
17606       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17607          structures or unions.  These were of the form "._%d" in GCC 4.1,
17608          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17609          and GCC 4.4.  We work around this problem by ignoring these.  */
17610       if (attr && DW_STRING (attr)
17611           && (strncmp (DW_STRING (attr), "._", 2) == 0
17612               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17613         return NULL;
17614
17615       /* GCC might emit a nameless typedef that has a linkage name.  See
17616          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17617       if (!attr || DW_STRING (attr) == NULL)
17618         {
17619           char *demangled = NULL;
17620
17621           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17622           if (attr == NULL)
17623             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17624
17625           if (attr == NULL || DW_STRING (attr) == NULL)
17626             return NULL;
17627
17628           /* Avoid demangling DW_STRING (attr) the second time on a second
17629              call for the same DIE.  */
17630           if (!DW_STRING_IS_CANONICAL (attr))
17631             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17632
17633           if (demangled)
17634             {
17635               char *base;
17636
17637               /* FIXME: we already did this for the partial symbol... */
17638               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17639                                                 demangled, strlen (demangled));
17640               DW_STRING_IS_CANONICAL (attr) = 1;
17641               xfree (demangled);
17642
17643               /* Strip any leading namespaces/classes, keep only the base name.
17644                  DW_AT_name for named DIEs does not contain the prefixes.  */
17645               base = strrchr (DW_STRING (attr), ':');
17646               if (base && base > DW_STRING (attr) && base[-1] == ':')
17647                 return &base[1];
17648               else
17649                 return DW_STRING (attr);
17650             }
17651         }
17652       break;
17653
17654     default:
17655       break;
17656     }
17657
17658   if (!DW_STRING_IS_CANONICAL (attr))
17659     {
17660       DW_STRING (attr)
17661         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17662                                     &cu->objfile->objfile_obstack);
17663       DW_STRING_IS_CANONICAL (attr) = 1;
17664     }
17665   return DW_STRING (attr);
17666 }
17667
17668 /* Return the die that this die in an extension of, or NULL if there
17669    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17670    containing the return value on output.  */
17671
17672 static struct die_info *
17673 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17674 {
17675   struct attribute *attr;
17676
17677   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17678   if (attr == NULL)
17679     return NULL;
17680
17681   return follow_die_ref (die, attr, ext_cu);
17682 }
17683
17684 /* Convert a DIE tag into its string name.  */
17685
17686 static const char *
17687 dwarf_tag_name (unsigned tag)
17688 {
17689   const char *name = get_DW_TAG_name (tag);
17690
17691   if (name == NULL)
17692     return "DW_TAG_<unknown>";
17693
17694   return name;
17695 }
17696
17697 /* Convert a DWARF attribute code into its string name.  */
17698
17699 static const char *
17700 dwarf_attr_name (unsigned attr)
17701 {
17702   const char *name;
17703
17704 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17705   if (attr == DW_AT_MIPS_fde)
17706     return "DW_AT_MIPS_fde";
17707 #else
17708   if (attr == DW_AT_HP_block_index)
17709     return "DW_AT_HP_block_index";
17710 #endif
17711
17712   name = get_DW_AT_name (attr);
17713
17714   if (name == NULL)
17715     return "DW_AT_<unknown>";
17716
17717   return name;
17718 }
17719
17720 /* Convert a DWARF value form code into its string name.  */
17721
17722 static const char *
17723 dwarf_form_name (unsigned form)
17724 {
17725   const char *name = get_DW_FORM_name (form);
17726
17727   if (name == NULL)
17728     return "DW_FORM_<unknown>";
17729
17730   return name;
17731 }
17732
17733 static char *
17734 dwarf_bool_name (unsigned mybool)
17735 {
17736   if (mybool)
17737     return "TRUE";
17738   else
17739     return "FALSE";
17740 }
17741
17742 /* Convert a DWARF type code into its string name.  */
17743
17744 static const char *
17745 dwarf_type_encoding_name (unsigned enc)
17746 {
17747   const char *name = get_DW_ATE_name (enc);
17748
17749   if (name == NULL)
17750     return "DW_ATE_<unknown>";
17751
17752   return name;
17753 }
17754
17755 static void
17756 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17757 {
17758   unsigned int i;
17759
17760   print_spaces (indent, f);
17761   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17762            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17763
17764   if (die->parent != NULL)
17765     {
17766       print_spaces (indent, f);
17767       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17768                           die->parent->offset.sect_off);
17769     }
17770
17771   print_spaces (indent, f);
17772   fprintf_unfiltered (f, "  has children: %s\n",
17773            dwarf_bool_name (die->child != NULL));
17774
17775   print_spaces (indent, f);
17776   fprintf_unfiltered (f, "  attributes:\n");
17777
17778   for (i = 0; i < die->num_attrs; ++i)
17779     {
17780       print_spaces (indent, f);
17781       fprintf_unfiltered (f, "    %s (%s) ",
17782                dwarf_attr_name (die->attrs[i].name),
17783                dwarf_form_name (die->attrs[i].form));
17784
17785       switch (die->attrs[i].form)
17786         {
17787         case DW_FORM_addr:
17788         case DW_FORM_GNU_addr_index:
17789           fprintf_unfiltered (f, "address: ");
17790           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17791           break;
17792         case DW_FORM_block2:
17793         case DW_FORM_block4:
17794         case DW_FORM_block:
17795         case DW_FORM_block1:
17796           fprintf_unfiltered (f, "block: size %s",
17797                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17798           break;
17799         case DW_FORM_exprloc:
17800           fprintf_unfiltered (f, "expression: size %s",
17801                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17802           break;
17803         case DW_FORM_ref_addr:
17804           fprintf_unfiltered (f, "ref address: ");
17805           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17806           break;
17807         case DW_FORM_GNU_ref_alt:
17808           fprintf_unfiltered (f, "alt ref address: ");
17809           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17810           break;
17811         case DW_FORM_ref1:
17812         case DW_FORM_ref2:
17813         case DW_FORM_ref4:
17814         case DW_FORM_ref8:
17815         case DW_FORM_ref_udata:
17816           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17817                               (long) (DW_UNSND (&die->attrs[i])));
17818           break;
17819         case DW_FORM_data1:
17820         case DW_FORM_data2:
17821         case DW_FORM_data4:
17822         case DW_FORM_data8:
17823         case DW_FORM_udata:
17824         case DW_FORM_sdata:
17825           fprintf_unfiltered (f, "constant: %s",
17826                               pulongest (DW_UNSND (&die->attrs[i])));
17827           break;
17828         case DW_FORM_sec_offset:
17829           fprintf_unfiltered (f, "section offset: %s",
17830                               pulongest (DW_UNSND (&die->attrs[i])));
17831           break;
17832         case DW_FORM_ref_sig8:
17833           fprintf_unfiltered (f, "signature: %s",
17834                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17835           break;
17836         case DW_FORM_string:
17837         case DW_FORM_strp:
17838         case DW_FORM_GNU_str_index:
17839         case DW_FORM_GNU_strp_alt:
17840           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17841                    DW_STRING (&die->attrs[i])
17842                    ? DW_STRING (&die->attrs[i]) : "",
17843                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17844           break;
17845         case DW_FORM_flag:
17846           if (DW_UNSND (&die->attrs[i]))
17847             fprintf_unfiltered (f, "flag: TRUE");
17848           else
17849             fprintf_unfiltered (f, "flag: FALSE");
17850           break;
17851         case DW_FORM_flag_present:
17852           fprintf_unfiltered (f, "flag: TRUE");
17853           break;
17854         case DW_FORM_indirect:
17855           /* The reader will have reduced the indirect form to
17856              the "base form" so this form should not occur.  */
17857           fprintf_unfiltered (f, 
17858                               "unexpected attribute form: DW_FORM_indirect");
17859           break;
17860         default:
17861           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17862                    die->attrs[i].form);
17863           break;
17864         }
17865       fprintf_unfiltered (f, "\n");
17866     }
17867 }
17868
17869 static void
17870 dump_die_for_error (struct die_info *die)
17871 {
17872   dump_die_shallow (gdb_stderr, 0, die);
17873 }
17874
17875 static void
17876 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17877 {
17878   int indent = level * 4;
17879
17880   gdb_assert (die != NULL);
17881
17882   if (level >= max_level)
17883     return;
17884
17885   dump_die_shallow (f, indent, die);
17886
17887   if (die->child != NULL)
17888     {
17889       print_spaces (indent, f);
17890       fprintf_unfiltered (f, "  Children:");
17891       if (level + 1 < max_level)
17892         {
17893           fprintf_unfiltered (f, "\n");
17894           dump_die_1 (f, level + 1, max_level, die->child);
17895         }
17896       else
17897         {
17898           fprintf_unfiltered (f,
17899                               " [not printed, max nesting level reached]\n");
17900         }
17901     }
17902
17903   if (die->sibling != NULL && level > 0)
17904     {
17905       dump_die_1 (f, level, max_level, die->sibling);
17906     }
17907 }
17908
17909 /* This is called from the pdie macro in gdbinit.in.
17910    It's not static so gcc will keep a copy callable from gdb.  */
17911
17912 void
17913 dump_die (struct die_info *die, int max_level)
17914 {
17915   dump_die_1 (gdb_stdlog, 0, max_level, die);
17916 }
17917
17918 static void
17919 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17920 {
17921   void **slot;
17922
17923   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17924                                    INSERT);
17925
17926   *slot = die;
17927 }
17928
17929 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17930    required kind.  */
17931
17932 static sect_offset
17933 dwarf2_get_ref_die_offset (const struct attribute *attr)
17934 {
17935   sect_offset retval = { DW_UNSND (attr) };
17936
17937   if (attr_form_is_ref (attr))
17938     return retval;
17939
17940   retval.sect_off = 0;
17941   complaint (&symfile_complaints,
17942              _("unsupported die ref attribute form: '%s'"),
17943              dwarf_form_name (attr->form));
17944   return retval;
17945 }
17946
17947 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17948  * the value held by the attribute is not constant.  */
17949
17950 static LONGEST
17951 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
17952 {
17953   if (attr->form == DW_FORM_sdata)
17954     return DW_SND (attr);
17955   else if (attr->form == DW_FORM_udata
17956            || attr->form == DW_FORM_data1
17957            || attr->form == DW_FORM_data2
17958            || attr->form == DW_FORM_data4
17959            || attr->form == DW_FORM_data8)
17960     return DW_UNSND (attr);
17961   else
17962     {
17963       complaint (&symfile_complaints,
17964                  _("Attribute value is not a constant (%s)"),
17965                  dwarf_form_name (attr->form));
17966       return default_value;
17967     }
17968 }
17969
17970 /* Follow reference or signature attribute ATTR of SRC_DIE.
17971    On entry *REF_CU is the CU of SRC_DIE.
17972    On exit *REF_CU is the CU of the result.  */
17973
17974 static struct die_info *
17975 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
17976                        struct dwarf2_cu **ref_cu)
17977 {
17978   struct die_info *die;
17979
17980   if (attr_form_is_ref (attr))
17981     die = follow_die_ref (src_die, attr, ref_cu);
17982   else if (attr->form == DW_FORM_ref_sig8)
17983     die = follow_die_sig (src_die, attr, ref_cu);
17984   else
17985     {
17986       dump_die_for_error (src_die);
17987       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17988              (*ref_cu)->objfile->name);
17989     }
17990
17991   return die;
17992 }
17993
17994 /* Follow reference OFFSET.
17995    On entry *REF_CU is the CU of the source die referencing OFFSET.
17996    On exit *REF_CU is the CU of the result.
17997    Returns NULL if OFFSET is invalid.  */
17998
17999 static struct die_info *
18000 follow_die_offset (sect_offset offset, int offset_in_dwz,
18001                    struct dwarf2_cu **ref_cu)
18002 {
18003   struct die_info temp_die;
18004   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18005
18006   gdb_assert (cu->per_cu != NULL);
18007
18008   target_cu = cu;
18009
18010   if (cu->per_cu->is_debug_types)
18011     {
18012       /* .debug_types CUs cannot reference anything outside their CU.
18013          If they need to, they have to reference a signatured type via
18014          DW_FORM_ref_sig8.  */
18015       if (! offset_in_cu_p (&cu->header, offset))
18016         return NULL;
18017     }
18018   else if (offset_in_dwz != cu->per_cu->is_dwz
18019            || ! offset_in_cu_p (&cu->header, offset))
18020     {
18021       struct dwarf2_per_cu_data *per_cu;
18022
18023       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18024                                                  cu->objfile);
18025
18026       /* If necessary, add it to the queue and load its DIEs.  */
18027       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18028         load_full_comp_unit (per_cu, cu->language);
18029
18030       target_cu = per_cu->cu;
18031     }
18032   else if (cu->dies == NULL)
18033     {
18034       /* We're loading full DIEs during partial symbol reading.  */
18035       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18036       load_full_comp_unit (cu->per_cu, language_minimal);
18037     }
18038
18039   *ref_cu = target_cu;
18040   temp_die.offset = offset;
18041   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18042 }
18043
18044 /* Follow reference attribute ATTR of SRC_DIE.
18045    On entry *REF_CU is the CU of SRC_DIE.
18046    On exit *REF_CU is the CU of the result.  */
18047
18048 static struct die_info *
18049 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18050                 struct dwarf2_cu **ref_cu)
18051 {
18052   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18053   struct dwarf2_cu *cu = *ref_cu;
18054   struct die_info *die;
18055
18056   die = follow_die_offset (offset,
18057                            (attr->form == DW_FORM_GNU_ref_alt
18058                             || cu->per_cu->is_dwz),
18059                            ref_cu);
18060   if (!die)
18061     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18062            "at 0x%x [in module %s]"),
18063            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
18064
18065   return die;
18066 }
18067
18068 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18069    Returned value is intended for DW_OP_call*.  Returned
18070    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18071
18072 struct dwarf2_locexpr_baton
18073 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18074                                struct dwarf2_per_cu_data *per_cu,
18075                                CORE_ADDR (*get_frame_pc) (void *baton),
18076                                void *baton)
18077 {
18078   struct dwarf2_cu *cu;
18079   struct die_info *die;
18080   struct attribute *attr;
18081   struct dwarf2_locexpr_baton retval;
18082
18083   dw2_setup (per_cu->objfile);
18084
18085   if (per_cu->cu == NULL)
18086     load_cu (per_cu);
18087   cu = per_cu->cu;
18088
18089   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18090   if (!die)
18091     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18092            offset.sect_off, per_cu->objfile->name);
18093
18094   attr = dwarf2_attr (die, DW_AT_location, cu);
18095   if (!attr)
18096     {
18097       /* DWARF: "If there is no such attribute, then there is no effect.".
18098          DATA is ignored if SIZE is 0.  */
18099
18100       retval.data = NULL;
18101       retval.size = 0;
18102     }
18103   else if (attr_form_is_section_offset (attr))
18104     {
18105       struct dwarf2_loclist_baton loclist_baton;
18106       CORE_ADDR pc = (*get_frame_pc) (baton);
18107       size_t size;
18108
18109       fill_in_loclist_baton (cu, &loclist_baton, attr);
18110
18111       retval.data = dwarf2_find_location_expression (&loclist_baton,
18112                                                      &size, pc);
18113       retval.size = size;
18114     }
18115   else
18116     {
18117       if (!attr_form_is_block (attr))
18118         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18119                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18120                offset.sect_off, per_cu->objfile->name);
18121
18122       retval.data = DW_BLOCK (attr)->data;
18123       retval.size = DW_BLOCK (attr)->size;
18124     }
18125   retval.per_cu = cu->per_cu;
18126
18127   age_cached_comp_units ();
18128
18129   return retval;
18130 }
18131
18132 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18133    offset.  */
18134
18135 struct dwarf2_locexpr_baton
18136 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18137                              struct dwarf2_per_cu_data *per_cu,
18138                              CORE_ADDR (*get_frame_pc) (void *baton),
18139                              void *baton)
18140 {
18141   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18142
18143   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18144 }
18145
18146 /* Write a constant of a given type as target-ordered bytes into
18147    OBSTACK.  */
18148
18149 static const gdb_byte *
18150 write_constant_as_bytes (struct obstack *obstack,
18151                          enum bfd_endian byte_order,
18152                          struct type *type,
18153                          ULONGEST value,
18154                          LONGEST *len)
18155 {
18156   gdb_byte *result;
18157
18158   *len = TYPE_LENGTH (type);
18159   result = obstack_alloc (obstack, *len);
18160   store_unsigned_integer (result, *len, byte_order, value);
18161
18162   return result;
18163 }
18164
18165 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18166    pointer to the constant bytes and set LEN to the length of the
18167    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18168    does not have a DW_AT_const_value, return NULL.  */
18169
18170 const gdb_byte *
18171 dwarf2_fetch_constant_bytes (sect_offset offset,
18172                              struct dwarf2_per_cu_data *per_cu,
18173                              struct obstack *obstack,
18174                              LONGEST *len)
18175 {
18176   struct dwarf2_cu *cu;
18177   struct die_info *die;
18178   struct attribute *attr;
18179   const gdb_byte *result = NULL;
18180   struct type *type;
18181   LONGEST value;
18182   enum bfd_endian byte_order;
18183
18184   dw2_setup (per_cu->objfile);
18185
18186   if (per_cu->cu == NULL)
18187     load_cu (per_cu);
18188   cu = per_cu->cu;
18189
18190   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18191   if (!die)
18192     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18193            offset.sect_off, per_cu->objfile->name);
18194
18195
18196   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18197   if (attr == NULL)
18198     return NULL;
18199
18200   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18201                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18202
18203   switch (attr->form)
18204     {
18205     case DW_FORM_addr:
18206     case DW_FORM_GNU_addr_index:
18207       {
18208         gdb_byte *tem;
18209
18210         *len = cu->header.addr_size;
18211         tem = obstack_alloc (obstack, *len);
18212         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18213         result = tem;
18214       }
18215       break;
18216     case DW_FORM_string:
18217     case DW_FORM_strp:
18218     case DW_FORM_GNU_str_index:
18219     case DW_FORM_GNU_strp_alt:
18220       /* DW_STRING is already allocated on the objfile obstack, point
18221          directly to it.  */
18222       result = (const gdb_byte *) DW_STRING (attr);
18223       *len = strlen (DW_STRING (attr));
18224       break;
18225     case DW_FORM_block1:
18226     case DW_FORM_block2:
18227     case DW_FORM_block4:
18228     case DW_FORM_block:
18229     case DW_FORM_exprloc:
18230       result = DW_BLOCK (attr)->data;
18231       *len = DW_BLOCK (attr)->size;
18232       break;
18233
18234       /* The DW_AT_const_value attributes are supposed to carry the
18235          symbol's value "represented as it would be on the target
18236          architecture."  By the time we get here, it's already been
18237          converted to host endianness, so we just need to sign- or
18238          zero-extend it as appropriate.  */
18239     case DW_FORM_data1:
18240       type = die_type (die, cu);
18241       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18242       if (result == NULL)
18243         result = write_constant_as_bytes (obstack, byte_order,
18244                                           type, value, len);
18245       break;
18246     case DW_FORM_data2:
18247       type = die_type (die, cu);
18248       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18249       if (result == NULL)
18250         result = write_constant_as_bytes (obstack, byte_order,
18251                                           type, value, len);
18252       break;
18253     case DW_FORM_data4:
18254       type = die_type (die, cu);
18255       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18256       if (result == NULL)
18257         result = write_constant_as_bytes (obstack, byte_order,
18258                                           type, value, len);
18259       break;
18260     case DW_FORM_data8:
18261       type = die_type (die, cu);
18262       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18263       if (result == NULL)
18264         result = write_constant_as_bytes (obstack, byte_order,
18265                                           type, value, len);
18266       break;
18267
18268     case DW_FORM_sdata:
18269       type = die_type (die, cu);
18270       result = write_constant_as_bytes (obstack, byte_order,
18271                                         type, DW_SND (attr), len);
18272       break;
18273
18274     case DW_FORM_udata:
18275       type = die_type (die, cu);
18276       result = write_constant_as_bytes (obstack, byte_order,
18277                                         type, DW_UNSND (attr), len);
18278       break;
18279
18280     default:
18281       complaint (&symfile_complaints,
18282                  _("unsupported const value attribute form: '%s'"),
18283                  dwarf_form_name (attr->form));
18284       break;
18285     }
18286
18287   return result;
18288 }
18289
18290 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18291    PER_CU.  */
18292
18293 struct type *
18294 dwarf2_get_die_type (cu_offset die_offset,
18295                      struct dwarf2_per_cu_data *per_cu)
18296 {
18297   sect_offset die_offset_sect;
18298
18299   dw2_setup (per_cu->objfile);
18300
18301   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18302   return get_die_type_at_offset (die_offset_sect, per_cu);
18303 }
18304
18305 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18306    On entry *REF_CU is the CU of SRC_DIE.
18307    On exit *REF_CU is the CU of the result.
18308    Returns NULL if the referenced DIE isn't found.  */
18309
18310 static struct die_info *
18311 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18312                   struct dwarf2_cu **ref_cu)
18313 {
18314   struct objfile *objfile = (*ref_cu)->objfile;
18315   struct die_info temp_die;
18316   struct dwarf2_cu *sig_cu;
18317   struct die_info *die;
18318
18319   /* While it might be nice to assert sig_type->type == NULL here,
18320      we can get here for DW_AT_imported_declaration where we need
18321      the DIE not the type.  */
18322
18323   /* If necessary, add it to the queue and load its DIEs.  */
18324
18325   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18326     read_signatured_type (sig_type);
18327
18328   gdb_assert (sig_type->per_cu.cu != NULL);
18329
18330   sig_cu = sig_type->per_cu.cu;
18331   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18332   temp_die.offset = sig_type->type_offset_in_section;
18333   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18334                              temp_die.offset.sect_off);
18335   if (die)
18336     {
18337       /* For .gdb_index version 7 keep track of included TUs.
18338          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18339       if (dwarf2_per_objfile->index_table != NULL
18340           && dwarf2_per_objfile->index_table->version <= 7)
18341         {
18342           VEC_safe_push (dwarf2_per_cu_ptr,
18343                          (*ref_cu)->per_cu->imported_symtabs,
18344                          sig_cu->per_cu);
18345         }
18346
18347       *ref_cu = sig_cu;
18348       return die;
18349     }
18350
18351   return NULL;
18352 }
18353
18354 /* Follow signatured type referenced by ATTR in SRC_DIE.
18355    On entry *REF_CU is the CU of SRC_DIE.
18356    On exit *REF_CU is the CU of the result.
18357    The result is the DIE of the type.
18358    If the referenced type cannot be found an error is thrown.  */
18359
18360 static struct die_info *
18361 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
18362                 struct dwarf2_cu **ref_cu)
18363 {
18364   ULONGEST signature = DW_SIGNATURE (attr);
18365   struct signatured_type *sig_type;
18366   struct die_info *die;
18367
18368   gdb_assert (attr->form == DW_FORM_ref_sig8);
18369
18370   sig_type = lookup_signatured_type (*ref_cu, signature);
18371   /* sig_type will be NULL if the signatured type is missing from
18372      the debug info.  */
18373   if (sig_type == NULL)
18374     {
18375       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18376                " from DIE at 0x%x [in module %s]"),
18377              hex_string (signature), src_die->offset.sect_off,
18378              (*ref_cu)->objfile->name);
18379     }
18380
18381   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18382   if (die == NULL)
18383     {
18384       dump_die_for_error (src_die);
18385       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18386                " from DIE at 0x%x [in module %s]"),
18387              hex_string (signature), src_die->offset.sect_off,
18388              (*ref_cu)->objfile->name);
18389     }
18390
18391   return die;
18392 }
18393
18394 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18395    reading in and processing the type unit if necessary.  */
18396
18397 static struct type *
18398 get_signatured_type (struct die_info *die, ULONGEST signature,
18399                      struct dwarf2_cu *cu)
18400 {
18401   struct signatured_type *sig_type;
18402   struct dwarf2_cu *type_cu;
18403   struct die_info *type_die;
18404   struct type *type;
18405
18406   sig_type = lookup_signatured_type (cu, signature);
18407   /* sig_type will be NULL if the signatured type is missing from
18408      the debug info.  */
18409   if (sig_type == NULL)
18410     {
18411       complaint (&symfile_complaints,
18412                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18413                    " from DIE at 0x%x [in module %s]"),
18414                  hex_string (signature), die->offset.sect_off,
18415                  dwarf2_per_objfile->objfile->name);
18416       return build_error_marker_type (cu, die);
18417     }
18418
18419   /* If we already know the type we're done.  */
18420   if (sig_type->type != NULL)
18421     return sig_type->type;
18422
18423   type_cu = cu;
18424   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18425   if (type_die != NULL)
18426     {
18427       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18428          is created.  This is important, for example, because for c++ classes
18429          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18430       type = read_type_die (type_die, type_cu);
18431       if (type == NULL)
18432         {
18433           complaint (&symfile_complaints,
18434                      _("Dwarf Error: Cannot build signatured type %s"
18435                        " referenced from DIE at 0x%x [in module %s]"),
18436                      hex_string (signature), die->offset.sect_off,
18437                      dwarf2_per_objfile->objfile->name);
18438           type = build_error_marker_type (cu, die);
18439         }
18440     }
18441   else
18442     {
18443       complaint (&symfile_complaints,
18444                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18445                    " from DIE at 0x%x [in module %s]"),
18446                  hex_string (signature), die->offset.sect_off,
18447                  dwarf2_per_objfile->objfile->name);
18448       type = build_error_marker_type (cu, die);
18449     }
18450   sig_type->type = type;
18451
18452   return type;
18453 }
18454
18455 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18456    reading in and processing the type unit if necessary.  */
18457
18458 static struct type *
18459 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
18460                           struct dwarf2_cu *cu) /* ARI: editCase function */
18461 {
18462   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18463   if (attr_form_is_ref (attr))
18464     {
18465       struct dwarf2_cu *type_cu = cu;
18466       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18467
18468       return read_type_die (type_die, type_cu);
18469     }
18470   else if (attr->form == DW_FORM_ref_sig8)
18471     {
18472       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18473     }
18474   else
18475     {
18476       complaint (&symfile_complaints,
18477                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18478                    " at 0x%x [in module %s]"),
18479                  dwarf_form_name (attr->form), die->offset.sect_off,
18480                  dwarf2_per_objfile->objfile->name);
18481       return build_error_marker_type (cu, die);
18482     }
18483 }
18484
18485 /* Load the DIEs associated with type unit PER_CU into memory.  */
18486
18487 static void
18488 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18489 {
18490   struct signatured_type *sig_type;
18491
18492   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18493   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18494
18495   /* We have the per_cu, but we need the signatured_type.
18496      Fortunately this is an easy translation.  */
18497   gdb_assert (per_cu->is_debug_types);
18498   sig_type = (struct signatured_type *) per_cu;
18499
18500   gdb_assert (per_cu->cu == NULL);
18501
18502   read_signatured_type (sig_type);
18503
18504   gdb_assert (per_cu->cu != NULL);
18505 }
18506
18507 /* die_reader_func for read_signatured_type.
18508    This is identical to load_full_comp_unit_reader,
18509    but is kept separate for now.  */
18510
18511 static void
18512 read_signatured_type_reader (const struct die_reader_specs *reader,
18513                              const gdb_byte *info_ptr,
18514                              struct die_info *comp_unit_die,
18515                              int has_children,
18516                              void *data)
18517 {
18518   struct dwarf2_cu *cu = reader->cu;
18519
18520   gdb_assert (cu->die_hash == NULL);
18521   cu->die_hash =
18522     htab_create_alloc_ex (cu->header.length / 12,
18523                           die_hash,
18524                           die_eq,
18525                           NULL,
18526                           &cu->comp_unit_obstack,
18527                           hashtab_obstack_allocate,
18528                           dummy_obstack_deallocate);
18529
18530   if (has_children)
18531     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18532                                                   &info_ptr, comp_unit_die);
18533   cu->dies = comp_unit_die;
18534   /* comp_unit_die is not stored in die_hash, no need.  */
18535
18536   /* We try not to read any attributes in this function, because not
18537      all CUs needed for references have been loaded yet, and symbol
18538      table processing isn't initialized.  But we have to set the CU language,
18539      or we won't be able to build types correctly.
18540      Similarly, if we do not read the producer, we can not apply
18541      producer-specific interpretation.  */
18542   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18543 }
18544
18545 /* Read in a signatured type and build its CU and DIEs.
18546    If the type is a stub for the real type in a DWO file,
18547    read in the real type from the DWO file as well.  */
18548
18549 static void
18550 read_signatured_type (struct signatured_type *sig_type)
18551 {
18552   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18553
18554   gdb_assert (per_cu->is_debug_types);
18555   gdb_assert (per_cu->cu == NULL);
18556
18557   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18558                            read_signatured_type_reader, NULL);
18559   sig_type->per_cu.tu_read = 1;
18560 }
18561
18562 /* Decode simple location descriptions.
18563    Given a pointer to a dwarf block that defines a location, compute
18564    the location and return the value.
18565
18566    NOTE drow/2003-11-18: This function is called in two situations
18567    now: for the address of static or global variables (partial symbols
18568    only) and for offsets into structures which are expected to be
18569    (more or less) constant.  The partial symbol case should go away,
18570    and only the constant case should remain.  That will let this
18571    function complain more accurately.  A few special modes are allowed
18572    without complaint for global variables (for instance, global
18573    register values and thread-local values).
18574
18575    A location description containing no operations indicates that the
18576    object is optimized out.  The return value is 0 for that case.
18577    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18578    callers will only want a very basic result and this can become a
18579    complaint.
18580
18581    Note that stack[0] is unused except as a default error return.  */
18582
18583 static CORE_ADDR
18584 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18585 {
18586   struct objfile *objfile = cu->objfile;
18587   size_t i;
18588   size_t size = blk->size;
18589   const gdb_byte *data = blk->data;
18590   CORE_ADDR stack[64];
18591   int stacki;
18592   unsigned int bytes_read, unsnd;
18593   gdb_byte op;
18594
18595   i = 0;
18596   stacki = 0;
18597   stack[stacki] = 0;
18598   stack[++stacki] = 0;
18599
18600   while (i < size)
18601     {
18602       op = data[i++];
18603       switch (op)
18604         {
18605         case DW_OP_lit0:
18606         case DW_OP_lit1:
18607         case DW_OP_lit2:
18608         case DW_OP_lit3:
18609         case DW_OP_lit4:
18610         case DW_OP_lit5:
18611         case DW_OP_lit6:
18612         case DW_OP_lit7:
18613         case DW_OP_lit8:
18614         case DW_OP_lit9:
18615         case DW_OP_lit10:
18616         case DW_OP_lit11:
18617         case DW_OP_lit12:
18618         case DW_OP_lit13:
18619         case DW_OP_lit14:
18620         case DW_OP_lit15:
18621         case DW_OP_lit16:
18622         case DW_OP_lit17:
18623         case DW_OP_lit18:
18624         case DW_OP_lit19:
18625         case DW_OP_lit20:
18626         case DW_OP_lit21:
18627         case DW_OP_lit22:
18628         case DW_OP_lit23:
18629         case DW_OP_lit24:
18630         case DW_OP_lit25:
18631         case DW_OP_lit26:
18632         case DW_OP_lit27:
18633         case DW_OP_lit28:
18634         case DW_OP_lit29:
18635         case DW_OP_lit30:
18636         case DW_OP_lit31:
18637           stack[++stacki] = op - DW_OP_lit0;
18638           break;
18639
18640         case DW_OP_reg0:
18641         case DW_OP_reg1:
18642         case DW_OP_reg2:
18643         case DW_OP_reg3:
18644         case DW_OP_reg4:
18645         case DW_OP_reg5:
18646         case DW_OP_reg6:
18647         case DW_OP_reg7:
18648         case DW_OP_reg8:
18649         case DW_OP_reg9:
18650         case DW_OP_reg10:
18651         case DW_OP_reg11:
18652         case DW_OP_reg12:
18653         case DW_OP_reg13:
18654         case DW_OP_reg14:
18655         case DW_OP_reg15:
18656         case DW_OP_reg16:
18657         case DW_OP_reg17:
18658         case DW_OP_reg18:
18659         case DW_OP_reg19:
18660         case DW_OP_reg20:
18661         case DW_OP_reg21:
18662         case DW_OP_reg22:
18663         case DW_OP_reg23:
18664         case DW_OP_reg24:
18665         case DW_OP_reg25:
18666         case DW_OP_reg26:
18667         case DW_OP_reg27:
18668         case DW_OP_reg28:
18669         case DW_OP_reg29:
18670         case DW_OP_reg30:
18671         case DW_OP_reg31:
18672           stack[++stacki] = op - DW_OP_reg0;
18673           if (i < size)
18674             dwarf2_complex_location_expr_complaint ();
18675           break;
18676
18677         case DW_OP_regx:
18678           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18679           i += bytes_read;
18680           stack[++stacki] = unsnd;
18681           if (i < size)
18682             dwarf2_complex_location_expr_complaint ();
18683           break;
18684
18685         case DW_OP_addr:
18686           stack[++stacki] = read_address (objfile->obfd, &data[i],
18687                                           cu, &bytes_read);
18688           i += bytes_read;
18689           break;
18690
18691         case DW_OP_const1u:
18692           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18693           i += 1;
18694           break;
18695
18696         case DW_OP_const1s:
18697           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18698           i += 1;
18699           break;
18700
18701         case DW_OP_const2u:
18702           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18703           i += 2;
18704           break;
18705
18706         case DW_OP_const2s:
18707           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18708           i += 2;
18709           break;
18710
18711         case DW_OP_const4u:
18712           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18713           i += 4;
18714           break;
18715
18716         case DW_OP_const4s:
18717           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18718           i += 4;
18719           break;
18720
18721         case DW_OP_const8u:
18722           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18723           i += 8;
18724           break;
18725
18726         case DW_OP_constu:
18727           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18728                                                   &bytes_read);
18729           i += bytes_read;
18730           break;
18731
18732         case DW_OP_consts:
18733           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18734           i += bytes_read;
18735           break;
18736
18737         case DW_OP_dup:
18738           stack[stacki + 1] = stack[stacki];
18739           stacki++;
18740           break;
18741
18742         case DW_OP_plus:
18743           stack[stacki - 1] += stack[stacki];
18744           stacki--;
18745           break;
18746
18747         case DW_OP_plus_uconst:
18748           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18749                                                  &bytes_read);
18750           i += bytes_read;
18751           break;
18752
18753         case DW_OP_minus:
18754           stack[stacki - 1] -= stack[stacki];
18755           stacki--;
18756           break;
18757
18758         case DW_OP_deref:
18759           /* If we're not the last op, then we definitely can't encode
18760              this using GDB's address_class enum.  This is valid for partial
18761              global symbols, although the variable's address will be bogus
18762              in the psymtab.  */
18763           if (i < size)
18764             dwarf2_complex_location_expr_complaint ();
18765           break;
18766
18767         case DW_OP_GNU_push_tls_address:
18768           /* The top of the stack has the offset from the beginning
18769              of the thread control block at which the variable is located.  */
18770           /* Nothing should follow this operator, so the top of stack would
18771              be returned.  */
18772           /* This is valid for partial global symbols, but the variable's
18773              address will be bogus in the psymtab.  Make it always at least
18774              non-zero to not look as a variable garbage collected by linker
18775              which have DW_OP_addr 0.  */
18776           if (i < size)
18777             dwarf2_complex_location_expr_complaint ();
18778           stack[stacki]++;
18779           break;
18780
18781         case DW_OP_GNU_uninit:
18782           break;
18783
18784         case DW_OP_GNU_addr_index:
18785         case DW_OP_GNU_const_index:
18786           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18787                                                          &bytes_read);
18788           i += bytes_read;
18789           break;
18790
18791         default:
18792           {
18793             const char *name = get_DW_OP_name (op);
18794
18795             if (name)
18796               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18797                          name);
18798             else
18799               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18800                          op);
18801           }
18802
18803           return (stack[stacki]);
18804         }
18805
18806       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18807          outside of the allocated space.  Also enforce minimum>0.  */
18808       if (stacki >= ARRAY_SIZE (stack) - 1)
18809         {
18810           complaint (&symfile_complaints,
18811                      _("location description stack overflow"));
18812           return 0;
18813         }
18814
18815       if (stacki <= 0)
18816         {
18817           complaint (&symfile_complaints,
18818                      _("location description stack underflow"));
18819           return 0;
18820         }
18821     }
18822   return (stack[stacki]);
18823 }
18824
18825 /* memory allocation interface */
18826
18827 static struct dwarf_block *
18828 dwarf_alloc_block (struct dwarf2_cu *cu)
18829 {
18830   struct dwarf_block *blk;
18831
18832   blk = (struct dwarf_block *)
18833     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18834   return (blk);
18835 }
18836
18837 static struct die_info *
18838 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18839 {
18840   struct die_info *die;
18841   size_t size = sizeof (struct die_info);
18842
18843   if (num_attrs > 1)
18844     size += (num_attrs - 1) * sizeof (struct attribute);
18845
18846   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18847   memset (die, 0, sizeof (struct die_info));
18848   return (die);
18849 }
18850
18851 \f
18852 /* Macro support.  */
18853
18854 /* Return file name relative to the compilation directory of file number I in
18855    *LH's file name table.  The result is allocated using xmalloc; the caller is
18856    responsible for freeing it.  */
18857
18858 static char *
18859 file_file_name (int file, struct line_header *lh)
18860 {
18861   /* Is the file number a valid index into the line header's file name
18862      table?  Remember that file numbers start with one, not zero.  */
18863   if (1 <= file && file <= lh->num_file_names)
18864     {
18865       struct file_entry *fe = &lh->file_names[file - 1];
18866
18867       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18868         return xstrdup (fe->name);
18869       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18870                      fe->name, NULL);
18871     }
18872   else
18873     {
18874       /* The compiler produced a bogus file number.  We can at least
18875          record the macro definitions made in the file, even if we
18876          won't be able to find the file by name.  */
18877       char fake_name[80];
18878
18879       xsnprintf (fake_name, sizeof (fake_name),
18880                  "<bad macro file number %d>", file);
18881
18882       complaint (&symfile_complaints,
18883                  _("bad file number in macro information (%d)"),
18884                  file);
18885
18886       return xstrdup (fake_name);
18887     }
18888 }
18889
18890 /* Return the full name of file number I in *LH's file name table.
18891    Use COMP_DIR as the name of the current directory of the
18892    compilation.  The result is allocated using xmalloc; the caller is
18893    responsible for freeing it.  */
18894 static char *
18895 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18896 {
18897   /* Is the file number a valid index into the line header's file name
18898      table?  Remember that file numbers start with one, not zero.  */
18899   if (1 <= file && file <= lh->num_file_names)
18900     {
18901       char *relative = file_file_name (file, lh);
18902
18903       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18904         return relative;
18905       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18906     }
18907   else
18908     return file_file_name (file, lh);
18909 }
18910
18911
18912 static struct macro_source_file *
18913 macro_start_file (int file, int line,
18914                   struct macro_source_file *current_file,
18915                   const char *comp_dir,
18916                   struct line_header *lh, struct objfile *objfile)
18917 {
18918   /* File name relative to the compilation directory of this source file.  */
18919   char *file_name = file_file_name (file, lh);
18920
18921   /* We don't create a macro table for this compilation unit
18922      at all until we actually get a filename.  */
18923   if (! pending_macros)
18924     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18925                                       objfile->per_bfd->macro_cache,
18926                                       comp_dir);
18927
18928   if (! current_file)
18929     {
18930       /* If we have no current file, then this must be the start_file
18931          directive for the compilation unit's main source file.  */
18932       current_file = macro_set_main (pending_macros, file_name);
18933       macro_define_special (pending_macros);
18934     }
18935   else
18936     current_file = macro_include (current_file, line, file_name);
18937
18938   xfree (file_name);
18939
18940   return current_file;
18941 }
18942
18943
18944 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18945    followed by a null byte.  */
18946 static char *
18947 copy_string (const char *buf, int len)
18948 {
18949   char *s = xmalloc (len + 1);
18950
18951   memcpy (s, buf, len);
18952   s[len] = '\0';
18953   return s;
18954 }
18955
18956
18957 static const char *
18958 consume_improper_spaces (const char *p, const char *body)
18959 {
18960   if (*p == ' ')
18961     {
18962       complaint (&symfile_complaints,
18963                  _("macro definition contains spaces "
18964                    "in formal argument list:\n`%s'"),
18965                  body);
18966
18967       while (*p == ' ')
18968         p++;
18969     }
18970
18971   return p;
18972 }
18973
18974
18975 static void
18976 parse_macro_definition (struct macro_source_file *file, int line,
18977                         const char *body)
18978 {
18979   const char *p;
18980
18981   /* The body string takes one of two forms.  For object-like macro
18982      definitions, it should be:
18983
18984         <macro name> " " <definition>
18985
18986      For function-like macro definitions, it should be:
18987
18988         <macro name> "() " <definition>
18989      or
18990         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18991
18992      Spaces may appear only where explicitly indicated, and in the
18993      <definition>.
18994
18995      The Dwarf 2 spec says that an object-like macro's name is always
18996      followed by a space, but versions of GCC around March 2002 omit
18997      the space when the macro's definition is the empty string.
18998
18999      The Dwarf 2 spec says that there should be no spaces between the
19000      formal arguments in a function-like macro's formal argument list,
19001      but versions of GCC around March 2002 include spaces after the
19002      commas.  */
19003
19004
19005   /* Find the extent of the macro name.  The macro name is terminated
19006      by either a space or null character (for an object-like macro) or
19007      an opening paren (for a function-like macro).  */
19008   for (p = body; *p; p++)
19009     if (*p == ' ' || *p == '(')
19010       break;
19011
19012   if (*p == ' ' || *p == '\0')
19013     {
19014       /* It's an object-like macro.  */
19015       int name_len = p - body;
19016       char *name = copy_string (body, name_len);
19017       const char *replacement;
19018
19019       if (*p == ' ')
19020         replacement = body + name_len + 1;
19021       else
19022         {
19023           dwarf2_macro_malformed_definition_complaint (body);
19024           replacement = body + name_len;
19025         }
19026
19027       macro_define_object (file, line, name, replacement);
19028
19029       xfree (name);
19030     }
19031   else if (*p == '(')
19032     {
19033       /* It's a function-like macro.  */
19034       char *name = copy_string (body, p - body);
19035       int argc = 0;
19036       int argv_size = 1;
19037       char **argv = xmalloc (argv_size * sizeof (*argv));
19038
19039       p++;
19040
19041       p = consume_improper_spaces (p, body);
19042
19043       /* Parse the formal argument list.  */
19044       while (*p && *p != ')')
19045         {
19046           /* Find the extent of the current argument name.  */
19047           const char *arg_start = p;
19048
19049           while (*p && *p != ',' && *p != ')' && *p != ' ')
19050             p++;
19051
19052           if (! *p || p == arg_start)
19053             dwarf2_macro_malformed_definition_complaint (body);
19054           else
19055             {
19056               /* Make sure argv has room for the new argument.  */
19057               if (argc >= argv_size)
19058                 {
19059                   argv_size *= 2;
19060                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19061                 }
19062
19063               argv[argc++] = copy_string (arg_start, p - arg_start);
19064             }
19065
19066           p = consume_improper_spaces (p, body);
19067
19068           /* Consume the comma, if present.  */
19069           if (*p == ',')
19070             {
19071               p++;
19072
19073               p = consume_improper_spaces (p, body);
19074             }
19075         }
19076
19077       if (*p == ')')
19078         {
19079           p++;
19080
19081           if (*p == ' ')
19082             /* Perfectly formed definition, no complaints.  */
19083             macro_define_function (file, line, name,
19084                                    argc, (const char **) argv,
19085                                    p + 1);
19086           else if (*p == '\0')
19087             {
19088               /* Complain, but do define it.  */
19089               dwarf2_macro_malformed_definition_complaint (body);
19090               macro_define_function (file, line, name,
19091                                      argc, (const char **) argv,
19092                                      p);
19093             }
19094           else
19095             /* Just complain.  */
19096             dwarf2_macro_malformed_definition_complaint (body);
19097         }
19098       else
19099         /* Just complain.  */
19100         dwarf2_macro_malformed_definition_complaint (body);
19101
19102       xfree (name);
19103       {
19104         int i;
19105
19106         for (i = 0; i < argc; i++)
19107           xfree (argv[i]);
19108       }
19109       xfree (argv);
19110     }
19111   else
19112     dwarf2_macro_malformed_definition_complaint (body);
19113 }
19114
19115 /* Skip some bytes from BYTES according to the form given in FORM.
19116    Returns the new pointer.  */
19117
19118 static const gdb_byte *
19119 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19120                  enum dwarf_form form,
19121                  unsigned int offset_size,
19122                  struct dwarf2_section_info *section)
19123 {
19124   unsigned int bytes_read;
19125
19126   switch (form)
19127     {
19128     case DW_FORM_data1:
19129     case DW_FORM_flag:
19130       ++bytes;
19131       break;
19132
19133     case DW_FORM_data2:
19134       bytes += 2;
19135       break;
19136
19137     case DW_FORM_data4:
19138       bytes += 4;
19139       break;
19140
19141     case DW_FORM_data8:
19142       bytes += 8;
19143       break;
19144
19145     case DW_FORM_string:
19146       read_direct_string (abfd, bytes, &bytes_read);
19147       bytes += bytes_read;
19148       break;
19149
19150     case DW_FORM_sec_offset:
19151     case DW_FORM_strp:
19152     case DW_FORM_GNU_strp_alt:
19153       bytes += offset_size;
19154       break;
19155
19156     case DW_FORM_block:
19157       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19158       bytes += bytes_read;
19159       break;
19160
19161     case DW_FORM_block1:
19162       bytes += 1 + read_1_byte (abfd, bytes);
19163       break;
19164     case DW_FORM_block2:
19165       bytes += 2 + read_2_bytes (abfd, bytes);
19166       break;
19167     case DW_FORM_block4:
19168       bytes += 4 + read_4_bytes (abfd, bytes);
19169       break;
19170
19171     case DW_FORM_sdata:
19172     case DW_FORM_udata:
19173     case DW_FORM_GNU_addr_index:
19174     case DW_FORM_GNU_str_index:
19175       bytes = gdb_skip_leb128 (bytes, buffer_end);
19176       if (bytes == NULL)
19177         {
19178           dwarf2_section_buffer_overflow_complaint (section);
19179           return NULL;
19180         }
19181       break;
19182
19183     default:
19184       {
19185       complain:
19186         complaint (&symfile_complaints,
19187                    _("invalid form 0x%x in `%s'"),
19188                    form,
19189                    section->asection->name);
19190         return NULL;
19191       }
19192     }
19193
19194   return bytes;
19195 }
19196
19197 /* A helper for dwarf_decode_macros that handles skipping an unknown
19198    opcode.  Returns an updated pointer to the macro data buffer; or,
19199    on error, issues a complaint and returns NULL.  */
19200
19201 static const gdb_byte *
19202 skip_unknown_opcode (unsigned int opcode,
19203                      const gdb_byte **opcode_definitions,
19204                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19205                      bfd *abfd,
19206                      unsigned int offset_size,
19207                      struct dwarf2_section_info *section)
19208 {
19209   unsigned int bytes_read, i;
19210   unsigned long arg;
19211   const gdb_byte *defn;
19212
19213   if (opcode_definitions[opcode] == NULL)
19214     {
19215       complaint (&symfile_complaints,
19216                  _("unrecognized DW_MACFINO opcode 0x%x"),
19217                  opcode);
19218       return NULL;
19219     }
19220
19221   defn = opcode_definitions[opcode];
19222   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19223   defn += bytes_read;
19224
19225   for (i = 0; i < arg; ++i)
19226     {
19227       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19228                                  section);
19229       if (mac_ptr == NULL)
19230         {
19231           /* skip_form_bytes already issued the complaint.  */
19232           return NULL;
19233         }
19234     }
19235
19236   return mac_ptr;
19237 }
19238
19239 /* A helper function which parses the header of a macro section.
19240    If the macro section is the extended (for now called "GNU") type,
19241    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19242    the header, or issues a complaint and returns NULL on error.  */
19243
19244 static const gdb_byte *
19245 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19246                           bfd *abfd,
19247                           const gdb_byte *mac_ptr,
19248                           unsigned int *offset_size,
19249                           int section_is_gnu)
19250 {
19251   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19252
19253   if (section_is_gnu)
19254     {
19255       unsigned int version, flags;
19256
19257       version = read_2_bytes (abfd, mac_ptr);
19258       if (version != 4)
19259         {
19260           complaint (&symfile_complaints,
19261                      _("unrecognized version `%d' in .debug_macro section"),
19262                      version);
19263           return NULL;
19264         }
19265       mac_ptr += 2;
19266
19267       flags = read_1_byte (abfd, mac_ptr);
19268       ++mac_ptr;
19269       *offset_size = (flags & 1) ? 8 : 4;
19270
19271       if ((flags & 2) != 0)
19272         /* We don't need the line table offset.  */
19273         mac_ptr += *offset_size;
19274
19275       /* Vendor opcode descriptions.  */
19276       if ((flags & 4) != 0)
19277         {
19278           unsigned int i, count;
19279
19280           count = read_1_byte (abfd, mac_ptr);
19281           ++mac_ptr;
19282           for (i = 0; i < count; ++i)
19283             {
19284               unsigned int opcode, bytes_read;
19285               unsigned long arg;
19286
19287               opcode = read_1_byte (abfd, mac_ptr);
19288               ++mac_ptr;
19289               opcode_definitions[opcode] = mac_ptr;
19290               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19291               mac_ptr += bytes_read;
19292               mac_ptr += arg;
19293             }
19294         }
19295     }
19296
19297   return mac_ptr;
19298 }
19299
19300 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19301    including DW_MACRO_GNU_transparent_include.  */
19302
19303 static void
19304 dwarf_decode_macro_bytes (bfd *abfd,
19305                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19306                           struct macro_source_file *current_file,
19307                           struct line_header *lh, const char *comp_dir,
19308                           struct dwarf2_section_info *section,
19309                           int section_is_gnu, int section_is_dwz,
19310                           unsigned int offset_size,
19311                           struct objfile *objfile,
19312                           htab_t include_hash)
19313 {
19314   enum dwarf_macro_record_type macinfo_type;
19315   int at_commandline;
19316   const gdb_byte *opcode_definitions[256];
19317
19318   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19319                                       &offset_size, section_is_gnu);
19320   if (mac_ptr == NULL)
19321     {
19322       /* We already issued a complaint.  */
19323       return;
19324     }
19325
19326   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19327      GDB is still reading the definitions from command line.  First
19328      DW_MACINFO_start_file will need to be ignored as it was already executed
19329      to create CURRENT_FILE for the main source holding also the command line
19330      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19331      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19332
19333   at_commandline = 1;
19334
19335   do
19336     {
19337       /* Do we at least have room for a macinfo type byte?  */
19338       if (mac_ptr >= mac_end)
19339         {
19340           dwarf2_section_buffer_overflow_complaint (section);
19341           break;
19342         }
19343
19344       macinfo_type = read_1_byte (abfd, mac_ptr);
19345       mac_ptr++;
19346
19347       /* Note that we rely on the fact that the corresponding GNU and
19348          DWARF constants are the same.  */
19349       switch (macinfo_type)
19350         {
19351           /* A zero macinfo type indicates the end of the macro
19352              information.  */
19353         case 0:
19354           break;
19355
19356         case DW_MACRO_GNU_define:
19357         case DW_MACRO_GNU_undef:
19358         case DW_MACRO_GNU_define_indirect:
19359         case DW_MACRO_GNU_undef_indirect:
19360         case DW_MACRO_GNU_define_indirect_alt:
19361         case DW_MACRO_GNU_undef_indirect_alt:
19362           {
19363             unsigned int bytes_read;
19364             int line;
19365             const char *body;
19366             int is_define;
19367
19368             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19369             mac_ptr += bytes_read;
19370
19371             if (macinfo_type == DW_MACRO_GNU_define
19372                 || macinfo_type == DW_MACRO_GNU_undef)
19373               {
19374                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19375                 mac_ptr += bytes_read;
19376               }
19377             else
19378               {
19379                 LONGEST str_offset;
19380
19381                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19382                 mac_ptr += offset_size;
19383
19384                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19385                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19386                     || section_is_dwz)
19387                   {
19388                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19389
19390                     body = read_indirect_string_from_dwz (dwz, str_offset);
19391                   }
19392                 else
19393                   body = read_indirect_string_at_offset (abfd, str_offset);
19394               }
19395
19396             is_define = (macinfo_type == DW_MACRO_GNU_define
19397                          || macinfo_type == DW_MACRO_GNU_define_indirect
19398                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19399             if (! current_file)
19400               {
19401                 /* DWARF violation as no main source is present.  */
19402                 complaint (&symfile_complaints,
19403                            _("debug info with no main source gives macro %s "
19404                              "on line %d: %s"),
19405                            is_define ? _("definition") : _("undefinition"),
19406                            line, body);
19407                 break;
19408               }
19409             if ((line == 0 && !at_commandline)
19410                 || (line != 0 && at_commandline))
19411               complaint (&symfile_complaints,
19412                          _("debug info gives %s macro %s with %s line %d: %s"),
19413                          at_commandline ? _("command-line") : _("in-file"),
19414                          is_define ? _("definition") : _("undefinition"),
19415                          line == 0 ? _("zero") : _("non-zero"), line, body);
19416
19417             if (is_define)
19418               parse_macro_definition (current_file, line, body);
19419             else
19420               {
19421                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19422                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19423                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19424                 macro_undef (current_file, line, body);
19425               }
19426           }
19427           break;
19428
19429         case DW_MACRO_GNU_start_file:
19430           {
19431             unsigned int bytes_read;
19432             int line, file;
19433
19434             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19435             mac_ptr += bytes_read;
19436             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19437             mac_ptr += bytes_read;
19438
19439             if ((line == 0 && !at_commandline)
19440                 || (line != 0 && at_commandline))
19441               complaint (&symfile_complaints,
19442                          _("debug info gives source %d included "
19443                            "from %s at %s line %d"),
19444                          file, at_commandline ? _("command-line") : _("file"),
19445                          line == 0 ? _("zero") : _("non-zero"), line);
19446
19447             if (at_commandline)
19448               {
19449                 /* This DW_MACRO_GNU_start_file was executed in the
19450                    pass one.  */
19451                 at_commandline = 0;
19452               }
19453             else
19454               current_file = macro_start_file (file, line,
19455                                                current_file, comp_dir,
19456                                                lh, objfile);
19457           }
19458           break;
19459
19460         case DW_MACRO_GNU_end_file:
19461           if (! current_file)
19462             complaint (&symfile_complaints,
19463                        _("macro debug info has an unmatched "
19464                          "`close_file' directive"));
19465           else
19466             {
19467               current_file = current_file->included_by;
19468               if (! current_file)
19469                 {
19470                   enum dwarf_macro_record_type next_type;
19471
19472                   /* GCC circa March 2002 doesn't produce the zero
19473                      type byte marking the end of the compilation
19474                      unit.  Complain if it's not there, but exit no
19475                      matter what.  */
19476
19477                   /* Do we at least have room for a macinfo type byte?  */
19478                   if (mac_ptr >= mac_end)
19479                     {
19480                       dwarf2_section_buffer_overflow_complaint (section);
19481                       return;
19482                     }
19483
19484                   /* We don't increment mac_ptr here, so this is just
19485                      a look-ahead.  */
19486                   next_type = read_1_byte (abfd, mac_ptr);
19487                   if (next_type != 0)
19488                     complaint (&symfile_complaints,
19489                                _("no terminating 0-type entry for "
19490                                  "macros in `.debug_macinfo' section"));
19491
19492                   return;
19493                 }
19494             }
19495           break;
19496
19497         case DW_MACRO_GNU_transparent_include:
19498         case DW_MACRO_GNU_transparent_include_alt:
19499           {
19500             LONGEST offset;
19501             void **slot;
19502             bfd *include_bfd = abfd;
19503             struct dwarf2_section_info *include_section = section;
19504             struct dwarf2_section_info alt_section;
19505             const gdb_byte *include_mac_end = mac_end;
19506             int is_dwz = section_is_dwz;
19507             const gdb_byte *new_mac_ptr;
19508
19509             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19510             mac_ptr += offset_size;
19511
19512             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19513               {
19514                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19515
19516                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19517                                      &dwz->macro);
19518
19519                 include_bfd = dwz->macro.asection->owner;
19520                 include_section = &dwz->macro;
19521                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19522                 is_dwz = 1;
19523               }
19524
19525             new_mac_ptr = include_section->buffer + offset;
19526             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19527
19528             if (*slot != NULL)
19529               {
19530                 /* This has actually happened; see
19531                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19532                 complaint (&symfile_complaints,
19533                            _("recursive DW_MACRO_GNU_transparent_include in "
19534                              ".debug_macro section"));
19535               }
19536             else
19537               {
19538                 *slot = (void *) new_mac_ptr;
19539
19540                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19541                                           include_mac_end, current_file,
19542                                           lh, comp_dir,
19543                                           section, section_is_gnu, is_dwz,
19544                                           offset_size, objfile, include_hash);
19545
19546                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19547               }
19548           }
19549           break;
19550
19551         case DW_MACINFO_vendor_ext:
19552           if (!section_is_gnu)
19553             {
19554               unsigned int bytes_read;
19555               int constant;
19556
19557               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19558               mac_ptr += bytes_read;
19559               read_direct_string (abfd, mac_ptr, &bytes_read);
19560               mac_ptr += bytes_read;
19561
19562               /* We don't recognize any vendor extensions.  */
19563               break;
19564             }
19565           /* FALLTHROUGH */
19566
19567         default:
19568           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19569                                          mac_ptr, mac_end, abfd, offset_size,
19570                                          section);
19571           if (mac_ptr == NULL)
19572             return;
19573           break;
19574         }
19575     } while (macinfo_type != 0);
19576 }
19577
19578 static void
19579 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19580                      const char *comp_dir, int section_is_gnu)
19581 {
19582   struct objfile *objfile = dwarf2_per_objfile->objfile;
19583   struct line_header *lh = cu->line_header;
19584   bfd *abfd;
19585   const gdb_byte *mac_ptr, *mac_end;
19586   struct macro_source_file *current_file = 0;
19587   enum dwarf_macro_record_type macinfo_type;
19588   unsigned int offset_size = cu->header.offset_size;
19589   const gdb_byte *opcode_definitions[256];
19590   struct cleanup *cleanup;
19591   htab_t include_hash;
19592   void **slot;
19593   struct dwarf2_section_info *section;
19594   const char *section_name;
19595
19596   if (cu->dwo_unit != NULL)
19597     {
19598       if (section_is_gnu)
19599         {
19600           section = &cu->dwo_unit->dwo_file->sections.macro;
19601           section_name = ".debug_macro.dwo";
19602         }
19603       else
19604         {
19605           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19606           section_name = ".debug_macinfo.dwo";
19607         }
19608     }
19609   else
19610     {
19611       if (section_is_gnu)
19612         {
19613           section = &dwarf2_per_objfile->macro;
19614           section_name = ".debug_macro";
19615         }
19616       else
19617         {
19618           section = &dwarf2_per_objfile->macinfo;
19619           section_name = ".debug_macinfo";
19620         }
19621     }
19622
19623   dwarf2_read_section (objfile, section);
19624   if (section->buffer == NULL)
19625     {
19626       complaint (&symfile_complaints, _("missing %s section"), section_name);
19627       return;
19628     }
19629   abfd = section->asection->owner;
19630
19631   /* First pass: Find the name of the base filename.
19632      This filename is needed in order to process all macros whose definition
19633      (or undefinition) comes from the command line.  These macros are defined
19634      before the first DW_MACINFO_start_file entry, and yet still need to be
19635      associated to the base file.
19636
19637      To determine the base file name, we scan the macro definitions until we
19638      reach the first DW_MACINFO_start_file entry.  We then initialize
19639      CURRENT_FILE accordingly so that any macro definition found before the
19640      first DW_MACINFO_start_file can still be associated to the base file.  */
19641
19642   mac_ptr = section->buffer + offset;
19643   mac_end = section->buffer + section->size;
19644
19645   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19646                                       &offset_size, section_is_gnu);
19647   if (mac_ptr == NULL)
19648     {
19649       /* We already issued a complaint.  */
19650       return;
19651     }
19652
19653   do
19654     {
19655       /* Do we at least have room for a macinfo type byte?  */
19656       if (mac_ptr >= mac_end)
19657         {
19658           /* Complaint is printed during the second pass as GDB will probably
19659              stop the first pass earlier upon finding
19660              DW_MACINFO_start_file.  */
19661           break;
19662         }
19663
19664       macinfo_type = read_1_byte (abfd, mac_ptr);
19665       mac_ptr++;
19666
19667       /* Note that we rely on the fact that the corresponding GNU and
19668          DWARF constants are the same.  */
19669       switch (macinfo_type)
19670         {
19671           /* A zero macinfo type indicates the end of the macro
19672              information.  */
19673         case 0:
19674           break;
19675
19676         case DW_MACRO_GNU_define:
19677         case DW_MACRO_GNU_undef:
19678           /* Only skip the data by MAC_PTR.  */
19679           {
19680             unsigned int bytes_read;
19681
19682             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19683             mac_ptr += bytes_read;
19684             read_direct_string (abfd, mac_ptr, &bytes_read);
19685             mac_ptr += bytes_read;
19686           }
19687           break;
19688
19689         case DW_MACRO_GNU_start_file:
19690           {
19691             unsigned int bytes_read;
19692             int line, file;
19693
19694             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19695             mac_ptr += bytes_read;
19696             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19697             mac_ptr += bytes_read;
19698
19699             current_file = macro_start_file (file, line, current_file,
19700                                              comp_dir, lh, objfile);
19701           }
19702           break;
19703
19704         case DW_MACRO_GNU_end_file:
19705           /* No data to skip by MAC_PTR.  */
19706           break;
19707
19708         case DW_MACRO_GNU_define_indirect:
19709         case DW_MACRO_GNU_undef_indirect:
19710         case DW_MACRO_GNU_define_indirect_alt:
19711         case DW_MACRO_GNU_undef_indirect_alt:
19712           {
19713             unsigned int bytes_read;
19714
19715             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19716             mac_ptr += bytes_read;
19717             mac_ptr += offset_size;
19718           }
19719           break;
19720
19721         case DW_MACRO_GNU_transparent_include:
19722         case DW_MACRO_GNU_transparent_include_alt:
19723           /* Note that, according to the spec, a transparent include
19724              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19725              skip this opcode.  */
19726           mac_ptr += offset_size;
19727           break;
19728
19729         case DW_MACINFO_vendor_ext:
19730           /* Only skip the data by MAC_PTR.  */
19731           if (!section_is_gnu)
19732             {
19733               unsigned int bytes_read;
19734
19735               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19736               mac_ptr += bytes_read;
19737               read_direct_string (abfd, mac_ptr, &bytes_read);
19738               mac_ptr += bytes_read;
19739             }
19740           /* FALLTHROUGH */
19741
19742         default:
19743           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19744                                          mac_ptr, mac_end, abfd, offset_size,
19745                                          section);
19746           if (mac_ptr == NULL)
19747             return;
19748           break;
19749         }
19750     } while (macinfo_type != 0 && current_file == NULL);
19751
19752   /* Second pass: Process all entries.
19753
19754      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19755      command-line macro definitions/undefinitions.  This flag is unset when we
19756      reach the first DW_MACINFO_start_file entry.  */
19757
19758   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19759                                     NULL, xcalloc, xfree);
19760   cleanup = make_cleanup_htab_delete (include_hash);
19761   mac_ptr = section->buffer + offset;
19762   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19763   *slot = (void *) mac_ptr;
19764   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19765                             current_file, lh, comp_dir, section,
19766                             section_is_gnu, 0,
19767                             offset_size, objfile, include_hash);
19768   do_cleanups (cleanup);
19769 }
19770
19771 /* Check if the attribute's form is a DW_FORM_block*
19772    if so return true else false.  */
19773
19774 static int
19775 attr_form_is_block (const struct attribute *attr)
19776 {
19777   return (attr == NULL ? 0 :
19778       attr->form == DW_FORM_block1
19779       || attr->form == DW_FORM_block2
19780       || attr->form == DW_FORM_block4
19781       || attr->form == DW_FORM_block
19782       || attr->form == DW_FORM_exprloc);
19783 }
19784
19785 /* Return non-zero if ATTR's value is a section offset --- classes
19786    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19787    You may use DW_UNSND (attr) to retrieve such offsets.
19788
19789    Section 7.5.4, "Attribute Encodings", explains that no attribute
19790    may have a value that belongs to more than one of these classes; it
19791    would be ambiguous if we did, because we use the same forms for all
19792    of them.  */
19793
19794 static int
19795 attr_form_is_section_offset (const struct attribute *attr)
19796 {
19797   return (attr->form == DW_FORM_data4
19798           || attr->form == DW_FORM_data8
19799           || attr->form == DW_FORM_sec_offset);
19800 }
19801
19802 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19803    zero otherwise.  When this function returns true, you can apply
19804    dwarf2_get_attr_constant_value to it.
19805
19806    However, note that for some attributes you must check
19807    attr_form_is_section_offset before using this test.  DW_FORM_data4
19808    and DW_FORM_data8 are members of both the constant class, and of
19809    the classes that contain offsets into other debug sections
19810    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19811    that, if an attribute's can be either a constant or one of the
19812    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19813    taken as section offsets, not constants.  */
19814
19815 static int
19816 attr_form_is_constant (const struct attribute *attr)
19817 {
19818   switch (attr->form)
19819     {
19820     case DW_FORM_sdata:
19821     case DW_FORM_udata:
19822     case DW_FORM_data1:
19823     case DW_FORM_data2:
19824     case DW_FORM_data4:
19825     case DW_FORM_data8:
19826       return 1;
19827     default:
19828       return 0;
19829     }
19830 }
19831
19832
19833 /* DW_ADDR is always stored already as sect_offset; despite for the forms
19834    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
19835
19836 static int
19837 attr_form_is_ref (const struct attribute *attr)
19838 {
19839   switch (attr->form)
19840     {
19841     case DW_FORM_ref_addr:
19842     case DW_FORM_ref1:
19843     case DW_FORM_ref2:
19844     case DW_FORM_ref4:
19845     case DW_FORM_ref8:
19846     case DW_FORM_ref_udata:
19847     case DW_FORM_GNU_ref_alt:
19848       return 1;
19849     default:
19850       return 0;
19851     }
19852 }
19853
19854 /* Return the .debug_loc section to use for CU.
19855    For DWO files use .debug_loc.dwo.  */
19856
19857 static struct dwarf2_section_info *
19858 cu_debug_loc_section (struct dwarf2_cu *cu)
19859 {
19860   if (cu->dwo_unit)
19861     return &cu->dwo_unit->dwo_file->sections.loc;
19862   return &dwarf2_per_objfile->loc;
19863 }
19864
19865 /* A helper function that fills in a dwarf2_loclist_baton.  */
19866
19867 static void
19868 fill_in_loclist_baton (struct dwarf2_cu *cu,
19869                        struct dwarf2_loclist_baton *baton,
19870                        const struct attribute *attr)
19871 {
19872   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19873
19874   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19875
19876   baton->per_cu = cu->per_cu;
19877   gdb_assert (baton->per_cu);
19878   /* We don't know how long the location list is, but make sure we
19879      don't run off the edge of the section.  */
19880   baton->size = section->size - DW_UNSND (attr);
19881   baton->data = section->buffer + DW_UNSND (attr);
19882   baton->base_address = cu->base_address;
19883   baton->from_dwo = cu->dwo_unit != NULL;
19884 }
19885
19886 static void
19887 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
19888                              struct dwarf2_cu *cu, int is_block)
19889 {
19890   struct objfile *objfile = dwarf2_per_objfile->objfile;
19891   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19892
19893   if (attr_form_is_section_offset (attr)
19894       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19895          the section.  If so, fall through to the complaint in the
19896          other branch.  */
19897       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19898     {
19899       struct dwarf2_loclist_baton *baton;
19900
19901       baton = obstack_alloc (&objfile->objfile_obstack,
19902                              sizeof (struct dwarf2_loclist_baton));
19903
19904       fill_in_loclist_baton (cu, baton, attr);
19905
19906       if (cu->base_known == 0)
19907         complaint (&symfile_complaints,
19908                    _("Location list used without "
19909                      "specifying the CU base address."));
19910
19911       SYMBOL_ACLASS_INDEX (sym) = (is_block
19912                                    ? dwarf2_loclist_block_index
19913                                    : dwarf2_loclist_index);
19914       SYMBOL_LOCATION_BATON (sym) = baton;
19915     }
19916   else
19917     {
19918       struct dwarf2_locexpr_baton *baton;
19919
19920       baton = obstack_alloc (&objfile->objfile_obstack,
19921                              sizeof (struct dwarf2_locexpr_baton));
19922       baton->per_cu = cu->per_cu;
19923       gdb_assert (baton->per_cu);
19924
19925       if (attr_form_is_block (attr))
19926         {
19927           /* Note that we're just copying the block's data pointer
19928              here, not the actual data.  We're still pointing into the
19929              info_buffer for SYM's objfile; right now we never release
19930              that buffer, but when we do clean up properly this may
19931              need to change.  */
19932           baton->size = DW_BLOCK (attr)->size;
19933           baton->data = DW_BLOCK (attr)->data;
19934         }
19935       else
19936         {
19937           dwarf2_invalid_attrib_class_complaint ("location description",
19938                                                  SYMBOL_NATURAL_NAME (sym));
19939           baton->size = 0;
19940         }
19941
19942       SYMBOL_ACLASS_INDEX (sym) = (is_block
19943                                    ? dwarf2_locexpr_block_index
19944                                    : dwarf2_locexpr_index);
19945       SYMBOL_LOCATION_BATON (sym) = baton;
19946     }
19947 }
19948
19949 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19950    came from a separate debuginfo file, then the master objfile is
19951    returned.  */
19952
19953 struct objfile *
19954 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19955 {
19956   struct objfile *objfile = per_cu->objfile;
19957
19958   /* Return the master objfile, so that we can report and look up the
19959      correct file containing this variable.  */
19960   if (objfile->separate_debug_objfile_backlink)
19961     objfile = objfile->separate_debug_objfile_backlink;
19962
19963   return objfile;
19964 }
19965
19966 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19967    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19968    CU_HEADERP first.  */
19969
19970 static const struct comp_unit_head *
19971 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19972                        struct dwarf2_per_cu_data *per_cu)
19973 {
19974   const gdb_byte *info_ptr;
19975
19976   if (per_cu->cu)
19977     return &per_cu->cu->header;
19978
19979   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19980
19981   memset (cu_headerp, 0, sizeof (*cu_headerp));
19982   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19983
19984   return cu_headerp;
19985 }
19986
19987 /* Return the address size given in the compilation unit header for CU.  */
19988
19989 int
19990 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19991 {
19992   struct comp_unit_head cu_header_local;
19993   const struct comp_unit_head *cu_headerp;
19994
19995   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19996
19997   return cu_headerp->addr_size;
19998 }
19999
20000 /* Return the offset size given in the compilation unit header for CU.  */
20001
20002 int
20003 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20004 {
20005   struct comp_unit_head cu_header_local;
20006   const struct comp_unit_head *cu_headerp;
20007
20008   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20009
20010   return cu_headerp->offset_size;
20011 }
20012
20013 /* See its dwarf2loc.h declaration.  */
20014
20015 int
20016 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20017 {
20018   struct comp_unit_head cu_header_local;
20019   const struct comp_unit_head *cu_headerp;
20020
20021   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20022
20023   if (cu_headerp->version == 2)
20024     return cu_headerp->addr_size;
20025   else
20026     return cu_headerp->offset_size;
20027 }
20028
20029 /* Return the text offset of the CU.  The returned offset comes from
20030    this CU's objfile.  If this objfile came from a separate debuginfo
20031    file, then the offset may be different from the corresponding
20032    offset in the parent objfile.  */
20033
20034 CORE_ADDR
20035 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20036 {
20037   struct objfile *objfile = per_cu->objfile;
20038
20039   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20040 }
20041
20042 /* Locate the .debug_info compilation unit from CU's objfile which contains
20043    the DIE at OFFSET.  Raises an error on failure.  */
20044
20045 static struct dwarf2_per_cu_data *
20046 dwarf2_find_containing_comp_unit (sect_offset offset,
20047                                   unsigned int offset_in_dwz,
20048                                   struct objfile *objfile)
20049 {
20050   struct dwarf2_per_cu_data *this_cu;
20051   int low, high;
20052   const sect_offset *cu_off;
20053
20054   low = 0;
20055   high = dwarf2_per_objfile->n_comp_units - 1;
20056   while (high > low)
20057     {
20058       struct dwarf2_per_cu_data *mid_cu;
20059       int mid = low + (high - low) / 2;
20060
20061       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20062       cu_off = &mid_cu->offset;
20063       if (mid_cu->is_dwz > offset_in_dwz
20064           || (mid_cu->is_dwz == offset_in_dwz
20065               && cu_off->sect_off >= offset.sect_off))
20066         high = mid;
20067       else
20068         low = mid + 1;
20069     }
20070   gdb_assert (low == high);
20071   this_cu = dwarf2_per_objfile->all_comp_units[low];
20072   cu_off = &this_cu->offset;
20073   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20074     {
20075       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20076         error (_("Dwarf Error: could not find partial DIE containing "
20077                "offset 0x%lx [in module %s]"),
20078                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20079
20080       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20081                   <= offset.sect_off);
20082       return dwarf2_per_objfile->all_comp_units[low-1];
20083     }
20084   else
20085     {
20086       this_cu = dwarf2_per_objfile->all_comp_units[low];
20087       if (low == dwarf2_per_objfile->n_comp_units - 1
20088           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20089         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20090       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20091       return this_cu;
20092     }
20093 }
20094
20095 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20096
20097 static void
20098 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20099 {
20100   memset (cu, 0, sizeof (*cu));
20101   per_cu->cu = cu;
20102   cu->per_cu = per_cu;
20103   cu->objfile = per_cu->objfile;
20104   obstack_init (&cu->comp_unit_obstack);
20105 }
20106
20107 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20108
20109 static void
20110 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20111                        enum language pretend_language)
20112 {
20113   struct attribute *attr;
20114
20115   /* Set the language we're debugging.  */
20116   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20117   if (attr)
20118     set_cu_language (DW_UNSND (attr), cu);
20119   else
20120     {
20121       cu->language = pretend_language;
20122       cu->language_defn = language_def (cu->language);
20123     }
20124
20125   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20126   if (attr)
20127     cu->producer = DW_STRING (attr);
20128 }
20129
20130 /* Release one cached compilation unit, CU.  We unlink it from the tree
20131    of compilation units, but we don't remove it from the read_in_chain;
20132    the caller is responsible for that.
20133    NOTE: DATA is a void * because this function is also used as a
20134    cleanup routine.  */
20135
20136 static void
20137 free_heap_comp_unit (void *data)
20138 {
20139   struct dwarf2_cu *cu = data;
20140
20141   gdb_assert (cu->per_cu != NULL);
20142   cu->per_cu->cu = NULL;
20143   cu->per_cu = NULL;
20144
20145   obstack_free (&cu->comp_unit_obstack, NULL);
20146
20147   xfree (cu);
20148 }
20149
20150 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20151    when we're finished with it.  We can't free the pointer itself, but be
20152    sure to unlink it from the cache.  Also release any associated storage.  */
20153
20154 static void
20155 free_stack_comp_unit (void *data)
20156 {
20157   struct dwarf2_cu *cu = data;
20158
20159   gdb_assert (cu->per_cu != NULL);
20160   cu->per_cu->cu = NULL;
20161   cu->per_cu = NULL;
20162
20163   obstack_free (&cu->comp_unit_obstack, NULL);
20164   cu->partial_dies = NULL;
20165 }
20166
20167 /* Free all cached compilation units.  */
20168
20169 static void
20170 free_cached_comp_units (void *data)
20171 {
20172   struct dwarf2_per_cu_data *per_cu, **last_chain;
20173
20174   per_cu = dwarf2_per_objfile->read_in_chain;
20175   last_chain = &dwarf2_per_objfile->read_in_chain;
20176   while (per_cu != NULL)
20177     {
20178       struct dwarf2_per_cu_data *next_cu;
20179
20180       next_cu = per_cu->cu->read_in_chain;
20181
20182       free_heap_comp_unit (per_cu->cu);
20183       *last_chain = next_cu;
20184
20185       per_cu = next_cu;
20186     }
20187 }
20188
20189 /* Increase the age counter on each cached compilation unit, and free
20190    any that are too old.  */
20191
20192 static void
20193 age_cached_comp_units (void)
20194 {
20195   struct dwarf2_per_cu_data *per_cu, **last_chain;
20196
20197   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20198   per_cu = dwarf2_per_objfile->read_in_chain;
20199   while (per_cu != NULL)
20200     {
20201       per_cu->cu->last_used ++;
20202       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20203         dwarf2_mark (per_cu->cu);
20204       per_cu = per_cu->cu->read_in_chain;
20205     }
20206
20207   per_cu = dwarf2_per_objfile->read_in_chain;
20208   last_chain = &dwarf2_per_objfile->read_in_chain;
20209   while (per_cu != NULL)
20210     {
20211       struct dwarf2_per_cu_data *next_cu;
20212
20213       next_cu = per_cu->cu->read_in_chain;
20214
20215       if (!per_cu->cu->mark)
20216         {
20217           free_heap_comp_unit (per_cu->cu);
20218           *last_chain = next_cu;
20219         }
20220       else
20221         last_chain = &per_cu->cu->read_in_chain;
20222
20223       per_cu = next_cu;
20224     }
20225 }
20226
20227 /* Remove a single compilation unit from the cache.  */
20228
20229 static void
20230 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20231 {
20232   struct dwarf2_per_cu_data *per_cu, **last_chain;
20233
20234   per_cu = dwarf2_per_objfile->read_in_chain;
20235   last_chain = &dwarf2_per_objfile->read_in_chain;
20236   while (per_cu != NULL)
20237     {
20238       struct dwarf2_per_cu_data *next_cu;
20239
20240       next_cu = per_cu->cu->read_in_chain;
20241
20242       if (per_cu == target_per_cu)
20243         {
20244           free_heap_comp_unit (per_cu->cu);
20245           per_cu->cu = NULL;
20246           *last_chain = next_cu;
20247           break;
20248         }
20249       else
20250         last_chain = &per_cu->cu->read_in_chain;
20251
20252       per_cu = next_cu;
20253     }
20254 }
20255
20256 /* Release all extra memory associated with OBJFILE.  */
20257
20258 void
20259 dwarf2_free_objfile (struct objfile *objfile)
20260 {
20261   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20262
20263   if (dwarf2_per_objfile == NULL)
20264     return;
20265
20266   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20267   free_cached_comp_units (NULL);
20268
20269   if (dwarf2_per_objfile->quick_file_names_table)
20270     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20271
20272   /* Everything else should be on the objfile obstack.  */
20273 }
20274
20275 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20276    We store these in a hash table separate from the DIEs, and preserve them
20277    when the DIEs are flushed out of cache.
20278
20279    The CU "per_cu" pointer is needed because offset alone is not enough to
20280    uniquely identify the type.  A file may have multiple .debug_types sections,
20281    or the type may come from a DWO file.  Furthermore, while it's more logical
20282    to use per_cu->section+offset, with Fission the section with the data is in
20283    the DWO file but we don't know that section at the point we need it.
20284    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20285    because we can enter the lookup routine, get_die_type_at_offset, from
20286    outside this file, and thus won't necessarily have PER_CU->cu.
20287    Fortunately, PER_CU is stable for the life of the objfile.  */
20288
20289 struct dwarf2_per_cu_offset_and_type
20290 {
20291   const struct dwarf2_per_cu_data *per_cu;
20292   sect_offset offset;
20293   struct type *type;
20294 };
20295
20296 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20297
20298 static hashval_t
20299 per_cu_offset_and_type_hash (const void *item)
20300 {
20301   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20302
20303   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20304 }
20305
20306 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20307
20308 static int
20309 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20310 {
20311   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20312   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20313
20314   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20315           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20316 }
20317
20318 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20319    table if necessary.  For convenience, return TYPE.
20320
20321    The DIEs reading must have careful ordering to:
20322     * Not cause infite loops trying to read in DIEs as a prerequisite for
20323       reading current DIE.
20324     * Not trying to dereference contents of still incompletely read in types
20325       while reading in other DIEs.
20326     * Enable referencing still incompletely read in types just by a pointer to
20327       the type without accessing its fields.
20328
20329    Therefore caller should follow these rules:
20330      * Try to fetch any prerequisite types we may need to build this DIE type
20331        before building the type and calling set_die_type.
20332      * After building type call set_die_type for current DIE as soon as
20333        possible before fetching more types to complete the current type.
20334      * Make the type as complete as possible before fetching more types.  */
20335
20336 static struct type *
20337 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20338 {
20339   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20340   struct objfile *objfile = cu->objfile;
20341
20342   /* For Ada types, make sure that the gnat-specific data is always
20343      initialized (if not already set).  There are a few types where
20344      we should not be doing so, because the type-specific area is
20345      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20346      where the type-specific area is used to store the floatformat).
20347      But this is not a problem, because the gnat-specific information
20348      is actually not needed for these types.  */
20349   if (need_gnat_info (cu)
20350       && TYPE_CODE (type) != TYPE_CODE_FUNC
20351       && TYPE_CODE (type) != TYPE_CODE_FLT
20352       && !HAVE_GNAT_AUX_INFO (type))
20353     INIT_GNAT_SPECIFIC (type);
20354
20355   if (dwarf2_per_objfile->die_type_hash == NULL)
20356     {
20357       dwarf2_per_objfile->die_type_hash =
20358         htab_create_alloc_ex (127,
20359                               per_cu_offset_and_type_hash,
20360                               per_cu_offset_and_type_eq,
20361                               NULL,
20362                               &objfile->objfile_obstack,
20363                               hashtab_obstack_allocate,
20364                               dummy_obstack_deallocate);
20365     }
20366
20367   ofs.per_cu = cu->per_cu;
20368   ofs.offset = die->offset;
20369   ofs.type = type;
20370   slot = (struct dwarf2_per_cu_offset_and_type **)
20371     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20372   if (*slot)
20373     complaint (&symfile_complaints,
20374                _("A problem internal to GDB: DIE 0x%x has type already set"),
20375                die->offset.sect_off);
20376   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20377   **slot = ofs;
20378   return type;
20379 }
20380
20381 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20382    or return NULL if the die does not have a saved type.  */
20383
20384 static struct type *
20385 get_die_type_at_offset (sect_offset offset,
20386                         struct dwarf2_per_cu_data *per_cu)
20387 {
20388   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20389
20390   if (dwarf2_per_objfile->die_type_hash == NULL)
20391     return NULL;
20392
20393   ofs.per_cu = per_cu;
20394   ofs.offset = offset;
20395   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20396   if (slot)
20397     return slot->type;
20398   else
20399     return NULL;
20400 }
20401
20402 /* Look up the type for DIE in CU in die_type_hash,
20403    or return NULL if DIE does not have a saved type.  */
20404
20405 static struct type *
20406 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20407 {
20408   return get_die_type_at_offset (die->offset, cu->per_cu);
20409 }
20410
20411 /* Add a dependence relationship from CU to REF_PER_CU.  */
20412
20413 static void
20414 dwarf2_add_dependence (struct dwarf2_cu *cu,
20415                        struct dwarf2_per_cu_data *ref_per_cu)
20416 {
20417   void **slot;
20418
20419   if (cu->dependencies == NULL)
20420     cu->dependencies
20421       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20422                               NULL, &cu->comp_unit_obstack,
20423                               hashtab_obstack_allocate,
20424                               dummy_obstack_deallocate);
20425
20426   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20427   if (*slot == NULL)
20428     *slot = ref_per_cu;
20429 }
20430
20431 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20432    Set the mark field in every compilation unit in the
20433    cache that we must keep because we are keeping CU.  */
20434
20435 static int
20436 dwarf2_mark_helper (void **slot, void *data)
20437 {
20438   struct dwarf2_per_cu_data *per_cu;
20439
20440   per_cu = (struct dwarf2_per_cu_data *) *slot;
20441
20442   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20443      reading of the chain.  As such dependencies remain valid it is not much
20444      useful to track and undo them during QUIT cleanups.  */
20445   if (per_cu->cu == NULL)
20446     return 1;
20447
20448   if (per_cu->cu->mark)
20449     return 1;
20450   per_cu->cu->mark = 1;
20451
20452   if (per_cu->cu->dependencies != NULL)
20453     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20454
20455   return 1;
20456 }
20457
20458 /* Set the mark field in CU and in every other compilation unit in the
20459    cache that we must keep because we are keeping CU.  */
20460
20461 static void
20462 dwarf2_mark (struct dwarf2_cu *cu)
20463 {
20464   if (cu->mark)
20465     return;
20466   cu->mark = 1;
20467   if (cu->dependencies != NULL)
20468     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20469 }
20470
20471 static void
20472 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20473 {
20474   while (per_cu)
20475     {
20476       per_cu->cu->mark = 0;
20477       per_cu = per_cu->cu->read_in_chain;
20478     }
20479 }
20480
20481 /* Trivial hash function for partial_die_info: the hash value of a DIE
20482    is its offset in .debug_info for this objfile.  */
20483
20484 static hashval_t
20485 partial_die_hash (const void *item)
20486 {
20487   const struct partial_die_info *part_die = item;
20488
20489   return part_die->offset.sect_off;
20490 }
20491
20492 /* Trivial comparison function for partial_die_info structures: two DIEs
20493    are equal if they have the same offset.  */
20494
20495 static int
20496 partial_die_eq (const void *item_lhs, const void *item_rhs)
20497 {
20498   const struct partial_die_info *part_die_lhs = item_lhs;
20499   const struct partial_die_info *part_die_rhs = item_rhs;
20500
20501   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20502 }
20503
20504 static struct cmd_list_element *set_dwarf2_cmdlist;
20505 static struct cmd_list_element *show_dwarf2_cmdlist;
20506
20507 static void
20508 set_dwarf2_cmd (char *args, int from_tty)
20509 {
20510   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20511 }
20512
20513 static void
20514 show_dwarf2_cmd (char *args, int from_tty)
20515 {
20516   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20517 }
20518
20519 /* Free data associated with OBJFILE, if necessary.  */
20520
20521 static void
20522 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20523 {
20524   struct dwarf2_per_objfile *data = d;
20525   int ix;
20526
20527   /* Make sure we don't accidentally use dwarf2_per_objfile while
20528      cleaning up.  */
20529   dwarf2_per_objfile = NULL;
20530
20531   for (ix = 0; ix < data->n_comp_units; ++ix)
20532    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20533
20534   for (ix = 0; ix < data->n_type_units; ++ix)
20535     VEC_free (dwarf2_per_cu_ptr,
20536               data->all_type_units[ix]->per_cu.imported_symtabs);
20537   xfree (data->all_type_units);
20538
20539   VEC_free (dwarf2_section_info_def, data->types);
20540
20541   if (data->dwo_files)
20542     free_dwo_files (data->dwo_files, objfile);
20543   if (data->dwp_file)
20544     gdb_bfd_unref (data->dwp_file->dbfd);
20545
20546   if (data->dwz_file && data->dwz_file->dwz_bfd)
20547     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20548 }
20549
20550 \f
20551 /* The "save gdb-index" command.  */
20552
20553 /* The contents of the hash table we create when building the string
20554    table.  */
20555 struct strtab_entry
20556 {
20557   offset_type offset;
20558   const char *str;
20559 };
20560
20561 /* Hash function for a strtab_entry.
20562
20563    Function is used only during write_hash_table so no index format backward
20564    compatibility is needed.  */
20565
20566 static hashval_t
20567 hash_strtab_entry (const void *e)
20568 {
20569   const struct strtab_entry *entry = e;
20570   return mapped_index_string_hash (INT_MAX, entry->str);
20571 }
20572
20573 /* Equality function for a strtab_entry.  */
20574
20575 static int
20576 eq_strtab_entry (const void *a, const void *b)
20577 {
20578   const struct strtab_entry *ea = a;
20579   const struct strtab_entry *eb = b;
20580   return !strcmp (ea->str, eb->str);
20581 }
20582
20583 /* Create a strtab_entry hash table.  */
20584
20585 static htab_t
20586 create_strtab (void)
20587 {
20588   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20589                             xfree, xcalloc, xfree);
20590 }
20591
20592 /* Add a string to the constant pool.  Return the string's offset in
20593    host order.  */
20594
20595 static offset_type
20596 add_string (htab_t table, struct obstack *cpool, const char *str)
20597 {
20598   void **slot;
20599   struct strtab_entry entry;
20600   struct strtab_entry *result;
20601
20602   entry.str = str;
20603   slot = htab_find_slot (table, &entry, INSERT);
20604   if (*slot)
20605     result = *slot;
20606   else
20607     {
20608       result = XNEW (struct strtab_entry);
20609       result->offset = obstack_object_size (cpool);
20610       result->str = str;
20611       obstack_grow_str0 (cpool, str);
20612       *slot = result;
20613     }
20614   return result->offset;
20615 }
20616
20617 /* An entry in the symbol table.  */
20618 struct symtab_index_entry
20619 {
20620   /* The name of the symbol.  */
20621   const char *name;
20622   /* The offset of the name in the constant pool.  */
20623   offset_type index_offset;
20624   /* A sorted vector of the indices of all the CUs that hold an object
20625      of this name.  */
20626   VEC (offset_type) *cu_indices;
20627 };
20628
20629 /* The symbol table.  This is a power-of-2-sized hash table.  */
20630 struct mapped_symtab
20631 {
20632   offset_type n_elements;
20633   offset_type size;
20634   struct symtab_index_entry **data;
20635 };
20636
20637 /* Hash function for a symtab_index_entry.  */
20638
20639 static hashval_t
20640 hash_symtab_entry (const void *e)
20641 {
20642   const struct symtab_index_entry *entry = e;
20643   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20644                          sizeof (offset_type) * VEC_length (offset_type,
20645                                                             entry->cu_indices),
20646                          0);
20647 }
20648
20649 /* Equality function for a symtab_index_entry.  */
20650
20651 static int
20652 eq_symtab_entry (const void *a, const void *b)
20653 {
20654   const struct symtab_index_entry *ea = a;
20655   const struct symtab_index_entry *eb = b;
20656   int len = VEC_length (offset_type, ea->cu_indices);
20657   if (len != VEC_length (offset_type, eb->cu_indices))
20658     return 0;
20659   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20660                   VEC_address (offset_type, eb->cu_indices),
20661                   sizeof (offset_type) * len);
20662 }
20663
20664 /* Destroy a symtab_index_entry.  */
20665
20666 static void
20667 delete_symtab_entry (void *p)
20668 {
20669   struct symtab_index_entry *entry = p;
20670   VEC_free (offset_type, entry->cu_indices);
20671   xfree (entry);
20672 }
20673
20674 /* Create a hash table holding symtab_index_entry objects.  */
20675
20676 static htab_t
20677 create_symbol_hash_table (void)
20678 {
20679   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20680                             delete_symtab_entry, xcalloc, xfree);
20681 }
20682
20683 /* Create a new mapped symtab object.  */
20684
20685 static struct mapped_symtab *
20686 create_mapped_symtab (void)
20687 {
20688   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20689   symtab->n_elements = 0;
20690   symtab->size = 1024;
20691   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20692   return symtab;
20693 }
20694
20695 /* Destroy a mapped_symtab.  */
20696
20697 static void
20698 cleanup_mapped_symtab (void *p)
20699 {
20700   struct mapped_symtab *symtab = p;
20701   /* The contents of the array are freed when the other hash table is
20702      destroyed.  */
20703   xfree (symtab->data);
20704   xfree (symtab);
20705 }
20706
20707 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20708    the slot.
20709    
20710    Function is used only during write_hash_table so no index format backward
20711    compatibility is needed.  */
20712
20713 static struct symtab_index_entry **
20714 find_slot (struct mapped_symtab *symtab, const char *name)
20715 {
20716   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20717
20718   index = hash & (symtab->size - 1);
20719   step = ((hash * 17) & (symtab->size - 1)) | 1;
20720
20721   for (;;)
20722     {
20723       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20724         return &symtab->data[index];
20725       index = (index + step) & (symtab->size - 1);
20726     }
20727 }
20728
20729 /* Expand SYMTAB's hash table.  */
20730
20731 static void
20732 hash_expand (struct mapped_symtab *symtab)
20733 {
20734   offset_type old_size = symtab->size;
20735   offset_type i;
20736   struct symtab_index_entry **old_entries = symtab->data;
20737
20738   symtab->size *= 2;
20739   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20740
20741   for (i = 0; i < old_size; ++i)
20742     {
20743       if (old_entries[i])
20744         {
20745           struct symtab_index_entry **slot = find_slot (symtab,
20746                                                         old_entries[i]->name);
20747           *slot = old_entries[i];
20748         }
20749     }
20750
20751   xfree (old_entries);
20752 }
20753
20754 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20755    CU_INDEX is the index of the CU in which the symbol appears.
20756    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20757
20758 static void
20759 add_index_entry (struct mapped_symtab *symtab, const char *name,
20760                  int is_static, gdb_index_symbol_kind kind,
20761                  offset_type cu_index)
20762 {
20763   struct symtab_index_entry **slot;
20764   offset_type cu_index_and_attrs;
20765
20766   ++symtab->n_elements;
20767   if (4 * symtab->n_elements / 3 >= symtab->size)
20768     hash_expand (symtab);
20769
20770   slot = find_slot (symtab, name);
20771   if (!*slot)
20772     {
20773       *slot = XNEW (struct symtab_index_entry);
20774       (*slot)->name = name;
20775       /* index_offset is set later.  */
20776       (*slot)->cu_indices = NULL;
20777     }
20778
20779   cu_index_and_attrs = 0;
20780   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20781   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20782   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20783
20784   /* We don't want to record an index value twice as we want to avoid the
20785      duplication.
20786      We process all global symbols and then all static symbols
20787      (which would allow us to avoid the duplication by only having to check
20788      the last entry pushed), but a symbol could have multiple kinds in one CU.
20789      To keep things simple we don't worry about the duplication here and
20790      sort and uniqufy the list after we've processed all symbols.  */
20791   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20792 }
20793
20794 /* qsort helper routine for uniquify_cu_indices.  */
20795
20796 static int
20797 offset_type_compare (const void *ap, const void *bp)
20798 {
20799   offset_type a = *(offset_type *) ap;
20800   offset_type b = *(offset_type *) bp;
20801
20802   return (a > b) - (b > a);
20803 }
20804
20805 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20806
20807 static void
20808 uniquify_cu_indices (struct mapped_symtab *symtab)
20809 {
20810   int i;
20811
20812   for (i = 0; i < symtab->size; ++i)
20813     {
20814       struct symtab_index_entry *entry = symtab->data[i];
20815
20816       if (entry
20817           && entry->cu_indices != NULL)
20818         {
20819           unsigned int next_to_insert, next_to_check;
20820           offset_type last_value;
20821
20822           qsort (VEC_address (offset_type, entry->cu_indices),
20823                  VEC_length (offset_type, entry->cu_indices),
20824                  sizeof (offset_type), offset_type_compare);
20825
20826           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20827           next_to_insert = 1;
20828           for (next_to_check = 1;
20829                next_to_check < VEC_length (offset_type, entry->cu_indices);
20830                ++next_to_check)
20831             {
20832               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20833                   != last_value)
20834                 {
20835                   last_value = VEC_index (offset_type, entry->cu_indices,
20836                                           next_to_check);
20837                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20838                                last_value);
20839                   ++next_to_insert;
20840                 }
20841             }
20842           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20843         }
20844     }
20845 }
20846
20847 /* Add a vector of indices to the constant pool.  */
20848
20849 static offset_type
20850 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20851                       struct symtab_index_entry *entry)
20852 {
20853   void **slot;
20854
20855   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20856   if (!*slot)
20857     {
20858       offset_type len = VEC_length (offset_type, entry->cu_indices);
20859       offset_type val = MAYBE_SWAP (len);
20860       offset_type iter;
20861       int i;
20862
20863       *slot = entry;
20864       entry->index_offset = obstack_object_size (cpool);
20865
20866       obstack_grow (cpool, &val, sizeof (val));
20867       for (i = 0;
20868            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20869            ++i)
20870         {
20871           val = MAYBE_SWAP (iter);
20872           obstack_grow (cpool, &val, sizeof (val));
20873         }
20874     }
20875   else
20876     {
20877       struct symtab_index_entry *old_entry = *slot;
20878       entry->index_offset = old_entry->index_offset;
20879       entry = old_entry;
20880     }
20881   return entry->index_offset;
20882 }
20883
20884 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20885    constant pool entries going into the obstack CPOOL.  */
20886
20887 static void
20888 write_hash_table (struct mapped_symtab *symtab,
20889                   struct obstack *output, struct obstack *cpool)
20890 {
20891   offset_type i;
20892   htab_t symbol_hash_table;
20893   htab_t str_table;
20894
20895   symbol_hash_table = create_symbol_hash_table ();
20896   str_table = create_strtab ();
20897
20898   /* We add all the index vectors to the constant pool first, to
20899      ensure alignment is ok.  */
20900   for (i = 0; i < symtab->size; ++i)
20901     {
20902       if (symtab->data[i])
20903         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20904     }
20905
20906   /* Now write out the hash table.  */
20907   for (i = 0; i < symtab->size; ++i)
20908     {
20909       offset_type str_off, vec_off;
20910
20911       if (symtab->data[i])
20912         {
20913           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20914           vec_off = symtab->data[i]->index_offset;
20915         }
20916       else
20917         {
20918           /* While 0 is a valid constant pool index, it is not valid
20919              to have 0 for both offsets.  */
20920           str_off = 0;
20921           vec_off = 0;
20922         }
20923
20924       str_off = MAYBE_SWAP (str_off);
20925       vec_off = MAYBE_SWAP (vec_off);
20926
20927       obstack_grow (output, &str_off, sizeof (str_off));
20928       obstack_grow (output, &vec_off, sizeof (vec_off));
20929     }
20930
20931   htab_delete (str_table);
20932   htab_delete (symbol_hash_table);
20933 }
20934
20935 /* Struct to map psymtab to CU index in the index file.  */
20936 struct psymtab_cu_index_map
20937 {
20938   struct partial_symtab *psymtab;
20939   unsigned int cu_index;
20940 };
20941
20942 static hashval_t
20943 hash_psymtab_cu_index (const void *item)
20944 {
20945   const struct psymtab_cu_index_map *map = item;
20946
20947   return htab_hash_pointer (map->psymtab);
20948 }
20949
20950 static int
20951 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20952 {
20953   const struct psymtab_cu_index_map *lhs = item_lhs;
20954   const struct psymtab_cu_index_map *rhs = item_rhs;
20955
20956   return lhs->psymtab == rhs->psymtab;
20957 }
20958
20959 /* Helper struct for building the address table.  */
20960 struct addrmap_index_data
20961 {
20962   struct objfile *objfile;
20963   struct obstack *addr_obstack;
20964   htab_t cu_index_htab;
20965
20966   /* Non-zero if the previous_* fields are valid.
20967      We can't write an entry until we see the next entry (since it is only then
20968      that we know the end of the entry).  */
20969   int previous_valid;
20970   /* Index of the CU in the table of all CUs in the index file.  */
20971   unsigned int previous_cu_index;
20972   /* Start address of the CU.  */
20973   CORE_ADDR previous_cu_start;
20974 };
20975
20976 /* Write an address entry to OBSTACK.  */
20977
20978 static void
20979 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20980                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20981 {
20982   offset_type cu_index_to_write;
20983   gdb_byte addr[8];
20984   CORE_ADDR baseaddr;
20985
20986   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20987
20988   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20989   obstack_grow (obstack, addr, 8);
20990   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20991   obstack_grow (obstack, addr, 8);
20992   cu_index_to_write = MAYBE_SWAP (cu_index);
20993   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20994 }
20995
20996 /* Worker function for traversing an addrmap to build the address table.  */
20997
20998 static int
20999 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21000 {
21001   struct addrmap_index_data *data = datap;
21002   struct partial_symtab *pst = obj;
21003
21004   if (data->previous_valid)
21005     add_address_entry (data->objfile, data->addr_obstack,
21006                        data->previous_cu_start, start_addr,
21007                        data->previous_cu_index);
21008
21009   data->previous_cu_start = start_addr;
21010   if (pst != NULL)
21011     {
21012       struct psymtab_cu_index_map find_map, *map;
21013       find_map.psymtab = pst;
21014       map = htab_find (data->cu_index_htab, &find_map);
21015       gdb_assert (map != NULL);
21016       data->previous_cu_index = map->cu_index;
21017       data->previous_valid = 1;
21018     }
21019   else
21020       data->previous_valid = 0;
21021
21022   return 0;
21023 }
21024
21025 /* Write OBJFILE's address map to OBSTACK.
21026    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21027    in the index file.  */
21028
21029 static void
21030 write_address_map (struct objfile *objfile, struct obstack *obstack,
21031                    htab_t cu_index_htab)
21032 {
21033   struct addrmap_index_data addrmap_index_data;
21034
21035   /* When writing the address table, we have to cope with the fact that
21036      the addrmap iterator only provides the start of a region; we have to
21037      wait until the next invocation to get the start of the next region.  */
21038
21039   addrmap_index_data.objfile = objfile;
21040   addrmap_index_data.addr_obstack = obstack;
21041   addrmap_index_data.cu_index_htab = cu_index_htab;
21042   addrmap_index_data.previous_valid = 0;
21043
21044   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21045                    &addrmap_index_data);
21046
21047   /* It's highly unlikely the last entry (end address = 0xff...ff)
21048      is valid, but we should still handle it.
21049      The end address is recorded as the start of the next region, but that
21050      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21051      anyway.  */
21052   if (addrmap_index_data.previous_valid)
21053     add_address_entry (objfile, obstack,
21054                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21055                        addrmap_index_data.previous_cu_index);
21056 }
21057
21058 /* Return the symbol kind of PSYM.  */
21059
21060 static gdb_index_symbol_kind
21061 symbol_kind (struct partial_symbol *psym)
21062 {
21063   domain_enum domain = PSYMBOL_DOMAIN (psym);
21064   enum address_class aclass = PSYMBOL_CLASS (psym);
21065
21066   switch (domain)
21067     {
21068     case VAR_DOMAIN:
21069       switch (aclass)
21070         {
21071         case LOC_BLOCK:
21072           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21073         case LOC_TYPEDEF:
21074           return GDB_INDEX_SYMBOL_KIND_TYPE;
21075         case LOC_COMPUTED:
21076         case LOC_CONST_BYTES:
21077         case LOC_OPTIMIZED_OUT:
21078         case LOC_STATIC:
21079           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21080         case LOC_CONST:
21081           /* Note: It's currently impossible to recognize psyms as enum values
21082              short of reading the type info.  For now punt.  */
21083           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21084         default:
21085           /* There are other LOC_FOO values that one might want to classify
21086              as variables, but dwarf2read.c doesn't currently use them.  */
21087           return GDB_INDEX_SYMBOL_KIND_OTHER;
21088         }
21089     case STRUCT_DOMAIN:
21090       return GDB_INDEX_SYMBOL_KIND_TYPE;
21091     default:
21092       return GDB_INDEX_SYMBOL_KIND_OTHER;
21093     }
21094 }
21095
21096 /* Add a list of partial symbols to SYMTAB.  */
21097
21098 static void
21099 write_psymbols (struct mapped_symtab *symtab,
21100                 htab_t psyms_seen,
21101                 struct partial_symbol **psymp,
21102                 int count,
21103                 offset_type cu_index,
21104                 int is_static)
21105 {
21106   for (; count-- > 0; ++psymp)
21107     {
21108       struct partial_symbol *psym = *psymp;
21109       void **slot;
21110
21111       if (SYMBOL_LANGUAGE (psym) == language_ada)
21112         error (_("Ada is not currently supported by the index"));
21113
21114       /* Only add a given psymbol once.  */
21115       slot = htab_find_slot (psyms_seen, psym, INSERT);
21116       if (!*slot)
21117         {
21118           gdb_index_symbol_kind kind = symbol_kind (psym);
21119
21120           *slot = psym;
21121           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21122                            is_static, kind, cu_index);
21123         }
21124     }
21125 }
21126
21127 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21128    exception if there is an error.  */
21129
21130 static void
21131 write_obstack (FILE *file, struct obstack *obstack)
21132 {
21133   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21134               file)
21135       != obstack_object_size (obstack))
21136     error (_("couldn't data write to file"));
21137 }
21138
21139 /* Unlink a file if the argument is not NULL.  */
21140
21141 static void
21142 unlink_if_set (void *p)
21143 {
21144   char **filename = p;
21145   if (*filename)
21146     unlink (*filename);
21147 }
21148
21149 /* A helper struct used when iterating over debug_types.  */
21150 struct signatured_type_index_data
21151 {
21152   struct objfile *objfile;
21153   struct mapped_symtab *symtab;
21154   struct obstack *types_list;
21155   htab_t psyms_seen;
21156   int cu_index;
21157 };
21158
21159 /* A helper function that writes a single signatured_type to an
21160    obstack.  */
21161
21162 static int
21163 write_one_signatured_type (void **slot, void *d)
21164 {
21165   struct signatured_type_index_data *info = d;
21166   struct signatured_type *entry = (struct signatured_type *) *slot;
21167   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21168   gdb_byte val[8];
21169
21170   write_psymbols (info->symtab,
21171                   info->psyms_seen,
21172                   info->objfile->global_psymbols.list
21173                   + psymtab->globals_offset,
21174                   psymtab->n_global_syms, info->cu_index,
21175                   0);
21176   write_psymbols (info->symtab,
21177                   info->psyms_seen,
21178                   info->objfile->static_psymbols.list
21179                   + psymtab->statics_offset,
21180                   psymtab->n_static_syms, info->cu_index,
21181                   1);
21182
21183   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21184                           entry->per_cu.offset.sect_off);
21185   obstack_grow (info->types_list, val, 8);
21186   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21187                           entry->type_offset_in_tu.cu_off);
21188   obstack_grow (info->types_list, val, 8);
21189   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21190   obstack_grow (info->types_list, val, 8);
21191
21192   ++info->cu_index;
21193
21194   return 1;
21195 }
21196
21197 /* Recurse into all "included" dependencies and write their symbols as
21198    if they appeared in this psymtab.  */
21199
21200 static void
21201 recursively_write_psymbols (struct objfile *objfile,
21202                             struct partial_symtab *psymtab,
21203                             struct mapped_symtab *symtab,
21204                             htab_t psyms_seen,
21205                             offset_type cu_index)
21206 {
21207   int i;
21208
21209   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21210     if (psymtab->dependencies[i]->user != NULL)
21211       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21212                                   symtab, psyms_seen, cu_index);
21213
21214   write_psymbols (symtab,
21215                   psyms_seen,
21216                   objfile->global_psymbols.list + psymtab->globals_offset,
21217                   psymtab->n_global_syms, cu_index,
21218                   0);
21219   write_psymbols (symtab,
21220                   psyms_seen,
21221                   objfile->static_psymbols.list + psymtab->statics_offset,
21222                   psymtab->n_static_syms, cu_index,
21223                   1);
21224 }
21225
21226 /* Create an index file for OBJFILE in the directory DIR.  */
21227
21228 static void
21229 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21230 {
21231   struct cleanup *cleanup;
21232   char *filename, *cleanup_filename;
21233   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21234   struct obstack cu_list, types_cu_list;
21235   int i;
21236   FILE *out_file;
21237   struct mapped_symtab *symtab;
21238   offset_type val, size_of_contents, total_len;
21239   struct stat st;
21240   htab_t psyms_seen;
21241   htab_t cu_index_htab;
21242   struct psymtab_cu_index_map *psymtab_cu_index_map;
21243
21244   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21245     return;
21246
21247   if (dwarf2_per_objfile->using_index)
21248     error (_("Cannot use an index to create the index"));
21249
21250   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21251     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21252
21253   if (stat (objfile->name, &st) < 0)
21254     perror_with_name (objfile->name);
21255
21256   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
21257                      INDEX_SUFFIX, (char *) NULL);
21258   cleanup = make_cleanup (xfree, filename);
21259
21260   out_file = gdb_fopen_cloexec (filename, "wb");
21261   if (!out_file)
21262     error (_("Can't open `%s' for writing"), filename);
21263
21264   cleanup_filename = filename;
21265   make_cleanup (unlink_if_set, &cleanup_filename);
21266
21267   symtab = create_mapped_symtab ();
21268   make_cleanup (cleanup_mapped_symtab, symtab);
21269
21270   obstack_init (&addr_obstack);
21271   make_cleanup_obstack_free (&addr_obstack);
21272
21273   obstack_init (&cu_list);
21274   make_cleanup_obstack_free (&cu_list);
21275
21276   obstack_init (&types_cu_list);
21277   make_cleanup_obstack_free (&types_cu_list);
21278
21279   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21280                                   NULL, xcalloc, xfree);
21281   make_cleanup_htab_delete (psyms_seen);
21282
21283   /* While we're scanning CU's create a table that maps a psymtab pointer
21284      (which is what addrmap records) to its index (which is what is recorded
21285      in the index file).  This will later be needed to write the address
21286      table.  */
21287   cu_index_htab = htab_create_alloc (100,
21288                                      hash_psymtab_cu_index,
21289                                      eq_psymtab_cu_index,
21290                                      NULL, xcalloc, xfree);
21291   make_cleanup_htab_delete (cu_index_htab);
21292   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21293     xmalloc (sizeof (struct psymtab_cu_index_map)
21294              * dwarf2_per_objfile->n_comp_units);
21295   make_cleanup (xfree, psymtab_cu_index_map);
21296
21297   /* The CU list is already sorted, so we don't need to do additional
21298      work here.  Also, the debug_types entries do not appear in
21299      all_comp_units, but only in their own hash table.  */
21300   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21301     {
21302       struct dwarf2_per_cu_data *per_cu
21303         = dwarf2_per_objfile->all_comp_units[i];
21304       struct partial_symtab *psymtab = per_cu->v.psymtab;
21305       gdb_byte val[8];
21306       struct psymtab_cu_index_map *map;
21307       void **slot;
21308
21309       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21310          It may be referenced from a local scope but in such case it does not
21311          need to be present in .gdb_index.  */
21312       if (psymtab == NULL)
21313         continue;
21314
21315       if (psymtab->user == NULL)
21316         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21317
21318       map = &psymtab_cu_index_map[i];
21319       map->psymtab = psymtab;
21320       map->cu_index = i;
21321       slot = htab_find_slot (cu_index_htab, map, INSERT);
21322       gdb_assert (slot != NULL);
21323       gdb_assert (*slot == NULL);
21324       *slot = map;
21325
21326       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21327                               per_cu->offset.sect_off);
21328       obstack_grow (&cu_list, val, 8);
21329       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21330       obstack_grow (&cu_list, val, 8);
21331     }
21332
21333   /* Dump the address map.  */
21334   write_address_map (objfile, &addr_obstack, cu_index_htab);
21335
21336   /* Write out the .debug_type entries, if any.  */
21337   if (dwarf2_per_objfile->signatured_types)
21338     {
21339       struct signatured_type_index_data sig_data;
21340
21341       sig_data.objfile = objfile;
21342       sig_data.symtab = symtab;
21343       sig_data.types_list = &types_cu_list;
21344       sig_data.psyms_seen = psyms_seen;
21345       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21346       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21347                               write_one_signatured_type, &sig_data);
21348     }
21349
21350   /* Now that we've processed all symbols we can shrink their cu_indices
21351      lists.  */
21352   uniquify_cu_indices (symtab);
21353
21354   obstack_init (&constant_pool);
21355   make_cleanup_obstack_free (&constant_pool);
21356   obstack_init (&symtab_obstack);
21357   make_cleanup_obstack_free (&symtab_obstack);
21358   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21359
21360   obstack_init (&contents);
21361   make_cleanup_obstack_free (&contents);
21362   size_of_contents = 6 * sizeof (offset_type);
21363   total_len = size_of_contents;
21364
21365   /* The version number.  */
21366   val = MAYBE_SWAP (8);
21367   obstack_grow (&contents, &val, sizeof (val));
21368
21369   /* The offset of the CU list from the start of the file.  */
21370   val = MAYBE_SWAP (total_len);
21371   obstack_grow (&contents, &val, sizeof (val));
21372   total_len += obstack_object_size (&cu_list);
21373
21374   /* The offset of the types CU list from the start of the file.  */
21375   val = MAYBE_SWAP (total_len);
21376   obstack_grow (&contents, &val, sizeof (val));
21377   total_len += obstack_object_size (&types_cu_list);
21378
21379   /* The offset of the address table from the start of the file.  */
21380   val = MAYBE_SWAP (total_len);
21381   obstack_grow (&contents, &val, sizeof (val));
21382   total_len += obstack_object_size (&addr_obstack);
21383
21384   /* The offset of the symbol table from the start of the file.  */
21385   val = MAYBE_SWAP (total_len);
21386   obstack_grow (&contents, &val, sizeof (val));
21387   total_len += obstack_object_size (&symtab_obstack);
21388
21389   /* The offset of the constant pool from the start of the file.  */
21390   val = MAYBE_SWAP (total_len);
21391   obstack_grow (&contents, &val, sizeof (val));
21392   total_len += obstack_object_size (&constant_pool);
21393
21394   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21395
21396   write_obstack (out_file, &contents);
21397   write_obstack (out_file, &cu_list);
21398   write_obstack (out_file, &types_cu_list);
21399   write_obstack (out_file, &addr_obstack);
21400   write_obstack (out_file, &symtab_obstack);
21401   write_obstack (out_file, &constant_pool);
21402
21403   fclose (out_file);
21404
21405   /* We want to keep the file, so we set cleanup_filename to NULL
21406      here.  See unlink_if_set.  */
21407   cleanup_filename = NULL;
21408
21409   do_cleanups (cleanup);
21410 }
21411
21412 /* Implementation of the `save gdb-index' command.
21413    
21414    Note that the file format used by this command is documented in the
21415    GDB manual.  Any changes here must be documented there.  */
21416
21417 static void
21418 save_gdb_index_command (char *arg, int from_tty)
21419 {
21420   struct objfile *objfile;
21421
21422   if (!arg || !*arg)
21423     error (_("usage: save gdb-index DIRECTORY"));
21424
21425   ALL_OBJFILES (objfile)
21426   {
21427     struct stat st;
21428
21429     /* If the objfile does not correspond to an actual file, skip it.  */
21430     if (stat (objfile->name, &st) < 0)
21431       continue;
21432
21433     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21434     if (dwarf2_per_objfile)
21435       {
21436         volatile struct gdb_exception except;
21437
21438         TRY_CATCH (except, RETURN_MASK_ERROR)
21439           {
21440             write_psymtabs_to_index (objfile, arg);
21441           }
21442         if (except.reason < 0)
21443           exception_fprintf (gdb_stderr, except,
21444                              _("Error while writing index for `%s': "),
21445                              objfile->name);
21446       }
21447   }
21448 }
21449
21450 \f
21451
21452 int dwarf2_always_disassemble;
21453
21454 static void
21455 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21456                                 struct cmd_list_element *c, const char *value)
21457 {
21458   fprintf_filtered (file,
21459                     _("Whether to always disassemble "
21460                       "DWARF expressions is %s.\n"),
21461                     value);
21462 }
21463
21464 static void
21465 show_check_physname (struct ui_file *file, int from_tty,
21466                      struct cmd_list_element *c, const char *value)
21467 {
21468   fprintf_filtered (file,
21469                     _("Whether to check \"physname\" is %s.\n"),
21470                     value);
21471 }
21472
21473 void _initialize_dwarf2_read (void);
21474
21475 void
21476 _initialize_dwarf2_read (void)
21477 {
21478   struct cmd_list_element *c;
21479
21480   dwarf2_objfile_data_key
21481     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21482
21483   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21484 Set DWARF 2 specific variables.\n\
21485 Configure DWARF 2 variables such as the cache size"),
21486                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21487                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21488
21489   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21490 Show DWARF 2 specific variables\n\
21491 Show DWARF 2 variables such as the cache size"),
21492                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21493                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21494
21495   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21496                             &dwarf2_max_cache_age, _("\
21497 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21498 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21499 A higher limit means that cached compilation units will be stored\n\
21500 in memory longer, and more total memory will be used.  Zero disables\n\
21501 caching, which can slow down startup."),
21502                             NULL,
21503                             show_dwarf2_max_cache_age,
21504                             &set_dwarf2_cmdlist,
21505                             &show_dwarf2_cmdlist);
21506
21507   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21508                            &dwarf2_always_disassemble, _("\
21509 Set whether `info address' always disassembles DWARF expressions."), _("\
21510 Show whether `info address' always disassembles DWARF expressions."), _("\
21511 When enabled, DWARF expressions are always printed in an assembly-like\n\
21512 syntax.  When disabled, expressions will be printed in a more\n\
21513 conversational style, when possible."),
21514                            NULL,
21515                            show_dwarf2_always_disassemble,
21516                            &set_dwarf2_cmdlist,
21517                            &show_dwarf2_cmdlist);
21518
21519   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21520 Set debugging of the dwarf2 reader."), _("\
21521 Show debugging of the dwarf2 reader."), _("\
21522 When enabled, debugging messages are printed during dwarf2 reading\n\
21523 and symtab expansion."),
21524                             NULL,
21525                             NULL,
21526                             &setdebuglist, &showdebuglist);
21527
21528   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21529 Set debugging of the dwarf2 DIE reader."), _("\
21530 Show debugging of the dwarf2 DIE reader."), _("\
21531 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21532 The value is the maximum depth to print."),
21533                              NULL,
21534                              NULL,
21535                              &setdebuglist, &showdebuglist);
21536
21537   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21538 Set cross-checking of \"physname\" code against demangler."), _("\
21539 Show cross-checking of \"physname\" code against demangler."), _("\
21540 When enabled, GDB's internal \"physname\" code is checked against\n\
21541 the demangler."),
21542                            NULL, show_check_physname,
21543                            &setdebuglist, &showdebuglist);
21544
21545   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21546                            no_class, &use_deprecated_index_sections, _("\
21547 Set whether to use deprecated gdb_index sections."), _("\
21548 Show whether to use deprecated gdb_index sections."), _("\
21549 When enabled, deprecated .gdb_index sections are used anyway.\n\
21550 Normally they are ignored either because of a missing feature or\n\
21551 performance issue.\n\
21552 Warning: This option must be enabled before gdb reads the file."),
21553                            NULL,
21554                            NULL,
21555                            &setlist, &showlist);
21556
21557   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21558                _("\
21559 Save a gdb-index file.\n\
21560 Usage: save gdb-index DIRECTORY"),
21561                &save_cmdlist);
21562   set_cmd_completer (c, filename_completer);
21563
21564   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21565                                                         &dwarf2_locexpr_funcs);
21566   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21567                                                         &dwarf2_loclist_funcs);
21568
21569   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21570                                         &dwarf2_block_frame_base_locexpr_funcs);
21571   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21572                                         &dwarf2_block_frame_base_loclist_funcs);
21573 }