Code cleanup: Move variable.
[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   /* Backlink to our per_cu entry.  */
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      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
615   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
616 };
617
618 /* Entry in the signatured_types hash table.  */
619
620 struct signatured_type
621 {
622   /* The "per_cu" object of this type.
623      This struct is used iff per_cu.is_debug_types.
624      N.B.: This is the first member so that it's easy to convert pointers
625      between them.  */
626   struct dwarf2_per_cu_data per_cu;
627
628   /* The type's signature.  */
629   ULONGEST signature;
630
631   /* Offset in the TU of the type's DIE, as read from the TU header.
632      If this TU is a DWO stub and the definition lives in a DWO file
633      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
634   cu_offset type_offset_in_tu;
635
636   /* Offset in the section of the type's DIE.
637      If the definition lives in a DWO file, this is the offset in the
638      .debug_types.dwo section.
639      The value is zero until the actual value is known.
640      Zero is otherwise not a valid section offset.  */
641   sect_offset type_offset_in_section;
642
643   /* Type units are grouped by their DW_AT_stmt_list entry so that they
644      can share them.  This points to the containing symtab.  */
645   struct type_unit_group *type_unit_group;
646
647   /* The type.
648      The first time we encounter this type we fully read it in and install it
649      in the symbol tables.  Subsequent times we only need the type.  */
650   struct type *type;
651
652   /* Containing DWO unit.
653      This field is valid iff per_cu.reading_dwo_directly.  */
654   struct dwo_unit *dwo_unit;
655 };
656
657 typedef struct signatured_type *sig_type_ptr;
658 DEF_VEC_P (sig_type_ptr);
659
660 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
661    This includes type_unit_group and quick_file_names.  */
662
663 struct stmt_list_hash
664 {
665   /* The DWO unit this table is from or NULL if there is none.  */
666   struct dwo_unit *dwo_unit;
667
668   /* Offset in .debug_line or .debug_line.dwo.  */
669   sect_offset line_offset;
670 };
671
672 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
673    an object of this type.  */
674
675 struct type_unit_group
676 {
677   /* dwarf2read.c's main "handle" on a TU symtab.
678      To simplify things we create an artificial CU that "includes" all the
679      type units using this stmt_list so that the rest of the code still has
680      a "per_cu" handle on the symtab.
681      This PER_CU is recognized by having no section.  */
682 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
683   struct dwarf2_per_cu_data per_cu;
684
685   /* The TUs that share this DW_AT_stmt_list entry.
686      This is added to while parsing type units to build partial symtabs,
687      and is deleted afterwards and not used again.  */
688   VEC (sig_type_ptr) *tus;
689
690   /* The primary symtab.
691      Type units in a group needn't all be defined in the same source file,
692      so we create an essentially anonymous symtab as the primary symtab.  */
693   struct symtab *primary_symtab;
694
695   /* The data used to construct the hash key.  */
696   struct stmt_list_hash hash;
697
698   /* The number of symtabs from the line header.
699      The value here must match line_header.num_file_names.  */
700   unsigned int num_symtabs;
701
702   /* The symbol tables for this TU (obtained from the files listed in
703      DW_AT_stmt_list).
704      WARNING: The order of entries here must match the order of entries
705      in the line header.  After the first TU using this type_unit_group, the
706      line header for the subsequent TUs is recreated from this.  This is done
707      because we need to use the same symtabs for each TU using the same
708      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
709      there's no guarantee the line header doesn't have duplicate entries.  */
710   struct symtab **symtabs;
711 };
712
713 /* These sections are what may appear in a DWO file.  */
714
715 struct dwo_sections
716 {
717   struct dwarf2_section_info abbrev;
718   struct dwarf2_section_info line;
719   struct dwarf2_section_info loc;
720   struct dwarf2_section_info macinfo;
721   struct dwarf2_section_info macro;
722   struct dwarf2_section_info str;
723   struct dwarf2_section_info str_offsets;
724   /* In the case of a virtual DWO file, these two are unused.  */
725   struct dwarf2_section_info info;
726   VEC (dwarf2_section_info_def) *types;
727 };
728
729 /* CUs/TUs in DWP/DWO files.  */
730
731 struct dwo_unit
732 {
733   /* Backlink to the containing struct dwo_file.  */
734   struct dwo_file *dwo_file;
735
736   /* The "id" that distinguishes this CU/TU.
737      .debug_info calls this "dwo_id", .debug_types calls this "signature".
738      Since signatures came first, we stick with it for consistency.  */
739   ULONGEST signature;
740
741   /* The section this CU/TU lives in, in the DWO file.  */
742   struct dwarf2_section_info *section;
743
744   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
745   sect_offset offset;
746   unsigned int length;
747
748   /* For types, offset in the type's DIE of the type defined by this TU.  */
749   cu_offset type_offset_in_tu;
750 };
751
752 /* Data for one DWO file.
753    This includes virtual DWO files that have been packaged into a
754    DWP file.  */
755
756 struct dwo_file
757 {
758   /* The DW_AT_GNU_dwo_name attribute.
759      For virtual DWO files the name is constructed from the section offsets
760      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
761      from related CU+TUs.  */
762   const char *dwo_name;
763
764   /* The DW_AT_comp_dir attribute.  */
765   const char *comp_dir;
766
767   /* The bfd, when the file is open.  Otherwise this is NULL.
768      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
769   bfd *dbfd;
770
771   /* Section info for this file.  */
772   struct dwo_sections sections;
773
774   /* The CU in the file.
775      We only support one because having more than one requires hacking the
776      dwo_name of each to match, which is highly unlikely to happen.
777      Doing this means all TUs can share comp_dir: We also assume that
778      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
779   struct dwo_unit *cu;
780
781   /* Table of TUs in the file.
782      Each element is a struct dwo_unit.  */
783   htab_t tus;
784 };
785
786 /* These sections are what may appear in a DWP file.  */
787
788 struct dwp_sections
789 {
790   struct dwarf2_section_info str;
791   struct dwarf2_section_info cu_index;
792   struct dwarf2_section_info tu_index;
793   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
794      by section number.  We don't need to record them here.  */
795 };
796
797 /* These sections are what may appear in a virtual DWO file.  */
798
799 struct virtual_dwo_sections
800 {
801   struct dwarf2_section_info abbrev;
802   struct dwarf2_section_info line;
803   struct dwarf2_section_info loc;
804   struct dwarf2_section_info macinfo;
805   struct dwarf2_section_info macro;
806   struct dwarf2_section_info str_offsets;
807   /* Each DWP hash table entry records one CU or one TU.
808      That is recorded here, and copied to dwo_unit.section.  */
809   struct dwarf2_section_info info_or_types;
810 };
811
812 /* Contents of DWP hash tables.  */
813
814 struct dwp_hash_table
815 {
816   uint32_t nr_units, nr_slots;
817   const gdb_byte *hash_table, *unit_table, *section_pool;
818 };
819
820 /* Data for one DWP file.  */
821
822 struct dwp_file
823 {
824   /* Name of the file.  */
825   const char *name;
826
827   /* The bfd.  */
828   bfd *dbfd;
829
830   /* Section info for this file.  */
831   struct dwp_sections sections;
832
833   /* Table of CUs in the file. */
834   const struct dwp_hash_table *cus;
835
836   /* Table of TUs in the file.  */
837   const struct dwp_hash_table *tus;
838
839   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
840   htab_t loaded_cutus;
841
842   /* Table to map ELF section numbers to their sections.  */
843   unsigned int num_sections;
844   asection **elf_sections;
845 };
846
847 /* This represents a '.dwz' file.  */
848
849 struct dwz_file
850 {
851   /* A dwz file can only contain a few sections.  */
852   struct dwarf2_section_info abbrev;
853   struct dwarf2_section_info info;
854   struct dwarf2_section_info str;
855   struct dwarf2_section_info line;
856   struct dwarf2_section_info macro;
857   struct dwarf2_section_info gdb_index;
858
859   /* The dwz's BFD.  */
860   bfd *dwz_bfd;
861 };
862
863 /* Struct used to pass misc. parameters to read_die_and_children, et
864    al.  which are used for both .debug_info and .debug_types dies.
865    All parameters here are unchanging for the life of the call.  This
866    struct exists to abstract away the constant parameters of die reading.  */
867
868 struct die_reader_specs
869 {
870   /* die_section->asection->owner.  */
871   bfd* abfd;
872
873   /* The CU of the DIE we are parsing.  */
874   struct dwarf2_cu *cu;
875
876   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
877   struct dwo_file *dwo_file;
878
879   /* The section the die comes from.
880      This is either .debug_info or .debug_types, or the .dwo variants.  */
881   struct dwarf2_section_info *die_section;
882
883   /* die_section->buffer.  */
884   const gdb_byte *buffer;
885
886   /* The end of the buffer.  */
887   const gdb_byte *buffer_end;
888
889   /* The value of the DW_AT_comp_dir attribute.  */
890   const char *comp_dir;
891 };
892
893 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
894 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
895                                       const gdb_byte *info_ptr,
896                                       struct die_info *comp_unit_die,
897                                       int has_children,
898                                       void *data);
899
900 /* The line number information for a compilation unit (found in the
901    .debug_line section) begins with a "statement program header",
902    which contains the following information.  */
903 struct line_header
904 {
905   unsigned int total_length;
906   unsigned short version;
907   unsigned int header_length;
908   unsigned char minimum_instruction_length;
909   unsigned char maximum_ops_per_instruction;
910   unsigned char default_is_stmt;
911   int line_base;
912   unsigned char line_range;
913   unsigned char opcode_base;
914
915   /* standard_opcode_lengths[i] is the number of operands for the
916      standard opcode whose value is i.  This means that
917      standard_opcode_lengths[0] is unused, and the last meaningful
918      element is standard_opcode_lengths[opcode_base - 1].  */
919   unsigned char *standard_opcode_lengths;
920
921   /* The include_directories table.  NOTE!  These strings are not
922      allocated with xmalloc; instead, they are pointers into
923      debug_line_buffer.  If you try to free them, `free' will get
924      indigestion.  */
925   unsigned int num_include_dirs, include_dirs_size;
926   const char **include_dirs;
927
928   /* The file_names table.  NOTE!  These strings are not allocated
929      with xmalloc; instead, they are pointers into debug_line_buffer.
930      Don't try to free them directly.  */
931   unsigned int num_file_names, file_names_size;
932   struct file_entry
933   {
934     const char *name;
935     unsigned int dir_index;
936     unsigned int mod_time;
937     unsigned int length;
938     int included_p; /* Non-zero if referenced by the Line Number Program.  */
939     struct symtab *symtab; /* The associated symbol table, if any.  */
940   } *file_names;
941
942   /* The start and end of the statement program following this
943      header.  These point into dwarf2_per_objfile->line_buffer.  */
944   const gdb_byte *statement_program_start, *statement_program_end;
945 };
946
947 /* When we construct a partial symbol table entry we only
948    need this much information.  */
949 struct partial_die_info
950   {
951     /* Offset of this DIE.  */
952     sect_offset offset;
953
954     /* DWARF-2 tag for this DIE.  */
955     ENUM_BITFIELD(dwarf_tag) tag : 16;
956
957     /* Assorted flags describing the data found in this DIE.  */
958     unsigned int has_children : 1;
959     unsigned int is_external : 1;
960     unsigned int is_declaration : 1;
961     unsigned int has_type : 1;
962     unsigned int has_specification : 1;
963     unsigned int has_pc_info : 1;
964     unsigned int may_be_inlined : 1;
965
966     /* Flag set if the SCOPE field of this structure has been
967        computed.  */
968     unsigned int scope_set : 1;
969
970     /* Flag set if the DIE has a byte_size attribute.  */
971     unsigned int has_byte_size : 1;
972
973     /* Flag set if any of the DIE's children are template arguments.  */
974     unsigned int has_template_arguments : 1;
975
976     /* Flag set if fixup_partial_die has been called on this die.  */
977     unsigned int fixup_called : 1;
978
979     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
980     unsigned int is_dwz : 1;
981
982     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
983     unsigned int spec_is_dwz : 1;
984
985     /* The name of this DIE.  Normally the value of DW_AT_name, but
986        sometimes a default name for unnamed DIEs.  */
987     const char *name;
988
989     /* The linkage name, if present.  */
990     const char *linkage_name;
991
992     /* The scope to prepend to our children.  This is generally
993        allocated on the comp_unit_obstack, so will disappear
994        when this compilation unit leaves the cache.  */
995     const char *scope;
996
997     /* Some data associated with the partial DIE.  The tag determines
998        which field is live.  */
999     union
1000     {
1001       /* The location description associated with this DIE, if any.  */
1002       struct dwarf_block *locdesc;
1003       /* The offset of an import, for DW_TAG_imported_unit.  */
1004       sect_offset offset;
1005     } d;
1006
1007     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1008     CORE_ADDR lowpc;
1009     CORE_ADDR highpc;
1010
1011     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1012        DW_AT_sibling, if any.  */
1013     /* NOTE: This member isn't strictly necessary, read_partial_die could
1014        return DW_AT_sibling values to its caller load_partial_dies.  */
1015     const gdb_byte *sibling;
1016
1017     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1018        DW_AT_specification (or DW_AT_abstract_origin or
1019        DW_AT_extension).  */
1020     sect_offset spec_offset;
1021
1022     /* Pointers to this DIE's parent, first child, and next sibling,
1023        if any.  */
1024     struct partial_die_info *die_parent, *die_child, *die_sibling;
1025   };
1026
1027 /* This data structure holds the information of an abbrev.  */
1028 struct abbrev_info
1029   {
1030     unsigned int number;        /* number identifying abbrev */
1031     enum dwarf_tag tag;         /* dwarf tag */
1032     unsigned short has_children;                /* boolean */
1033     unsigned short num_attrs;   /* number of attributes */
1034     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1035     struct abbrev_info *next;   /* next in chain */
1036   };
1037
1038 struct attr_abbrev
1039   {
1040     ENUM_BITFIELD(dwarf_attribute) name : 16;
1041     ENUM_BITFIELD(dwarf_form) form : 16;
1042   };
1043
1044 /* Size of abbrev_table.abbrev_hash_table.  */
1045 #define ABBREV_HASH_SIZE 121
1046
1047 /* Top level data structure to contain an abbreviation table.  */
1048
1049 struct abbrev_table
1050 {
1051   /* Where the abbrev table came from.
1052      This is used as a sanity check when the table is used.  */
1053   sect_offset offset;
1054
1055   /* Storage for the abbrev table.  */
1056   struct obstack abbrev_obstack;
1057
1058   /* Hash table of abbrevs.
1059      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1060      It could be statically allocated, but the previous code didn't so we
1061      don't either.  */
1062   struct abbrev_info **abbrevs;
1063 };
1064
1065 /* Attributes have a name and a value.  */
1066 struct attribute
1067   {
1068     ENUM_BITFIELD(dwarf_attribute) name : 16;
1069     ENUM_BITFIELD(dwarf_form) form : 15;
1070
1071     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1072        field should be in u.str (existing only for DW_STRING) but it is kept
1073        here for better struct attribute alignment.  */
1074     unsigned int string_is_canonical : 1;
1075
1076     union
1077       {
1078         const char *str;
1079         struct dwarf_block *blk;
1080         ULONGEST unsnd;
1081         LONGEST snd;
1082         CORE_ADDR addr;
1083         ULONGEST signature;
1084       }
1085     u;
1086   };
1087
1088 /* This data structure holds a complete die structure.  */
1089 struct die_info
1090   {
1091     /* DWARF-2 tag for this DIE.  */
1092     ENUM_BITFIELD(dwarf_tag) tag : 16;
1093
1094     /* Number of attributes */
1095     unsigned char num_attrs;
1096
1097     /* True if we're presently building the full type name for the
1098        type derived from this DIE.  */
1099     unsigned char building_fullname : 1;
1100
1101     /* Abbrev number */
1102     unsigned int abbrev;
1103
1104     /* Offset in .debug_info or .debug_types section.  */
1105     sect_offset offset;
1106
1107     /* The dies in a compilation unit form an n-ary tree.  PARENT
1108        points to this die's parent; CHILD points to the first child of
1109        this node; and all the children of a given node are chained
1110        together via their SIBLING fields.  */
1111     struct die_info *child;     /* Its first child, if any.  */
1112     struct die_info *sibling;   /* Its next sibling, if any.  */
1113     struct die_info *parent;    /* Its parent, if any.  */
1114
1115     /* An array of attributes, with NUM_ATTRS elements.  There may be
1116        zero, but it's not common and zero-sized arrays are not
1117        sufficiently portable C.  */
1118     struct attribute attrs[1];
1119   };
1120
1121 /* Get at parts of an attribute structure.  */
1122
1123 #define DW_STRING(attr)    ((attr)->u.str)
1124 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1125 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1126 #define DW_BLOCK(attr)     ((attr)->u.blk)
1127 #define DW_SND(attr)       ((attr)->u.snd)
1128 #define DW_ADDR(attr)      ((attr)->u.addr)
1129 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1130
1131 /* Blocks are a bunch of untyped bytes.  */
1132 struct dwarf_block
1133   {
1134     size_t size;
1135
1136     /* Valid only if SIZE is not zero.  */
1137     const gdb_byte *data;
1138   };
1139
1140 #ifndef ATTR_ALLOC_CHUNK
1141 #define ATTR_ALLOC_CHUNK 4
1142 #endif
1143
1144 /* Allocate fields for structs, unions and enums in this size.  */
1145 #ifndef DW_FIELD_ALLOC_CHUNK
1146 #define DW_FIELD_ALLOC_CHUNK 4
1147 #endif
1148
1149 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1150    but this would require a corresponding change in unpack_field_as_long
1151    and friends.  */
1152 static int bits_per_byte = 8;
1153
1154 /* The routines that read and process dies for a C struct or C++ class
1155    pass lists of data member fields and lists of member function fields
1156    in an instance of a field_info structure, as defined below.  */
1157 struct field_info
1158   {
1159     /* List of data member and baseclasses fields.  */
1160     struct nextfield
1161       {
1162         struct nextfield *next;
1163         int accessibility;
1164         int virtuality;
1165         struct field field;
1166       }
1167      *fields, *baseclasses;
1168
1169     /* Number of fields (including baseclasses).  */
1170     int nfields;
1171
1172     /* Number of baseclasses.  */
1173     int nbaseclasses;
1174
1175     /* Set if the accesibility of one of the fields is not public.  */
1176     int non_public_fields;
1177
1178     /* Member function fields array, entries are allocated in the order they
1179        are encountered in the object file.  */
1180     struct nextfnfield
1181       {
1182         struct nextfnfield *next;
1183         struct fn_field fnfield;
1184       }
1185      *fnfields;
1186
1187     /* Member function fieldlist array, contains name of possibly overloaded
1188        member function, number of overloaded member functions and a pointer
1189        to the head of the member function field chain.  */
1190     struct fnfieldlist
1191       {
1192         const char *name;
1193         int length;
1194         struct nextfnfield *head;
1195       }
1196      *fnfieldlists;
1197
1198     /* Number of entries in the fnfieldlists array.  */
1199     int nfnfields;
1200
1201     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1202        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1203     struct typedef_field_list
1204       {
1205         struct typedef_field field;
1206         struct typedef_field_list *next;
1207       }
1208     *typedef_field_list;
1209     unsigned typedef_field_list_count;
1210   };
1211
1212 /* One item on the queue of compilation units to read in full symbols
1213    for.  */
1214 struct dwarf2_queue_item
1215 {
1216   struct dwarf2_per_cu_data *per_cu;
1217   enum language pretend_language;
1218   struct dwarf2_queue_item *next;
1219 };
1220
1221 /* The current queue.  */
1222 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1223
1224 /* Loaded secondary compilation units are kept in memory until they
1225    have not been referenced for the processing of this many
1226    compilation units.  Set this to zero to disable caching.  Cache
1227    sizes of up to at least twenty will improve startup time for
1228    typical inter-CU-reference binaries, at an obvious memory cost.  */
1229 static int dwarf2_max_cache_age = 5;
1230 static void
1231 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1232                            struct cmd_list_element *c, const char *value)
1233 {
1234   fprintf_filtered (file, _("The upper bound on the age of cached "
1235                             "dwarf2 compilation units is %s.\n"),
1236                     value);
1237 }
1238
1239
1240 /* Various complaints about symbol reading that don't abort the process.  */
1241
1242 static void
1243 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1244 {
1245   complaint (&symfile_complaints,
1246              _("statement list doesn't fit in .debug_line section"));
1247 }
1248
1249 static void
1250 dwarf2_debug_line_missing_file_complaint (void)
1251 {
1252   complaint (&symfile_complaints,
1253              _(".debug_line section has line data without a file"));
1254 }
1255
1256 static void
1257 dwarf2_debug_line_missing_end_sequence_complaint (void)
1258 {
1259   complaint (&symfile_complaints,
1260              _(".debug_line section has line "
1261                "program sequence without an end"));
1262 }
1263
1264 static void
1265 dwarf2_complex_location_expr_complaint (void)
1266 {
1267   complaint (&symfile_complaints, _("location expression too complex"));
1268 }
1269
1270 static void
1271 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1272                                               int arg3)
1273 {
1274   complaint (&symfile_complaints,
1275              _("const value length mismatch for '%s', got %d, expected %d"),
1276              arg1, arg2, arg3);
1277 }
1278
1279 static void
1280 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1281 {
1282   complaint (&symfile_complaints,
1283              _("debug info runs off end of %s section"
1284                " [in module %s]"),
1285              section->asection->name,
1286              bfd_get_filename (section->asection->owner));
1287 }
1288
1289 static void
1290 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1291 {
1292   complaint (&symfile_complaints,
1293              _("macro debug info contains a "
1294                "malformed macro definition:\n`%s'"),
1295              arg1);
1296 }
1297
1298 static void
1299 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1300 {
1301   complaint (&symfile_complaints,
1302              _("invalid attribute class or form for '%s' in '%s'"),
1303              arg1, arg2);
1304 }
1305
1306 /* local function prototypes */
1307
1308 static void dwarf2_locate_sections (bfd *, asection *, void *);
1309
1310 static void dwarf2_find_base_address (struct die_info *die,
1311                                       struct dwarf2_cu *cu);
1312
1313 static struct partial_symtab *create_partial_symtab
1314   (struct dwarf2_per_cu_data *per_cu, const char *name);
1315
1316 static void dwarf2_build_psymtabs_hard (struct objfile *);
1317
1318 static void scan_partial_symbols (struct partial_die_info *,
1319                                   CORE_ADDR *, CORE_ADDR *,
1320                                   int, struct dwarf2_cu *);
1321
1322 static void add_partial_symbol (struct partial_die_info *,
1323                                 struct dwarf2_cu *);
1324
1325 static void add_partial_namespace (struct partial_die_info *pdi,
1326                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1327                                    int need_pc, struct dwarf2_cu *cu);
1328
1329 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1330                                 CORE_ADDR *highpc, int need_pc,
1331                                 struct dwarf2_cu *cu);
1332
1333 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1334                                      struct dwarf2_cu *cu);
1335
1336 static void add_partial_subprogram (struct partial_die_info *pdi,
1337                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1338                                     int need_pc, struct dwarf2_cu *cu);
1339
1340 static void dwarf2_read_symtab (struct partial_symtab *,
1341                                 struct objfile *);
1342
1343 static void psymtab_to_symtab_1 (struct partial_symtab *);
1344
1345 static struct abbrev_info *abbrev_table_lookup_abbrev
1346   (const struct abbrev_table *, unsigned int);
1347
1348 static struct abbrev_table *abbrev_table_read_table
1349   (struct dwarf2_section_info *, sect_offset);
1350
1351 static void abbrev_table_free (struct abbrev_table *);
1352
1353 static void abbrev_table_free_cleanup (void *);
1354
1355 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1356                                  struct dwarf2_section_info *);
1357
1358 static void dwarf2_free_abbrev_table (void *);
1359
1360 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1361
1362 static struct partial_die_info *load_partial_dies
1363   (const struct die_reader_specs *, const gdb_byte *, int);
1364
1365 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1366                                          struct partial_die_info *,
1367                                          struct abbrev_info *,
1368                                          unsigned int,
1369                                          const gdb_byte *);
1370
1371 static struct partial_die_info *find_partial_die (sect_offset, int,
1372                                                   struct dwarf2_cu *);
1373
1374 static void fixup_partial_die (struct partial_die_info *,
1375                                struct dwarf2_cu *);
1376
1377 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1378                                        struct attribute *, struct attr_abbrev *,
1379                                        const gdb_byte *);
1380
1381 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1382
1383 static int read_1_signed_byte (bfd *, const gdb_byte *);
1384
1385 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1386
1387 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1388
1389 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1390
1391 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1392                                unsigned int *);
1393
1394 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1395
1396 static LONGEST read_checked_initial_length_and_offset
1397   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1398    unsigned int *, unsigned int *);
1399
1400 static LONGEST read_offset (bfd *, const gdb_byte *,
1401                             const struct comp_unit_head *,
1402                             unsigned int *);
1403
1404 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1405
1406 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1407                                        sect_offset);
1408
1409 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1410
1411 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1412
1413 static const char *read_indirect_string (bfd *, const gdb_byte *,
1414                                          const struct comp_unit_head *,
1415                                          unsigned int *);
1416
1417 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1418
1419 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1420
1421 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1422
1423 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1424                                               const gdb_byte *,
1425                                               unsigned int *);
1426
1427 static const char *read_str_index (const struct die_reader_specs *reader,
1428                                    struct dwarf2_cu *cu, ULONGEST str_index);
1429
1430 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1431
1432 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1433                                       struct dwarf2_cu *);
1434
1435 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1436                                                 unsigned int);
1437
1438 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1439                                struct dwarf2_cu *cu);
1440
1441 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1442
1443 static struct die_info *die_specification (struct die_info *die,
1444                                            struct dwarf2_cu **);
1445
1446 static void free_line_header (struct line_header *lh);
1447
1448 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1449                                                      struct dwarf2_cu *cu);
1450
1451 static void dwarf_decode_lines (struct line_header *, const char *,
1452                                 struct dwarf2_cu *, struct partial_symtab *,
1453                                 int);
1454
1455 static void dwarf2_start_subfile (const char *, const char *, const char *);
1456
1457 static void dwarf2_start_symtab (struct dwarf2_cu *,
1458                                  const char *, const char *, CORE_ADDR);
1459
1460 static struct symbol *new_symbol (struct die_info *, struct type *,
1461                                   struct dwarf2_cu *);
1462
1463 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1464                                        struct dwarf2_cu *, struct symbol *);
1465
1466 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1467                                 struct dwarf2_cu *);
1468
1469 static void dwarf2_const_value_attr (const struct attribute *attr,
1470                                      struct type *type,
1471                                      const char *name,
1472                                      struct obstack *obstack,
1473                                      struct dwarf2_cu *cu, LONGEST *value,
1474                                      const gdb_byte **bytes,
1475                                      struct dwarf2_locexpr_baton **baton);
1476
1477 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1478
1479 static int need_gnat_info (struct dwarf2_cu *);
1480
1481 static struct type *die_descriptive_type (struct die_info *,
1482                                           struct dwarf2_cu *);
1483
1484 static void set_descriptive_type (struct type *, struct die_info *,
1485                                   struct dwarf2_cu *);
1486
1487 static struct type *die_containing_type (struct die_info *,
1488                                          struct dwarf2_cu *);
1489
1490 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1491                                      struct dwarf2_cu *);
1492
1493 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1494
1495 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1496
1497 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1498
1499 static char *typename_concat (struct obstack *obs, const char *prefix,
1500                               const char *suffix, int physname,
1501                               struct dwarf2_cu *cu);
1502
1503 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1504
1505 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1506
1507 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1508
1509 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1510
1511 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1512
1513 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1514                                struct dwarf2_cu *, struct partial_symtab *);
1515
1516 static int dwarf2_get_pc_bounds (struct die_info *,
1517                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1518                                  struct partial_symtab *);
1519
1520 static void get_scope_pc_bounds (struct die_info *,
1521                                  CORE_ADDR *, CORE_ADDR *,
1522                                  struct dwarf2_cu *);
1523
1524 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1525                                         CORE_ADDR, struct dwarf2_cu *);
1526
1527 static void dwarf2_add_field (struct field_info *, struct die_info *,
1528                               struct dwarf2_cu *);
1529
1530 static void dwarf2_attach_fields_to_type (struct field_info *,
1531                                           struct type *, struct dwarf2_cu *);
1532
1533 static void dwarf2_add_member_fn (struct field_info *,
1534                                   struct die_info *, struct type *,
1535                                   struct dwarf2_cu *);
1536
1537 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1538                                              struct type *,
1539                                              struct dwarf2_cu *);
1540
1541 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1542
1543 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1544
1545 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1546
1547 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1548
1549 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1550
1551 static struct type *read_module_type (struct die_info *die,
1552                                       struct dwarf2_cu *cu);
1553
1554 static const char *namespace_name (struct die_info *die,
1555                                    int *is_anonymous, struct dwarf2_cu *);
1556
1557 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1558
1559 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1560
1561 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1562                                                        struct dwarf2_cu *);
1563
1564 static struct die_info *read_die_and_siblings_1
1565   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1566    struct die_info *);
1567
1568 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1569                                                const gdb_byte *info_ptr,
1570                                                const gdb_byte **new_info_ptr,
1571                                                struct die_info *parent);
1572
1573 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1574                                         struct die_info **, const gdb_byte *,
1575                                         int *, int);
1576
1577 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1578                                       struct die_info **, const gdb_byte *,
1579                                       int *);
1580
1581 static void process_die (struct die_info *, struct dwarf2_cu *);
1582
1583 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1584                                              struct obstack *);
1585
1586 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1587
1588 static const char *dwarf2_full_name (const char *name,
1589                                      struct die_info *die,
1590                                      struct dwarf2_cu *cu);
1591
1592 static const char *dwarf2_physname (const char *name, struct die_info *die,
1593                                     struct dwarf2_cu *cu);
1594
1595 static struct die_info *dwarf2_extension (struct die_info *die,
1596                                           struct dwarf2_cu **);
1597
1598 static const char *dwarf_tag_name (unsigned int);
1599
1600 static const char *dwarf_attr_name (unsigned int);
1601
1602 static const char *dwarf_form_name (unsigned int);
1603
1604 static char *dwarf_bool_name (unsigned int);
1605
1606 static const char *dwarf_type_encoding_name (unsigned int);
1607
1608 static struct die_info *sibling_die (struct die_info *);
1609
1610 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1611
1612 static void dump_die_for_error (struct die_info *);
1613
1614 static void dump_die_1 (struct ui_file *, int level, int max_level,
1615                         struct die_info *);
1616
1617 /*static*/ void dump_die (struct die_info *, int max_level);
1618
1619 static void store_in_ref_table (struct die_info *,
1620                                 struct dwarf2_cu *);
1621
1622 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1623
1624 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1625
1626 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1627                                                const struct attribute *,
1628                                                struct dwarf2_cu **);
1629
1630 static struct die_info *follow_die_ref (struct die_info *,
1631                                         const struct attribute *,
1632                                         struct dwarf2_cu **);
1633
1634 static struct die_info *follow_die_sig (struct die_info *,
1635                                         const struct attribute *,
1636                                         struct dwarf2_cu **);
1637
1638 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1639                                          struct dwarf2_cu *);
1640
1641 static struct type *get_DW_AT_signature_type (struct die_info *,
1642                                               const struct attribute *,
1643                                               struct dwarf2_cu *);
1644
1645 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1646
1647 static void read_signatured_type (struct signatured_type *);
1648
1649 static struct type_unit_group *get_type_unit_group
1650     (struct dwarf2_cu *, const struct attribute *);
1651
1652 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1653
1654 /* memory allocation interface */
1655
1656 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1657
1658 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1659
1660 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1661                                  const char *, int);
1662
1663 static int attr_form_is_block (const struct attribute *);
1664
1665 static int attr_form_is_section_offset (const struct attribute *);
1666
1667 static int attr_form_is_constant (const struct attribute *);
1668
1669 static int attr_form_is_ref (const struct attribute *);
1670
1671 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1672                                    struct dwarf2_loclist_baton *baton,
1673                                    const struct attribute *attr);
1674
1675 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1676                                          struct symbol *sym,
1677                                          struct dwarf2_cu *cu,
1678                                          int is_block);
1679
1680 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1681                                      const gdb_byte *info_ptr,
1682                                      struct abbrev_info *abbrev);
1683
1684 static void free_stack_comp_unit (void *);
1685
1686 static hashval_t partial_die_hash (const void *item);
1687
1688 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1689
1690 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1691   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1692
1693 static void init_one_comp_unit (struct dwarf2_cu *cu,
1694                                 struct dwarf2_per_cu_data *per_cu);
1695
1696 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1697                                    struct die_info *comp_unit_die,
1698                                    enum language pretend_language);
1699
1700 static void free_heap_comp_unit (void *);
1701
1702 static void free_cached_comp_units (void *);
1703
1704 static void age_cached_comp_units (void);
1705
1706 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1707
1708 static struct type *set_die_type (struct die_info *, struct type *,
1709                                   struct dwarf2_cu *);
1710
1711 static void create_all_comp_units (struct objfile *);
1712
1713 static int create_all_type_units (struct objfile *);
1714
1715 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1716                                  enum language);
1717
1718 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1719                                     enum language);
1720
1721 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1722                                     enum language);
1723
1724 static void dwarf2_add_dependence (struct dwarf2_cu *,
1725                                    struct dwarf2_per_cu_data *);
1726
1727 static void dwarf2_mark (struct dwarf2_cu *);
1728
1729 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1730
1731 static struct type *get_die_type_at_offset (sect_offset,
1732                                             struct dwarf2_per_cu_data *);
1733
1734 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1735
1736 static void dwarf2_release_queue (void *dummy);
1737
1738 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1739                              enum language pretend_language);
1740
1741 static void process_queue (void);
1742
1743 static void find_file_and_directory (struct die_info *die,
1744                                      struct dwarf2_cu *cu,
1745                                      const char **name, const char **comp_dir);
1746
1747 static char *file_full_name (int file, struct line_header *lh,
1748                              const char *comp_dir);
1749
1750 static const gdb_byte *read_and_check_comp_unit_head
1751   (struct comp_unit_head *header,
1752    struct dwarf2_section_info *section,
1753    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1754    int is_debug_types_section);
1755
1756 static void init_cutu_and_read_dies
1757   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1758    int use_existing_cu, int keep,
1759    die_reader_func_ftype *die_reader_func, void *data);
1760
1761 static void init_cutu_and_read_dies_simple
1762   (struct dwarf2_per_cu_data *this_cu,
1763    die_reader_func_ftype *die_reader_func, void *data);
1764
1765 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1766
1767 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1768
1769 static struct dwo_unit *lookup_dwo_in_dwp
1770   (struct dwp_file *dwp_file, const struct dwp_hash_table *htab,
1771    const char *comp_dir, ULONGEST signature, int is_debug_types);
1772
1773 static struct dwp_file *get_dwp_file (void);
1774
1775 static struct dwo_unit *lookup_dwo_comp_unit
1776   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1777
1778 static struct dwo_unit *lookup_dwo_type_unit
1779   (struct signatured_type *, const char *, const char *);
1780
1781 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1782
1783 static void free_dwo_file_cleanup (void *);
1784
1785 static void process_cu_includes (void);
1786
1787 static void check_producer (struct dwarf2_cu *cu);
1788
1789 #if WORDS_BIGENDIAN
1790
1791 /* Convert VALUE between big- and little-endian.  */
1792 static offset_type
1793 byte_swap (offset_type value)
1794 {
1795   offset_type result;
1796
1797   result = (value & 0xff) << 24;
1798   result |= (value & 0xff00) << 8;
1799   result |= (value & 0xff0000) >> 8;
1800   result |= (value & 0xff000000) >> 24;
1801   return result;
1802 }
1803
1804 #define MAYBE_SWAP(V)  byte_swap (V)
1805
1806 #else
1807 #define MAYBE_SWAP(V) (V)
1808 #endif /* WORDS_BIGENDIAN */
1809
1810 /* The suffix for an index file.  */
1811 #define INDEX_SUFFIX ".gdb-index"
1812
1813 /* Try to locate the sections we need for DWARF 2 debugging
1814    information and return true if we have enough to do something.
1815    NAMES points to the dwarf2 section names, or is NULL if the standard
1816    ELF names are used.  */
1817
1818 int
1819 dwarf2_has_info (struct objfile *objfile,
1820                  const struct dwarf2_debug_sections *names)
1821 {
1822   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1823   if (!dwarf2_per_objfile)
1824     {
1825       /* Initialize per-objfile state.  */
1826       struct dwarf2_per_objfile *data
1827         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1828
1829       memset (data, 0, sizeof (*data));
1830       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1831       dwarf2_per_objfile = data;
1832
1833       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1834                              (void *) names);
1835       dwarf2_per_objfile->objfile = objfile;
1836     }
1837   return (dwarf2_per_objfile->info.asection != NULL
1838           && dwarf2_per_objfile->abbrev.asection != NULL);
1839 }
1840
1841 /* When loading sections, we look either for uncompressed section or for
1842    compressed section names.  */
1843
1844 static int
1845 section_is_p (const char *section_name,
1846               const struct dwarf2_section_names *names)
1847 {
1848   if (names->normal != NULL
1849       && strcmp (section_name, names->normal) == 0)
1850     return 1;
1851   if (names->compressed != NULL
1852       && strcmp (section_name, names->compressed) == 0)
1853     return 1;
1854   return 0;
1855 }
1856
1857 /* This function is mapped across the sections and remembers the
1858    offset and size of each of the debugging sections we are interested
1859    in.  */
1860
1861 static void
1862 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1863 {
1864   const struct dwarf2_debug_sections *names;
1865   flagword aflag = bfd_get_section_flags (abfd, sectp);
1866
1867   if (vnames == NULL)
1868     names = &dwarf2_elf_names;
1869   else
1870     names = (const struct dwarf2_debug_sections *) vnames;
1871
1872   if ((aflag & SEC_HAS_CONTENTS) == 0)
1873     {
1874     }
1875   else if (section_is_p (sectp->name, &names->info))
1876     {
1877       dwarf2_per_objfile->info.asection = sectp;
1878       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1879     }
1880   else if (section_is_p (sectp->name, &names->abbrev))
1881     {
1882       dwarf2_per_objfile->abbrev.asection = sectp;
1883       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1884     }
1885   else if (section_is_p (sectp->name, &names->line))
1886     {
1887       dwarf2_per_objfile->line.asection = sectp;
1888       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1889     }
1890   else if (section_is_p (sectp->name, &names->loc))
1891     {
1892       dwarf2_per_objfile->loc.asection = sectp;
1893       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1894     }
1895   else if (section_is_p (sectp->name, &names->macinfo))
1896     {
1897       dwarf2_per_objfile->macinfo.asection = sectp;
1898       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1899     }
1900   else if (section_is_p (sectp->name, &names->macro))
1901     {
1902       dwarf2_per_objfile->macro.asection = sectp;
1903       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1904     }
1905   else if (section_is_p (sectp->name, &names->str))
1906     {
1907       dwarf2_per_objfile->str.asection = sectp;
1908       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1909     }
1910   else if (section_is_p (sectp->name, &names->addr))
1911     {
1912       dwarf2_per_objfile->addr.asection = sectp;
1913       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1914     }
1915   else if (section_is_p (sectp->name, &names->frame))
1916     {
1917       dwarf2_per_objfile->frame.asection = sectp;
1918       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1919     }
1920   else if (section_is_p (sectp->name, &names->eh_frame))
1921     {
1922       dwarf2_per_objfile->eh_frame.asection = sectp;
1923       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1924     }
1925   else if (section_is_p (sectp->name, &names->ranges))
1926     {
1927       dwarf2_per_objfile->ranges.asection = sectp;
1928       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1929     }
1930   else if (section_is_p (sectp->name, &names->types))
1931     {
1932       struct dwarf2_section_info type_section;
1933
1934       memset (&type_section, 0, sizeof (type_section));
1935       type_section.asection = sectp;
1936       type_section.size = bfd_get_section_size (sectp);
1937
1938       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1939                      &type_section);
1940     }
1941   else if (section_is_p (sectp->name, &names->gdb_index))
1942     {
1943       dwarf2_per_objfile->gdb_index.asection = sectp;
1944       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1945     }
1946
1947   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1948       && bfd_section_vma (abfd, sectp) == 0)
1949     dwarf2_per_objfile->has_section_at_zero = 1;
1950 }
1951
1952 /* A helper function that decides whether a section is empty,
1953    or not present.  */
1954
1955 static int
1956 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1957 {
1958   return info->asection == NULL || info->size == 0;
1959 }
1960
1961 /* Read the contents of the section INFO.
1962    OBJFILE is the main object file, but not necessarily the file where
1963    the section comes from.  E.g., for DWO files INFO->asection->owner
1964    is the bfd of the DWO file.
1965    If the section is compressed, uncompress it before returning.  */
1966
1967 static void
1968 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1969 {
1970   asection *sectp = info->asection;
1971   bfd *abfd;
1972   gdb_byte *buf, *retbuf;
1973   unsigned char header[4];
1974
1975   if (info->readin)
1976     return;
1977   info->buffer = NULL;
1978   info->readin = 1;
1979
1980   if (dwarf2_section_empty_p (info))
1981     return;
1982
1983   abfd = sectp->owner;
1984
1985   /* If the section has relocations, we must read it ourselves.
1986      Otherwise we attach it to the BFD.  */
1987   if ((sectp->flags & SEC_RELOC) == 0)
1988     {
1989       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1990       return;
1991     }
1992
1993   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1994   info->buffer = buf;
1995
1996   /* When debugging .o files, we may need to apply relocations; see
1997      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1998      We never compress sections in .o files, so we only need to
1999      try this when the section is not compressed.  */
2000   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2001   if (retbuf != NULL)
2002     {
2003       info->buffer = retbuf;
2004       return;
2005     }
2006
2007   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2008       || bfd_bread (buf, info->size, abfd) != info->size)
2009     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
2010            bfd_get_filename (abfd));
2011 }
2012
2013 /* A helper function that returns the size of a section in a safe way.
2014    If you are positive that the section has been read before using the
2015    size, then it is safe to refer to the dwarf2_section_info object's
2016    "size" field directly.  In other cases, you must call this
2017    function, because for compressed sections the size field is not set
2018    correctly until the section has been read.  */
2019
2020 static bfd_size_type
2021 dwarf2_section_size (struct objfile *objfile,
2022                      struct dwarf2_section_info *info)
2023 {
2024   if (!info->readin)
2025     dwarf2_read_section (objfile, info);
2026   return info->size;
2027 }
2028
2029 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2030    SECTION_NAME.  */
2031
2032 void
2033 dwarf2_get_section_info (struct objfile *objfile,
2034                          enum dwarf2_section_enum sect,
2035                          asection **sectp, const gdb_byte **bufp,
2036                          bfd_size_type *sizep)
2037 {
2038   struct dwarf2_per_objfile *data
2039     = objfile_data (objfile, dwarf2_objfile_data_key);
2040   struct dwarf2_section_info *info;
2041
2042   /* We may see an objfile without any DWARF, in which case we just
2043      return nothing.  */
2044   if (data == NULL)
2045     {
2046       *sectp = NULL;
2047       *bufp = NULL;
2048       *sizep = 0;
2049       return;
2050     }
2051   switch (sect)
2052     {
2053     case DWARF2_DEBUG_FRAME:
2054       info = &data->frame;
2055       break;
2056     case DWARF2_EH_FRAME:
2057       info = &data->eh_frame;
2058       break;
2059     default:
2060       gdb_assert_not_reached ("unexpected section");
2061     }
2062
2063   dwarf2_read_section (objfile, info);
2064
2065   *sectp = info->asection;
2066   *bufp = info->buffer;
2067   *sizep = info->size;
2068 }
2069
2070 /* A helper function to find the sections for a .dwz file.  */
2071
2072 static void
2073 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2074 {
2075   struct dwz_file *dwz_file = arg;
2076
2077   /* Note that we only support the standard ELF names, because .dwz
2078      is ELF-only (at the time of writing).  */
2079   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2080     {
2081       dwz_file->abbrev.asection = sectp;
2082       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2083     }
2084   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2085     {
2086       dwz_file->info.asection = sectp;
2087       dwz_file->info.size = bfd_get_section_size (sectp);
2088     }
2089   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2090     {
2091       dwz_file->str.asection = sectp;
2092       dwz_file->str.size = bfd_get_section_size (sectp);
2093     }
2094   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2095     {
2096       dwz_file->line.asection = sectp;
2097       dwz_file->line.size = bfd_get_section_size (sectp);
2098     }
2099   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2100     {
2101       dwz_file->macro.asection = sectp;
2102       dwz_file->macro.size = bfd_get_section_size (sectp);
2103     }
2104   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2105     {
2106       dwz_file->gdb_index.asection = sectp;
2107       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2108     }
2109 }
2110
2111 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2112    there is no .gnu_debugaltlink section in the file.  Error if there
2113    is such a section but the file cannot be found.  */
2114
2115 static struct dwz_file *
2116 dwarf2_get_dwz_file (void)
2117 {
2118   bfd *dwz_bfd;
2119   char *data;
2120   struct cleanup *cleanup;
2121   const char *filename;
2122   struct dwz_file *result;
2123   unsigned long buildid;
2124
2125   if (dwarf2_per_objfile->dwz_file != NULL)
2126     return dwarf2_per_objfile->dwz_file;
2127
2128   bfd_set_error (bfd_error_no_error);
2129   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2130                                       &buildid);
2131   if (data == NULL)
2132     {
2133       if (bfd_get_error () == bfd_error_no_error)
2134         return NULL;
2135       error (_("could not read '.gnu_debugaltlink' section: %s"),
2136              bfd_errmsg (bfd_get_error ()));
2137     }
2138   cleanup = make_cleanup (xfree, data);
2139
2140   filename = (const char *) data;
2141   if (!IS_ABSOLUTE_PATH (filename))
2142     {
2143       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2144       char *rel;
2145
2146       make_cleanup (xfree, abs);
2147       abs = ldirname (abs);
2148       make_cleanup (xfree, abs);
2149
2150       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2151       make_cleanup (xfree, rel);
2152       filename = rel;
2153     }
2154
2155   /* The format is just a NUL-terminated file name, followed by the
2156      build-id.  For now, though, we ignore the build-id.  */
2157   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2158   if (dwz_bfd == NULL)
2159     error (_("could not read '%s': %s"), filename,
2160            bfd_errmsg (bfd_get_error ()));
2161
2162   if (!bfd_check_format (dwz_bfd, bfd_object))
2163     {
2164       gdb_bfd_unref (dwz_bfd);
2165       error (_("file '%s' was not usable: %s"), filename,
2166              bfd_errmsg (bfd_get_error ()));
2167     }
2168
2169   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2170                            struct dwz_file);
2171   result->dwz_bfd = dwz_bfd;
2172
2173   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2174
2175   do_cleanups (cleanup);
2176
2177   dwarf2_per_objfile->dwz_file = result;
2178   return result;
2179 }
2180 \f
2181 /* DWARF quick_symbols_functions support.  */
2182
2183 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2184    unique line tables, so we maintain a separate table of all .debug_line
2185    derived entries to support the sharing.
2186    All the quick functions need is the list of file names.  We discard the
2187    line_header when we're done and don't need to record it here.  */
2188 struct quick_file_names
2189 {
2190   /* The data used to construct the hash key.  */
2191   struct stmt_list_hash hash;
2192
2193   /* The number of entries in file_names, real_names.  */
2194   unsigned int num_file_names;
2195
2196   /* The file names from the line table, after being run through
2197      file_full_name.  */
2198   const char **file_names;
2199
2200   /* The file names from the line table after being run through
2201      gdb_realpath.  These are computed lazily.  */
2202   const char **real_names;
2203 };
2204
2205 /* When using the index (and thus not using psymtabs), each CU has an
2206    object of this type.  This is used to hold information needed by
2207    the various "quick" methods.  */
2208 struct dwarf2_per_cu_quick_data
2209 {
2210   /* The file table.  This can be NULL if there was no file table
2211      or it's currently not read in.
2212      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2213   struct quick_file_names *file_names;
2214
2215   /* The corresponding symbol table.  This is NULL if symbols for this
2216      CU have not yet been read.  */
2217   struct symtab *symtab;
2218
2219   /* A temporary mark bit used when iterating over all CUs in
2220      expand_symtabs_matching.  */
2221   unsigned int mark : 1;
2222
2223   /* True if we've tried to read the file table and found there isn't one.
2224      There will be no point in trying to read it again next time.  */
2225   unsigned int no_file_data : 1;
2226 };
2227
2228 /* Utility hash function for a stmt_list_hash.  */
2229
2230 static hashval_t
2231 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2232 {
2233   hashval_t v = 0;
2234
2235   if (stmt_list_hash->dwo_unit != NULL)
2236     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2237   v += stmt_list_hash->line_offset.sect_off;
2238   return v;
2239 }
2240
2241 /* Utility equality function for a stmt_list_hash.  */
2242
2243 static int
2244 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2245                     const struct stmt_list_hash *rhs)
2246 {
2247   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2248     return 0;
2249   if (lhs->dwo_unit != NULL
2250       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2251     return 0;
2252
2253   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2254 }
2255
2256 /* Hash function for a quick_file_names.  */
2257
2258 static hashval_t
2259 hash_file_name_entry (const void *e)
2260 {
2261   const struct quick_file_names *file_data = e;
2262
2263   return hash_stmt_list_entry (&file_data->hash);
2264 }
2265
2266 /* Equality function for a quick_file_names.  */
2267
2268 static int
2269 eq_file_name_entry (const void *a, const void *b)
2270 {
2271   const struct quick_file_names *ea = a;
2272   const struct quick_file_names *eb = b;
2273
2274   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2275 }
2276
2277 /* Delete function for a quick_file_names.  */
2278
2279 static void
2280 delete_file_name_entry (void *e)
2281 {
2282   struct quick_file_names *file_data = e;
2283   int i;
2284
2285   for (i = 0; i < file_data->num_file_names; ++i)
2286     {
2287       xfree ((void*) file_data->file_names[i]);
2288       if (file_data->real_names)
2289         xfree ((void*) file_data->real_names[i]);
2290     }
2291
2292   /* The space for the struct itself lives on objfile_obstack,
2293      so we don't free it here.  */
2294 }
2295
2296 /* Create a quick_file_names hash table.  */
2297
2298 static htab_t
2299 create_quick_file_names_table (unsigned int nr_initial_entries)
2300 {
2301   return htab_create_alloc (nr_initial_entries,
2302                             hash_file_name_entry, eq_file_name_entry,
2303                             delete_file_name_entry, xcalloc, xfree);
2304 }
2305
2306 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2307    have to be created afterwards.  You should call age_cached_comp_units after
2308    processing PER_CU->CU.  dw2_setup must have been already called.  */
2309
2310 static void
2311 load_cu (struct dwarf2_per_cu_data *per_cu)
2312 {
2313   if (per_cu->is_debug_types)
2314     load_full_type_unit (per_cu);
2315   else
2316     load_full_comp_unit (per_cu, language_minimal);
2317
2318   gdb_assert (per_cu->cu != NULL);
2319
2320   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2321 }
2322
2323 /* Read in the symbols for PER_CU.  */
2324
2325 static void
2326 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2327 {
2328   struct cleanup *back_to;
2329
2330   /* Skip type_unit_groups, reading the type units they contain
2331      is handled elsewhere.  */
2332   if (IS_TYPE_UNIT_GROUP (per_cu))
2333     return;
2334
2335   back_to = make_cleanup (dwarf2_release_queue, NULL);
2336
2337   if (dwarf2_per_objfile->using_index
2338       ? per_cu->v.quick->symtab == NULL
2339       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2340     {
2341       queue_comp_unit (per_cu, language_minimal);
2342       load_cu (per_cu);
2343
2344       /* If we just loaded a CU from a DWO, and we're working with an index
2345          that may badly handle TUs, load all the TUs in that DWO as well.
2346          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2347       if (!per_cu->is_debug_types
2348           && per_cu->cu->dwo_unit != NULL
2349           && dwarf2_per_objfile->index_table != NULL
2350           && dwarf2_per_objfile->index_table->version <= 7
2351           /* DWP files aren't supported yet.  */
2352           && get_dwp_file () == NULL)
2353         queue_and_load_all_dwo_tus (per_cu);
2354     }
2355
2356   process_queue ();
2357
2358   /* Age the cache, releasing compilation units that have not
2359      been used recently.  */
2360   age_cached_comp_units ();
2361
2362   do_cleanups (back_to);
2363 }
2364
2365 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2366    the objfile from which this CU came.  Returns the resulting symbol
2367    table.  */
2368
2369 static struct symtab *
2370 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2371 {
2372   gdb_assert (dwarf2_per_objfile->using_index);
2373   if (!per_cu->v.quick->symtab)
2374     {
2375       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2376       increment_reading_symtab ();
2377       dw2_do_instantiate_symtab (per_cu);
2378       process_cu_includes ();
2379       do_cleanups (back_to);
2380     }
2381   return per_cu->v.quick->symtab;
2382 }
2383
2384 /* Return the CU given its index.
2385
2386    This is intended for loops like:
2387
2388    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2389                     + dwarf2_per_objfile->n_type_units); ++i)
2390      {
2391        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2392
2393        ...;
2394      }
2395 */
2396
2397 static struct dwarf2_per_cu_data *
2398 dw2_get_cu (int index)
2399 {
2400   if (index >= dwarf2_per_objfile->n_comp_units)
2401     {
2402       index -= dwarf2_per_objfile->n_comp_units;
2403       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2404       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2405     }
2406
2407   return dwarf2_per_objfile->all_comp_units[index];
2408 }
2409
2410 /* Return the primary CU given its index.
2411    The difference between this function and dw2_get_cu is in the handling
2412    of type units (TUs).  Here we return the type_unit_group object.
2413
2414    This is intended for loops like:
2415
2416    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2417                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2418      {
2419        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2420
2421        ...;
2422      }
2423 */
2424
2425 static struct dwarf2_per_cu_data *
2426 dw2_get_primary_cu (int index)
2427 {
2428   if (index >= dwarf2_per_objfile->n_comp_units)
2429     {
2430       index -= dwarf2_per_objfile->n_comp_units;
2431       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2432       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2433     }
2434
2435   return dwarf2_per_objfile->all_comp_units[index];
2436 }
2437
2438 /* A helper for create_cus_from_index that handles a given list of
2439    CUs.  */
2440
2441 static void
2442 create_cus_from_index_list (struct objfile *objfile,
2443                             const gdb_byte *cu_list, offset_type n_elements,
2444                             struct dwarf2_section_info *section,
2445                             int is_dwz,
2446                             int base_offset)
2447 {
2448   offset_type i;
2449
2450   for (i = 0; i < n_elements; i += 2)
2451     {
2452       struct dwarf2_per_cu_data *the_cu;
2453       ULONGEST offset, length;
2454
2455       gdb_static_assert (sizeof (ULONGEST) >= 8);
2456       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2457       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2458       cu_list += 2 * 8;
2459
2460       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2461                                struct dwarf2_per_cu_data);
2462       the_cu->offset.sect_off = offset;
2463       the_cu->length = length;
2464       the_cu->objfile = objfile;
2465       the_cu->section = section;
2466       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2467                                         struct dwarf2_per_cu_quick_data);
2468       the_cu->is_dwz = is_dwz;
2469       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2470     }
2471 }
2472
2473 /* Read the CU list from the mapped index, and use it to create all
2474    the CU objects for this objfile.  */
2475
2476 static void
2477 create_cus_from_index (struct objfile *objfile,
2478                        const gdb_byte *cu_list, offset_type cu_list_elements,
2479                        const gdb_byte *dwz_list, offset_type dwz_elements)
2480 {
2481   struct dwz_file *dwz;
2482
2483   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2484   dwarf2_per_objfile->all_comp_units
2485     = obstack_alloc (&objfile->objfile_obstack,
2486                      dwarf2_per_objfile->n_comp_units
2487                      * sizeof (struct dwarf2_per_cu_data *));
2488
2489   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2490                               &dwarf2_per_objfile->info, 0, 0);
2491
2492   if (dwz_elements == 0)
2493     return;
2494
2495   dwz = dwarf2_get_dwz_file ();
2496   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2497                               cu_list_elements / 2);
2498 }
2499
2500 /* Create the signatured type hash table from the index.  */
2501
2502 static void
2503 create_signatured_type_table_from_index (struct objfile *objfile,
2504                                          struct dwarf2_section_info *section,
2505                                          const gdb_byte *bytes,
2506                                          offset_type elements)
2507 {
2508   offset_type i;
2509   htab_t sig_types_hash;
2510
2511   dwarf2_per_objfile->n_type_units = elements / 3;
2512   dwarf2_per_objfile->all_type_units
2513     = xmalloc (dwarf2_per_objfile->n_type_units
2514                * sizeof (struct signatured_type *));
2515
2516   sig_types_hash = allocate_signatured_type_table (objfile);
2517
2518   for (i = 0; i < elements; i += 3)
2519     {
2520       struct signatured_type *sig_type;
2521       ULONGEST offset, type_offset_in_tu, signature;
2522       void **slot;
2523
2524       gdb_static_assert (sizeof (ULONGEST) >= 8);
2525       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2526       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2527                                                     BFD_ENDIAN_LITTLE);
2528       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2529       bytes += 3 * 8;
2530
2531       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2532                                  struct signatured_type);
2533       sig_type->signature = signature;
2534       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2535       sig_type->per_cu.is_debug_types = 1;
2536       sig_type->per_cu.section = section;
2537       sig_type->per_cu.offset.sect_off = offset;
2538       sig_type->per_cu.objfile = objfile;
2539       sig_type->per_cu.v.quick
2540         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2541                           struct dwarf2_per_cu_quick_data);
2542
2543       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2544       *slot = sig_type;
2545
2546       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2547     }
2548
2549   dwarf2_per_objfile->signatured_types = sig_types_hash;
2550 }
2551
2552 /* Read the address map data from the mapped index, and use it to
2553    populate the objfile's psymtabs_addrmap.  */
2554
2555 static void
2556 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2557 {
2558   const gdb_byte *iter, *end;
2559   struct obstack temp_obstack;
2560   struct addrmap *mutable_map;
2561   struct cleanup *cleanup;
2562   CORE_ADDR baseaddr;
2563
2564   obstack_init (&temp_obstack);
2565   cleanup = make_cleanup_obstack_free (&temp_obstack);
2566   mutable_map = addrmap_create_mutable (&temp_obstack);
2567
2568   iter = index->address_table;
2569   end = iter + index->address_table_size;
2570
2571   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2572
2573   while (iter < end)
2574     {
2575       ULONGEST hi, lo, cu_index;
2576       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2577       iter += 8;
2578       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2579       iter += 8;
2580       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2581       iter += 4;
2582
2583       if (lo > hi)
2584         {
2585           complaint (&symfile_complaints,
2586                      _(".gdb_index address table has invalid range (%s - %s)"),
2587                      hex_string (lo), hex_string (hi));
2588           continue;
2589         }
2590
2591       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2592         {
2593           complaint (&symfile_complaints,
2594                      _(".gdb_index address table has invalid CU number %u"),
2595                      (unsigned) cu_index);
2596           continue;
2597         }
2598
2599       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2600                          dw2_get_cu (cu_index));
2601     }
2602
2603   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2604                                                     &objfile->objfile_obstack);
2605   do_cleanups (cleanup);
2606 }
2607
2608 /* The hash function for strings in the mapped index.  This is the same as
2609    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2610    implementation.  This is necessary because the hash function is tied to the
2611    format of the mapped index file.  The hash values do not have to match with
2612    SYMBOL_HASH_NEXT.
2613    
2614    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2615
2616 static hashval_t
2617 mapped_index_string_hash (int index_version, const void *p)
2618 {
2619   const unsigned char *str = (const unsigned char *) p;
2620   hashval_t r = 0;
2621   unsigned char c;
2622
2623   while ((c = *str++) != 0)
2624     {
2625       if (index_version >= 5)
2626         c = tolower (c);
2627       r = r * 67 + c - 113;
2628     }
2629
2630   return r;
2631 }
2632
2633 /* Find a slot in the mapped index INDEX for the object named NAME.
2634    If NAME is found, set *VEC_OUT to point to the CU vector in the
2635    constant pool and return 1.  If NAME cannot be found, return 0.  */
2636
2637 static int
2638 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2639                           offset_type **vec_out)
2640 {
2641   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2642   offset_type hash;
2643   offset_type slot, step;
2644   int (*cmp) (const char *, const char *);
2645
2646   if (current_language->la_language == language_cplus
2647       || current_language->la_language == language_java
2648       || current_language->la_language == language_fortran)
2649     {
2650       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2651          not contain any.  */
2652       const char *paren = strchr (name, '(');
2653
2654       if (paren)
2655         {
2656           char *dup;
2657
2658           dup = xmalloc (paren - name + 1);
2659           memcpy (dup, name, paren - name);
2660           dup[paren - name] = 0;
2661
2662           make_cleanup (xfree, dup);
2663           name = dup;
2664         }
2665     }
2666
2667   /* Index version 4 did not support case insensitive searches.  But the
2668      indices for case insensitive languages are built in lowercase, therefore
2669      simulate our NAME being searched is also lowercased.  */
2670   hash = mapped_index_string_hash ((index->version == 4
2671                                     && case_sensitivity == case_sensitive_off
2672                                     ? 5 : index->version),
2673                                    name);
2674
2675   slot = hash & (index->symbol_table_slots - 1);
2676   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2677   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2678
2679   for (;;)
2680     {
2681       /* Convert a slot number to an offset into the table.  */
2682       offset_type i = 2 * slot;
2683       const char *str;
2684       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2685         {
2686           do_cleanups (back_to);
2687           return 0;
2688         }
2689
2690       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2691       if (!cmp (name, str))
2692         {
2693           *vec_out = (offset_type *) (index->constant_pool
2694                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2695           do_cleanups (back_to);
2696           return 1;
2697         }
2698
2699       slot = (slot + step) & (index->symbol_table_slots - 1);
2700     }
2701 }
2702
2703 /* A helper function that reads the .gdb_index from SECTION and fills
2704    in MAP.  FILENAME is the name of the file containing the section;
2705    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2706    ok to use deprecated sections.
2707
2708    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2709    out parameters that are filled in with information about the CU and
2710    TU lists in the section.
2711
2712    Returns 1 if all went well, 0 otherwise.  */
2713
2714 static int
2715 read_index_from_section (struct objfile *objfile,
2716                          const char *filename,
2717                          int deprecated_ok,
2718                          struct dwarf2_section_info *section,
2719                          struct mapped_index *map,
2720                          const gdb_byte **cu_list,
2721                          offset_type *cu_list_elements,
2722                          const gdb_byte **types_list,
2723                          offset_type *types_list_elements)
2724 {
2725   const gdb_byte *addr;
2726   offset_type version;
2727   offset_type *metadata;
2728   int i;
2729
2730   if (dwarf2_section_empty_p (section))
2731     return 0;
2732
2733   /* Older elfutils strip versions could keep the section in the main
2734      executable while splitting it for the separate debug info file.  */
2735   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2736     return 0;
2737
2738   dwarf2_read_section (objfile, section);
2739
2740   addr = section->buffer;
2741   /* Version check.  */
2742   version = MAYBE_SWAP (*(offset_type *) addr);
2743   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2744      causes the index to behave very poorly for certain requests.  Version 3
2745      contained incomplete addrmap.  So, it seems better to just ignore such
2746      indices.  */
2747   if (version < 4)
2748     {
2749       static int warning_printed = 0;
2750       if (!warning_printed)
2751         {
2752           warning (_("Skipping obsolete .gdb_index section in %s."),
2753                    filename);
2754           warning_printed = 1;
2755         }
2756       return 0;
2757     }
2758   /* Index version 4 uses a different hash function than index version
2759      5 and later.
2760
2761      Versions earlier than 6 did not emit psymbols for inlined
2762      functions.  Using these files will cause GDB not to be able to
2763      set breakpoints on inlined functions by name, so we ignore these
2764      indices unless the user has done
2765      "set use-deprecated-index-sections on".  */
2766   if (version < 6 && !deprecated_ok)
2767     {
2768       static int warning_printed = 0;
2769       if (!warning_printed)
2770         {
2771           warning (_("\
2772 Skipping deprecated .gdb_index section in %s.\n\
2773 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2774 to use the section anyway."),
2775                    filename);
2776           warning_printed = 1;
2777         }
2778       return 0;
2779     }
2780   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2781      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2782      we can't distinguish gdb-generated indices from gold-generated ones, so
2783      nothing to do here.  */
2784
2785   /* Indexes with higher version than the one supported by GDB may be no
2786      longer backward compatible.  */
2787   if (version > 8)
2788     return 0;
2789
2790   map->version = version;
2791   map->total_size = section->size;
2792
2793   metadata = (offset_type *) (addr + sizeof (offset_type));
2794
2795   i = 0;
2796   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2797   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2798                        / 8);
2799   ++i;
2800
2801   *types_list = addr + MAYBE_SWAP (metadata[i]);
2802   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2803                            - MAYBE_SWAP (metadata[i]))
2804                           / 8);
2805   ++i;
2806
2807   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2808   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2809                              - MAYBE_SWAP (metadata[i]));
2810   ++i;
2811
2812   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2813   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2814                               - MAYBE_SWAP (metadata[i]))
2815                              / (2 * sizeof (offset_type)));
2816   ++i;
2817
2818   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2819
2820   return 1;
2821 }
2822
2823
2824 /* Read the index file.  If everything went ok, initialize the "quick"
2825    elements of all the CUs and return 1.  Otherwise, return 0.  */
2826
2827 static int
2828 dwarf2_read_index (struct objfile *objfile)
2829 {
2830   struct mapped_index local_map, *map;
2831   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2832   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2833   struct dwz_file *dwz;
2834
2835   if (!read_index_from_section (objfile, objfile->name,
2836                                 use_deprecated_index_sections,
2837                                 &dwarf2_per_objfile->gdb_index, &local_map,
2838                                 &cu_list, &cu_list_elements,
2839                                 &types_list, &types_list_elements))
2840     return 0;
2841
2842   /* Don't use the index if it's empty.  */
2843   if (local_map.symbol_table_slots == 0)
2844     return 0;
2845
2846   /* If there is a .dwz file, read it so we can get its CU list as
2847      well.  */
2848   dwz = dwarf2_get_dwz_file ();
2849   if (dwz != NULL)
2850     {
2851       struct mapped_index dwz_map;
2852       const gdb_byte *dwz_types_ignore;
2853       offset_type dwz_types_elements_ignore;
2854
2855       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2856                                     1,
2857                                     &dwz->gdb_index, &dwz_map,
2858                                     &dwz_list, &dwz_list_elements,
2859                                     &dwz_types_ignore,
2860                                     &dwz_types_elements_ignore))
2861         {
2862           warning (_("could not read '.gdb_index' section from %s; skipping"),
2863                    bfd_get_filename (dwz->dwz_bfd));
2864           return 0;
2865         }
2866     }
2867
2868   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2869                          dwz_list_elements);
2870
2871   if (types_list_elements)
2872     {
2873       struct dwarf2_section_info *section;
2874
2875       /* We can only handle a single .debug_types when we have an
2876          index.  */
2877       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2878         return 0;
2879
2880       section = VEC_index (dwarf2_section_info_def,
2881                            dwarf2_per_objfile->types, 0);
2882
2883       create_signatured_type_table_from_index (objfile, section, types_list,
2884                                                types_list_elements);
2885     }
2886
2887   create_addrmap_from_index (objfile, &local_map);
2888
2889   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2890   *map = local_map;
2891
2892   dwarf2_per_objfile->index_table = map;
2893   dwarf2_per_objfile->using_index = 1;
2894   dwarf2_per_objfile->quick_file_names_table =
2895     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2896
2897   return 1;
2898 }
2899
2900 /* A helper for the "quick" functions which sets the global
2901    dwarf2_per_objfile according to OBJFILE.  */
2902
2903 static void
2904 dw2_setup (struct objfile *objfile)
2905 {
2906   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2907   gdb_assert (dwarf2_per_objfile);
2908 }
2909
2910 /* die_reader_func for dw2_get_file_names.  */
2911
2912 static void
2913 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2914                            const gdb_byte *info_ptr,
2915                            struct die_info *comp_unit_die,
2916                            int has_children,
2917                            void *data)
2918 {
2919   struct dwarf2_cu *cu = reader->cu;
2920   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2921   struct objfile *objfile = dwarf2_per_objfile->objfile;
2922   struct dwarf2_per_cu_data *lh_cu;
2923   struct line_header *lh;
2924   struct attribute *attr;
2925   int i;
2926   const char *name, *comp_dir;
2927   void **slot;
2928   struct quick_file_names *qfn;
2929   unsigned int line_offset;
2930
2931   gdb_assert (! this_cu->is_debug_types);
2932
2933   /* Our callers never want to match partial units -- instead they
2934      will match the enclosing full CU.  */
2935   if (comp_unit_die->tag == DW_TAG_partial_unit)
2936     {
2937       this_cu->v.quick->no_file_data = 1;
2938       return;
2939     }
2940
2941   lh_cu = this_cu;
2942   lh = NULL;
2943   slot = NULL;
2944   line_offset = 0;
2945
2946   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2947   if (attr)
2948     {
2949       struct quick_file_names find_entry;
2950
2951       line_offset = DW_UNSND (attr);
2952
2953       /* We may have already read in this line header (TU line header sharing).
2954          If we have we're done.  */
2955       find_entry.hash.dwo_unit = cu->dwo_unit;
2956       find_entry.hash.line_offset.sect_off = line_offset;
2957       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2958                              &find_entry, INSERT);
2959       if (*slot != NULL)
2960         {
2961           lh_cu->v.quick->file_names = *slot;
2962           return;
2963         }
2964
2965       lh = dwarf_decode_line_header (line_offset, cu);
2966     }
2967   if (lh == NULL)
2968     {
2969       lh_cu->v.quick->no_file_data = 1;
2970       return;
2971     }
2972
2973   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2974   qfn->hash.dwo_unit = cu->dwo_unit;
2975   qfn->hash.line_offset.sect_off = line_offset;
2976   gdb_assert (slot != NULL);
2977   *slot = qfn;
2978
2979   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2980
2981   qfn->num_file_names = lh->num_file_names;
2982   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2983                                    lh->num_file_names * sizeof (char *));
2984   for (i = 0; i < lh->num_file_names; ++i)
2985     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2986   qfn->real_names = NULL;
2987
2988   free_line_header (lh);
2989
2990   lh_cu->v.quick->file_names = qfn;
2991 }
2992
2993 /* A helper for the "quick" functions which attempts to read the line
2994    table for THIS_CU.  */
2995
2996 static struct quick_file_names *
2997 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2998 {
2999   /* This should never be called for TUs.  */
3000   gdb_assert (! this_cu->is_debug_types);
3001   /* Nor type unit groups.  */
3002   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3003
3004   if (this_cu->v.quick->file_names != NULL)
3005     return this_cu->v.quick->file_names;
3006   /* If we know there is no line data, no point in looking again.  */
3007   if (this_cu->v.quick->no_file_data)
3008     return NULL;
3009
3010   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3011
3012   if (this_cu->v.quick->no_file_data)
3013     return NULL;
3014   return this_cu->v.quick->file_names;
3015 }
3016
3017 /* A helper for the "quick" functions which computes and caches the
3018    real path for a given file name from the line table.  */
3019
3020 static const char *
3021 dw2_get_real_path (struct objfile *objfile,
3022                    struct quick_file_names *qfn, int index)
3023 {
3024   if (qfn->real_names == NULL)
3025     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3026                                       qfn->num_file_names, sizeof (char *));
3027
3028   if (qfn->real_names[index] == NULL)
3029     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3030
3031   return qfn->real_names[index];
3032 }
3033
3034 static struct symtab *
3035 dw2_find_last_source_symtab (struct objfile *objfile)
3036 {
3037   int index;
3038
3039   dw2_setup (objfile);
3040   index = dwarf2_per_objfile->n_comp_units - 1;
3041   return dw2_instantiate_symtab (dw2_get_cu (index));
3042 }
3043
3044 /* Traversal function for dw2_forget_cached_source_info.  */
3045
3046 static int
3047 dw2_free_cached_file_names (void **slot, void *info)
3048 {
3049   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3050
3051   if (file_data->real_names)
3052     {
3053       int i;
3054
3055       for (i = 0; i < file_data->num_file_names; ++i)
3056         {
3057           xfree ((void*) file_data->real_names[i]);
3058           file_data->real_names[i] = NULL;
3059         }
3060     }
3061
3062   return 1;
3063 }
3064
3065 static void
3066 dw2_forget_cached_source_info (struct objfile *objfile)
3067 {
3068   dw2_setup (objfile);
3069
3070   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3071                           dw2_free_cached_file_names, NULL);
3072 }
3073
3074 /* Helper function for dw2_map_symtabs_matching_filename that expands
3075    the symtabs and calls the iterator.  */
3076
3077 static int
3078 dw2_map_expand_apply (struct objfile *objfile,
3079                       struct dwarf2_per_cu_data *per_cu,
3080                       const char *name, const char *real_path,
3081                       int (*callback) (struct symtab *, void *),
3082                       void *data)
3083 {
3084   struct symtab *last_made = objfile->symtabs;
3085
3086   /* Don't visit already-expanded CUs.  */
3087   if (per_cu->v.quick->symtab)
3088     return 0;
3089
3090   /* This may expand more than one symtab, and we want to iterate over
3091      all of them.  */
3092   dw2_instantiate_symtab (per_cu);
3093
3094   return iterate_over_some_symtabs (name, real_path, callback, data,
3095                                     objfile->symtabs, last_made);
3096 }
3097
3098 /* Implementation of the map_symtabs_matching_filename method.  */
3099
3100 static int
3101 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3102                                    const char *real_path,
3103                                    int (*callback) (struct symtab *, void *),
3104                                    void *data)
3105 {
3106   int i;
3107   const char *name_basename = lbasename (name);
3108
3109   dw2_setup (objfile);
3110
3111   /* The rule is CUs specify all the files, including those used by
3112      any TU, so there's no need to scan TUs here.  */
3113
3114   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3115     {
3116       int j;
3117       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3118       struct quick_file_names *file_data;
3119
3120       /* We only need to look at symtabs not already expanded.  */
3121       if (per_cu->v.quick->symtab)
3122         continue;
3123
3124       file_data = dw2_get_file_names (per_cu);
3125       if (file_data == NULL)
3126         continue;
3127
3128       for (j = 0; j < file_data->num_file_names; ++j)
3129         {
3130           const char *this_name = file_data->file_names[j];
3131           const char *this_real_name;
3132
3133           if (compare_filenames_for_search (this_name, name))
3134             {
3135               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3136                                         callback, data))
3137                 return 1;
3138               continue;
3139             }
3140
3141           /* Before we invoke realpath, which can get expensive when many
3142              files are involved, do a quick comparison of the basenames.  */
3143           if (! basenames_may_differ
3144               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3145             continue;
3146
3147           this_real_name = dw2_get_real_path (objfile, file_data, j);
3148           if (compare_filenames_for_search (this_real_name, name))
3149             {
3150               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3151                                         callback, data))
3152                 return 1;
3153               continue;
3154             }
3155
3156           if (real_path != NULL)
3157             {
3158               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3159               gdb_assert (IS_ABSOLUTE_PATH (name));
3160               if (this_real_name != NULL
3161                   && FILENAME_CMP (real_path, this_real_name) == 0)
3162                 {
3163                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3164                                             callback, data))
3165                     return 1;
3166                   continue;
3167                 }
3168             }
3169         }
3170     }
3171
3172   return 0;
3173 }
3174
3175 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3176
3177 struct dw2_symtab_iterator
3178 {
3179   /* The internalized form of .gdb_index.  */
3180   struct mapped_index *index;
3181   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3182   int want_specific_block;
3183   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3184      Unused if !WANT_SPECIFIC_BLOCK.  */
3185   int block_index;
3186   /* The kind of symbol we're looking for.  */
3187   domain_enum domain;
3188   /* The list of CUs from the index entry of the symbol,
3189      or NULL if not found.  */
3190   offset_type *vec;
3191   /* The next element in VEC to look at.  */
3192   int next;
3193   /* The number of elements in VEC, or zero if there is no match.  */
3194   int length;
3195 };
3196
3197 /* Initialize the index symtab iterator ITER.
3198    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3199    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3200
3201 static void
3202 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3203                       struct mapped_index *index,
3204                       int want_specific_block,
3205                       int block_index,
3206                       domain_enum domain,
3207                       const char *name)
3208 {
3209   iter->index = index;
3210   iter->want_specific_block = want_specific_block;
3211   iter->block_index = block_index;
3212   iter->domain = domain;
3213   iter->next = 0;
3214
3215   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3216     iter->length = MAYBE_SWAP (*iter->vec);
3217   else
3218     {
3219       iter->vec = NULL;
3220       iter->length = 0;
3221     }
3222 }
3223
3224 /* Return the next matching CU or NULL if there are no more.  */
3225
3226 static struct dwarf2_per_cu_data *
3227 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3228 {
3229   for ( ; iter->next < iter->length; ++iter->next)
3230     {
3231       offset_type cu_index_and_attrs =
3232         MAYBE_SWAP (iter->vec[iter->next + 1]);
3233       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3234       struct dwarf2_per_cu_data *per_cu;
3235       int want_static = iter->block_index != GLOBAL_BLOCK;
3236       /* This value is only valid for index versions >= 7.  */
3237       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3238       gdb_index_symbol_kind symbol_kind =
3239         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3240       /* Only check the symbol attributes if they're present.
3241          Indices prior to version 7 don't record them,
3242          and indices >= 7 may elide them for certain symbols
3243          (gold does this).  */
3244       int attrs_valid =
3245         (iter->index->version >= 7
3246          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3247
3248       /* Don't crash on bad data.  */
3249       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3250                        + dwarf2_per_objfile->n_type_units))
3251         {
3252           complaint (&symfile_complaints,
3253                      _(".gdb_index entry has bad CU index"
3254                        " [in module %s]"), dwarf2_per_objfile->objfile->name);
3255           continue;
3256         }
3257
3258       per_cu = dw2_get_cu (cu_index);
3259
3260       /* Skip if already read in.  */
3261       if (per_cu->v.quick->symtab)
3262         continue;
3263
3264       if (attrs_valid
3265           && iter->want_specific_block
3266           && want_static != is_static)
3267         continue;
3268
3269       /* Only check the symbol's kind if it has one.  */
3270       if (attrs_valid)
3271         {
3272           switch (iter->domain)
3273             {
3274             case VAR_DOMAIN:
3275               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3276                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3277                   /* Some types are also in VAR_DOMAIN.  */
3278                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3279                 continue;
3280               break;
3281             case STRUCT_DOMAIN:
3282               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3283                 continue;
3284               break;
3285             case LABEL_DOMAIN:
3286               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3287                 continue;
3288               break;
3289             default:
3290               break;
3291             }
3292         }
3293
3294       ++iter->next;
3295       return per_cu;
3296     }
3297
3298   return NULL;
3299 }
3300
3301 static struct symtab *
3302 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3303                    const char *name, domain_enum domain)
3304 {
3305   struct symtab *stab_best = NULL;
3306   struct mapped_index *index;
3307
3308   dw2_setup (objfile);
3309
3310   index = dwarf2_per_objfile->index_table;
3311
3312   /* index is NULL if OBJF_READNOW.  */
3313   if (index)
3314     {
3315       struct dw2_symtab_iterator iter;
3316       struct dwarf2_per_cu_data *per_cu;
3317
3318       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3319
3320       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3321         {
3322           struct symbol *sym = NULL;
3323           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3324
3325           /* Some caution must be observed with overloaded functions
3326              and methods, since the index will not contain any overload
3327              information (but NAME might contain it).  */
3328           if (stab->primary)
3329             {
3330               struct blockvector *bv = BLOCKVECTOR (stab);
3331               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3332
3333               sym = lookup_block_symbol (block, name, domain);
3334             }
3335
3336           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3337             {
3338               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3339                 return stab;
3340
3341               stab_best = stab;
3342             }
3343
3344           /* Keep looking through other CUs.  */
3345         }
3346     }
3347
3348   return stab_best;
3349 }
3350
3351 static void
3352 dw2_print_stats (struct objfile *objfile)
3353 {
3354   int i, total, count;
3355
3356   dw2_setup (objfile);
3357   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3358   count = 0;
3359   for (i = 0; i < total; ++i)
3360     {
3361       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3362
3363       if (!per_cu->v.quick->symtab)
3364         ++count;
3365     }
3366   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3367   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3368 }
3369
3370 /* This dumps minimal information about the index.
3371    It is called via "mt print objfiles".
3372    One use is to verify .gdb_index has been loaded by the
3373    gdb.dwarf2/gdb-index.exp testcase.  */
3374
3375 static void
3376 dw2_dump (struct objfile *objfile)
3377 {
3378   dw2_setup (objfile);
3379   gdb_assert (dwarf2_per_objfile->using_index);
3380   printf_filtered (".gdb_index:");
3381   if (dwarf2_per_objfile->index_table != NULL)
3382     {
3383       printf_filtered (" version %d\n",
3384                        dwarf2_per_objfile->index_table->version);
3385     }
3386   else
3387     printf_filtered (" faked for \"readnow\"\n");
3388   printf_filtered ("\n");
3389 }
3390
3391 static void
3392 dw2_relocate (struct objfile *objfile,
3393               const struct section_offsets *new_offsets,
3394               const struct section_offsets *delta)
3395 {
3396   /* There's nothing to relocate here.  */
3397 }
3398
3399 static void
3400 dw2_expand_symtabs_for_function (struct objfile *objfile,
3401                                  const char *func_name)
3402 {
3403   struct mapped_index *index;
3404
3405   dw2_setup (objfile);
3406
3407   index = dwarf2_per_objfile->index_table;
3408
3409   /* index is NULL if OBJF_READNOW.  */
3410   if (index)
3411     {
3412       struct dw2_symtab_iterator iter;
3413       struct dwarf2_per_cu_data *per_cu;
3414
3415       /* Note: It doesn't matter what we pass for block_index here.  */
3416       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3417                             func_name);
3418
3419       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3420         dw2_instantiate_symtab (per_cu);
3421     }
3422 }
3423
3424 static void
3425 dw2_expand_all_symtabs (struct objfile *objfile)
3426 {
3427   int i;
3428
3429   dw2_setup (objfile);
3430
3431   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3432                    + dwarf2_per_objfile->n_type_units); ++i)
3433     {
3434       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3435
3436       dw2_instantiate_symtab (per_cu);
3437     }
3438 }
3439
3440 static void
3441 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3442                                   const char *fullname)
3443 {
3444   int i;
3445
3446   dw2_setup (objfile);
3447
3448   /* We don't need to consider type units here.
3449      This is only called for examining code, e.g. expand_line_sal.
3450      There can be an order of magnitude (or more) more type units
3451      than comp units, and we avoid them if we can.  */
3452
3453   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3454     {
3455       int j;
3456       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3457       struct quick_file_names *file_data;
3458
3459       /* We only need to look at symtabs not already expanded.  */
3460       if (per_cu->v.quick->symtab)
3461         continue;
3462
3463       file_data = dw2_get_file_names (per_cu);
3464       if (file_data == NULL)
3465         continue;
3466
3467       for (j = 0; j < file_data->num_file_names; ++j)
3468         {
3469           const char *this_fullname = file_data->file_names[j];
3470
3471           if (filename_cmp (this_fullname, fullname) == 0)
3472             {
3473               dw2_instantiate_symtab (per_cu);
3474               break;
3475             }
3476         }
3477     }
3478 }
3479
3480 static void
3481 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3482                           struct objfile *objfile, int global,
3483                           int (*callback) (struct block *,
3484                                            struct symbol *, void *),
3485                           void *data, symbol_compare_ftype *match,
3486                           symbol_compare_ftype *ordered_compare)
3487 {
3488   /* Currently unimplemented; used for Ada.  The function can be called if the
3489      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3490      does not look for non-Ada symbols this function should just return.  */
3491 }
3492
3493 static void
3494 dw2_expand_symtabs_matching
3495   (struct objfile *objfile,
3496    int (*file_matcher) (const char *, void *, int basenames),
3497    int (*name_matcher) (const char *, void *),
3498    enum search_domain kind,
3499    void *data)
3500 {
3501   int i;
3502   offset_type iter;
3503   struct mapped_index *index;
3504
3505   dw2_setup (objfile);
3506
3507   /* index_table is NULL if OBJF_READNOW.  */
3508   if (!dwarf2_per_objfile->index_table)
3509     return;
3510   index = dwarf2_per_objfile->index_table;
3511
3512   if (file_matcher != NULL)
3513     {
3514       struct cleanup *cleanup;
3515       htab_t visited_found, visited_not_found;
3516
3517       visited_found = htab_create_alloc (10,
3518                                          htab_hash_pointer, htab_eq_pointer,
3519                                          NULL, xcalloc, xfree);
3520       cleanup = make_cleanup_htab_delete (visited_found);
3521       visited_not_found = htab_create_alloc (10,
3522                                              htab_hash_pointer, htab_eq_pointer,
3523                                              NULL, xcalloc, xfree);
3524       make_cleanup_htab_delete (visited_not_found);
3525
3526       /* The rule is CUs specify all the files, including those used by
3527          any TU, so there's no need to scan TUs here.  */
3528
3529       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3530         {
3531           int j;
3532           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3533           struct quick_file_names *file_data;
3534           void **slot;
3535
3536           per_cu->v.quick->mark = 0;
3537
3538           /* We only need to look at symtabs not already expanded.  */
3539           if (per_cu->v.quick->symtab)
3540             continue;
3541
3542           file_data = dw2_get_file_names (per_cu);
3543           if (file_data == NULL)
3544             continue;
3545
3546           if (htab_find (visited_not_found, file_data) != NULL)
3547             continue;
3548           else if (htab_find (visited_found, file_data) != NULL)
3549             {
3550               per_cu->v.quick->mark = 1;
3551               continue;
3552             }
3553
3554           for (j = 0; j < file_data->num_file_names; ++j)
3555             {
3556               const char *this_real_name;
3557
3558               if (file_matcher (file_data->file_names[j], data, 0))
3559                 {
3560                   per_cu->v.quick->mark = 1;
3561                   break;
3562                 }
3563
3564               /* Before we invoke realpath, which can get expensive when many
3565                  files are involved, do a quick comparison of the basenames.  */
3566               if (!basenames_may_differ
3567                   && !file_matcher (lbasename (file_data->file_names[j]),
3568                                     data, 1))
3569                 continue;
3570
3571               this_real_name = dw2_get_real_path (objfile, file_data, j);
3572               if (file_matcher (this_real_name, data, 0))
3573                 {
3574                   per_cu->v.quick->mark = 1;
3575                   break;
3576                 }
3577             }
3578
3579           slot = htab_find_slot (per_cu->v.quick->mark
3580                                  ? visited_found
3581                                  : visited_not_found,
3582                                  file_data, INSERT);
3583           *slot = file_data;
3584         }
3585
3586       do_cleanups (cleanup);
3587     }
3588
3589   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3590     {
3591       offset_type idx = 2 * iter;
3592       const char *name;
3593       offset_type *vec, vec_len, vec_idx;
3594
3595       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3596         continue;
3597
3598       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3599
3600       if (! (*name_matcher) (name, data))
3601         continue;
3602
3603       /* The name was matched, now expand corresponding CUs that were
3604          marked.  */
3605       vec = (offset_type *) (index->constant_pool
3606                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3607       vec_len = MAYBE_SWAP (vec[0]);
3608       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3609         {
3610           struct dwarf2_per_cu_data *per_cu;
3611           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3612           gdb_index_symbol_kind symbol_kind =
3613             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3614           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3615           /* Only check the symbol attributes if they're present.
3616              Indices prior to version 7 don't record them,
3617              and indices >= 7 may elide them for certain symbols
3618              (gold does this).  */
3619           int attrs_valid =
3620             (index->version >= 7
3621              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3622
3623           /* Only check the symbol's kind if it has one.  */
3624           if (attrs_valid)
3625             {
3626               switch (kind)
3627                 {
3628                 case VARIABLES_DOMAIN:
3629                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3630                     continue;
3631                   break;
3632                 case FUNCTIONS_DOMAIN:
3633                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3634                     continue;
3635                   break;
3636                 case TYPES_DOMAIN:
3637                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3638                     continue;
3639                   break;
3640                 default:
3641                   break;
3642                 }
3643             }
3644
3645           /* Don't crash on bad data.  */
3646           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3647                            + dwarf2_per_objfile->n_type_units))
3648             {
3649               complaint (&symfile_complaints,
3650                          _(".gdb_index entry has bad CU index"
3651                            " [in module %s]"), objfile->name);
3652               continue;
3653             }
3654
3655           per_cu = dw2_get_cu (cu_index);
3656           if (file_matcher == NULL || per_cu->v.quick->mark)
3657             dw2_instantiate_symtab (per_cu);
3658         }
3659     }
3660 }
3661
3662 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3663    symtab.  */
3664
3665 static struct symtab *
3666 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3667 {
3668   int i;
3669
3670   if (BLOCKVECTOR (symtab) != NULL
3671       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3672     return symtab;
3673
3674   if (symtab->includes == NULL)
3675     return NULL;
3676
3677   for (i = 0; symtab->includes[i]; ++i)
3678     {
3679       struct symtab *s = symtab->includes[i];
3680
3681       s = recursively_find_pc_sect_symtab (s, pc);
3682       if (s != NULL)
3683         return s;
3684     }
3685
3686   return NULL;
3687 }
3688
3689 static struct symtab *
3690 dw2_find_pc_sect_symtab (struct objfile *objfile,
3691                          struct minimal_symbol *msymbol,
3692                          CORE_ADDR pc,
3693                          struct obj_section *section,
3694                          int warn_if_readin)
3695 {
3696   struct dwarf2_per_cu_data *data;
3697   struct symtab *result;
3698
3699   dw2_setup (objfile);
3700
3701   if (!objfile->psymtabs_addrmap)
3702     return NULL;
3703
3704   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3705   if (!data)
3706     return NULL;
3707
3708   if (warn_if_readin && data->v.quick->symtab)
3709     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3710              paddress (get_objfile_arch (objfile), pc));
3711
3712   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3713   gdb_assert (result != NULL);
3714   return result;
3715 }
3716
3717 static void
3718 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3719                           void *data, int need_fullname)
3720 {
3721   int i;
3722   struct cleanup *cleanup;
3723   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3724                                       NULL, xcalloc, xfree);
3725
3726   cleanup = make_cleanup_htab_delete (visited);
3727   dw2_setup (objfile);
3728
3729   /* The rule is CUs specify all the files, including those used by
3730      any TU, so there's no need to scan TUs here.
3731      We can ignore file names coming from already-expanded CUs.  */
3732
3733   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3734     {
3735       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3736
3737       if (per_cu->v.quick->symtab)
3738         {
3739           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3740                                         INSERT);
3741
3742           *slot = per_cu->v.quick->file_names;
3743         }
3744     }
3745
3746   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3747     {
3748       int j;
3749       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3750       struct quick_file_names *file_data;
3751       void **slot;
3752
3753       /* We only need to look at symtabs not already expanded.  */
3754       if (per_cu->v.quick->symtab)
3755         continue;
3756
3757       file_data = dw2_get_file_names (per_cu);
3758       if (file_data == NULL)
3759         continue;
3760
3761       slot = htab_find_slot (visited, file_data, INSERT);
3762       if (*slot)
3763         {
3764           /* Already visited.  */
3765           continue;
3766         }
3767       *slot = file_data;
3768
3769       for (j = 0; j < file_data->num_file_names; ++j)
3770         {
3771           const char *this_real_name;
3772
3773           if (need_fullname)
3774             this_real_name = dw2_get_real_path (objfile, file_data, j);
3775           else
3776             this_real_name = NULL;
3777           (*fun) (file_data->file_names[j], this_real_name, data);
3778         }
3779     }
3780
3781   do_cleanups (cleanup);
3782 }
3783
3784 static int
3785 dw2_has_symbols (struct objfile *objfile)
3786 {
3787   return 1;
3788 }
3789
3790 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3791 {
3792   dw2_has_symbols,
3793   dw2_find_last_source_symtab,
3794   dw2_forget_cached_source_info,
3795   dw2_map_symtabs_matching_filename,
3796   dw2_lookup_symbol,
3797   dw2_print_stats,
3798   dw2_dump,
3799   dw2_relocate,
3800   dw2_expand_symtabs_for_function,
3801   dw2_expand_all_symtabs,
3802   dw2_expand_symtabs_with_fullname,
3803   dw2_map_matching_symbols,
3804   dw2_expand_symtabs_matching,
3805   dw2_find_pc_sect_symtab,
3806   dw2_map_symbol_filenames
3807 };
3808
3809 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3810    file will use psymtabs, or 1 if using the GNU index.  */
3811
3812 int
3813 dwarf2_initialize_objfile (struct objfile *objfile)
3814 {
3815   /* If we're about to read full symbols, don't bother with the
3816      indices.  In this case we also don't care if some other debug
3817      format is making psymtabs, because they are all about to be
3818      expanded anyway.  */
3819   if ((objfile->flags & OBJF_READNOW))
3820     {
3821       int i;
3822
3823       dwarf2_per_objfile->using_index = 1;
3824       create_all_comp_units (objfile);
3825       create_all_type_units (objfile);
3826       dwarf2_per_objfile->quick_file_names_table =
3827         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3828
3829       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3830                        + dwarf2_per_objfile->n_type_units); ++i)
3831         {
3832           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3833
3834           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3835                                             struct dwarf2_per_cu_quick_data);
3836         }
3837
3838       /* Return 1 so that gdb sees the "quick" functions.  However,
3839          these functions will be no-ops because we will have expanded
3840          all symtabs.  */
3841       return 1;
3842     }
3843
3844   if (dwarf2_read_index (objfile))
3845     return 1;
3846
3847   return 0;
3848 }
3849
3850 \f
3851
3852 /* Build a partial symbol table.  */
3853
3854 void
3855 dwarf2_build_psymtabs (struct objfile *objfile)
3856 {
3857   volatile struct gdb_exception except;
3858
3859   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3860     {
3861       init_psymbol_list (objfile, 1024);
3862     }
3863
3864   TRY_CATCH (except, RETURN_MASK_ERROR)
3865     {
3866       /* This isn't really ideal: all the data we allocate on the
3867          objfile's obstack is still uselessly kept around.  However,
3868          freeing it seems unsafe.  */
3869       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3870
3871       dwarf2_build_psymtabs_hard (objfile);
3872       discard_cleanups (cleanups);
3873     }
3874   if (except.reason < 0)
3875     exception_print (gdb_stderr, except);
3876 }
3877
3878 /* Return the total length of the CU described by HEADER.  */
3879
3880 static unsigned int
3881 get_cu_length (const struct comp_unit_head *header)
3882 {
3883   return header->initial_length_size + header->length;
3884 }
3885
3886 /* Return TRUE if OFFSET is within CU_HEADER.  */
3887
3888 static inline int
3889 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3890 {
3891   sect_offset bottom = { cu_header->offset.sect_off };
3892   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3893
3894   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3895 }
3896
3897 /* Find the base address of the compilation unit for range lists and
3898    location lists.  It will normally be specified by DW_AT_low_pc.
3899    In DWARF-3 draft 4, the base address could be overridden by
3900    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3901    compilation units with discontinuous ranges.  */
3902
3903 static void
3904 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3905 {
3906   struct attribute *attr;
3907
3908   cu->base_known = 0;
3909   cu->base_address = 0;
3910
3911   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3912   if (attr)
3913     {
3914       cu->base_address = DW_ADDR (attr);
3915       cu->base_known = 1;
3916     }
3917   else
3918     {
3919       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3920       if (attr)
3921         {
3922           cu->base_address = DW_ADDR (attr);
3923           cu->base_known = 1;
3924         }
3925     }
3926 }
3927
3928 /* Read in the comp unit header information from the debug_info at info_ptr.
3929    NOTE: This leaves members offset, first_die_offset to be filled in
3930    by the caller.  */
3931
3932 static const gdb_byte *
3933 read_comp_unit_head (struct comp_unit_head *cu_header,
3934                      const gdb_byte *info_ptr, bfd *abfd)
3935 {
3936   int signed_addr;
3937   unsigned int bytes_read;
3938
3939   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3940   cu_header->initial_length_size = bytes_read;
3941   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3942   info_ptr += bytes_read;
3943   cu_header->version = read_2_bytes (abfd, info_ptr);
3944   info_ptr += 2;
3945   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3946                                              &bytes_read);
3947   info_ptr += bytes_read;
3948   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3949   info_ptr += 1;
3950   signed_addr = bfd_get_sign_extend_vma (abfd);
3951   if (signed_addr < 0)
3952     internal_error (__FILE__, __LINE__,
3953                     _("read_comp_unit_head: dwarf from non elf file"));
3954   cu_header->signed_addr_p = signed_addr;
3955
3956   return info_ptr;
3957 }
3958
3959 /* Helper function that returns the proper abbrev section for
3960    THIS_CU.  */
3961
3962 static struct dwarf2_section_info *
3963 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3964 {
3965   struct dwarf2_section_info *abbrev;
3966
3967   if (this_cu->is_dwz)
3968     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3969   else
3970     abbrev = &dwarf2_per_objfile->abbrev;
3971
3972   return abbrev;
3973 }
3974
3975 /* Subroutine of read_and_check_comp_unit_head and
3976    read_and_check_type_unit_head to simplify them.
3977    Perform various error checking on the header.  */
3978
3979 static void
3980 error_check_comp_unit_head (struct comp_unit_head *header,
3981                             struct dwarf2_section_info *section,
3982                             struct dwarf2_section_info *abbrev_section)
3983 {
3984   bfd *abfd = section->asection->owner;
3985   const char *filename = bfd_get_filename (abfd);
3986
3987   if (header->version != 2 && header->version != 3 && header->version != 4)
3988     error (_("Dwarf Error: wrong version in compilation unit header "
3989            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3990            filename);
3991
3992   if (header->abbrev_offset.sect_off
3993       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3994     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3995            "(offset 0x%lx + 6) [in module %s]"),
3996            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3997            filename);
3998
3999   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4000      avoid potential 32-bit overflow.  */
4001   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4002       > section->size)
4003     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4004            "(offset 0x%lx + 0) [in module %s]"),
4005            (long) header->length, (long) header->offset.sect_off,
4006            filename);
4007 }
4008
4009 /* Read in a CU/TU header and perform some basic error checking.
4010    The contents of the header are stored in HEADER.
4011    The result is a pointer to the start of the first DIE.  */
4012
4013 static const gdb_byte *
4014 read_and_check_comp_unit_head (struct comp_unit_head *header,
4015                                struct dwarf2_section_info *section,
4016                                struct dwarf2_section_info *abbrev_section,
4017                                const gdb_byte *info_ptr,
4018                                int is_debug_types_section)
4019 {
4020   const gdb_byte *beg_of_comp_unit = info_ptr;
4021   bfd *abfd = section->asection->owner;
4022
4023   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4024
4025   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4026
4027   /* If we're reading a type unit, skip over the signature and
4028      type_offset fields.  */
4029   if (is_debug_types_section)
4030     info_ptr += 8 /*signature*/ + header->offset_size;
4031
4032   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4033
4034   error_check_comp_unit_head (header, section, abbrev_section);
4035
4036   return info_ptr;
4037 }
4038
4039 /* Read in the types comp unit header information from .debug_types entry at
4040    types_ptr.  The result is a pointer to one past the end of the header.  */
4041
4042 static const gdb_byte *
4043 read_and_check_type_unit_head (struct comp_unit_head *header,
4044                                struct dwarf2_section_info *section,
4045                                struct dwarf2_section_info *abbrev_section,
4046                                const gdb_byte *info_ptr,
4047                                ULONGEST *signature,
4048                                cu_offset *type_offset_in_tu)
4049 {
4050   const gdb_byte *beg_of_comp_unit = info_ptr;
4051   bfd *abfd = section->asection->owner;
4052
4053   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4054
4055   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4056
4057   /* If we're reading a type unit, skip over the signature and
4058      type_offset fields.  */
4059   if (signature != NULL)
4060     *signature = read_8_bytes (abfd, info_ptr);
4061   info_ptr += 8;
4062   if (type_offset_in_tu != NULL)
4063     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4064                                                header->offset_size);
4065   info_ptr += header->offset_size;
4066
4067   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4068
4069   error_check_comp_unit_head (header, section, abbrev_section);
4070
4071   return info_ptr;
4072 }
4073
4074 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4075
4076 static sect_offset
4077 read_abbrev_offset (struct dwarf2_section_info *section,
4078                     sect_offset offset)
4079 {
4080   bfd *abfd = section->asection->owner;
4081   const gdb_byte *info_ptr;
4082   unsigned int length, initial_length_size, offset_size;
4083   sect_offset abbrev_offset;
4084
4085   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4086   info_ptr = section->buffer + offset.sect_off;
4087   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4088   offset_size = initial_length_size == 4 ? 4 : 8;
4089   info_ptr += initial_length_size + 2 /*version*/;
4090   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4091   return abbrev_offset;
4092 }
4093
4094 /* Allocate a new partial symtab for file named NAME and mark this new
4095    partial symtab as being an include of PST.  */
4096
4097 static void
4098 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4099                                struct objfile *objfile)
4100 {
4101   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4102
4103   if (!IS_ABSOLUTE_PATH (subpst->filename))
4104     {
4105       /* It shares objfile->objfile_obstack.  */
4106       subpst->dirname = pst->dirname;
4107     }
4108
4109   subpst->section_offsets = pst->section_offsets;
4110   subpst->textlow = 0;
4111   subpst->texthigh = 0;
4112
4113   subpst->dependencies = (struct partial_symtab **)
4114     obstack_alloc (&objfile->objfile_obstack,
4115                    sizeof (struct partial_symtab *));
4116   subpst->dependencies[0] = pst;
4117   subpst->number_of_dependencies = 1;
4118
4119   subpst->globals_offset = 0;
4120   subpst->n_global_syms = 0;
4121   subpst->statics_offset = 0;
4122   subpst->n_static_syms = 0;
4123   subpst->symtab = NULL;
4124   subpst->read_symtab = pst->read_symtab;
4125   subpst->readin = 0;
4126
4127   /* No private part is necessary for include psymtabs.  This property
4128      can be used to differentiate between such include psymtabs and
4129      the regular ones.  */
4130   subpst->read_symtab_private = NULL;
4131 }
4132
4133 /* Read the Line Number Program data and extract the list of files
4134    included by the source file represented by PST.  Build an include
4135    partial symtab for each of these included files.  */
4136
4137 static void
4138 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4139                                struct die_info *die,
4140                                struct partial_symtab *pst)
4141 {
4142   struct line_header *lh = NULL;
4143   struct attribute *attr;
4144
4145   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4146   if (attr)
4147     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4148   if (lh == NULL)
4149     return;  /* No linetable, so no includes.  */
4150
4151   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4152   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4153
4154   free_line_header (lh);
4155 }
4156
4157 static hashval_t
4158 hash_signatured_type (const void *item)
4159 {
4160   const struct signatured_type *sig_type = item;
4161
4162   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4163   return sig_type->signature;
4164 }
4165
4166 static int
4167 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4168 {
4169   const struct signatured_type *lhs = item_lhs;
4170   const struct signatured_type *rhs = item_rhs;
4171
4172   return lhs->signature == rhs->signature;
4173 }
4174
4175 /* Allocate a hash table for signatured types.  */
4176
4177 static htab_t
4178 allocate_signatured_type_table (struct objfile *objfile)
4179 {
4180   return htab_create_alloc_ex (41,
4181                                hash_signatured_type,
4182                                eq_signatured_type,
4183                                NULL,
4184                                &objfile->objfile_obstack,
4185                                hashtab_obstack_allocate,
4186                                dummy_obstack_deallocate);
4187 }
4188
4189 /* A helper function to add a signatured type CU to a table.  */
4190
4191 static int
4192 add_signatured_type_cu_to_table (void **slot, void *datum)
4193 {
4194   struct signatured_type *sigt = *slot;
4195   struct signatured_type ***datap = datum;
4196
4197   **datap = sigt;
4198   ++*datap;
4199
4200   return 1;
4201 }
4202
4203 /* Create the hash table of all entries in the .debug_types
4204    (or .debug_types.dwo) section(s).
4205    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4206    otherwise it is NULL.
4207
4208    The result is a pointer to the hash table or NULL if there are no types.
4209
4210    Note: This function processes DWO files only, not DWP files.  */
4211
4212 static htab_t
4213 create_debug_types_hash_table (struct dwo_file *dwo_file,
4214                                VEC (dwarf2_section_info_def) *types)
4215 {
4216   struct objfile *objfile = dwarf2_per_objfile->objfile;
4217   htab_t types_htab = NULL;
4218   int ix;
4219   struct dwarf2_section_info *section;
4220   struct dwarf2_section_info *abbrev_section;
4221
4222   if (VEC_empty (dwarf2_section_info_def, types))
4223     return NULL;
4224
4225   abbrev_section = (dwo_file != NULL
4226                     ? &dwo_file->sections.abbrev
4227                     : &dwarf2_per_objfile->abbrev);
4228
4229   if (dwarf2_read_debug)
4230     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4231                         dwo_file ? ".dwo" : "",
4232                         bfd_get_filename (abbrev_section->asection->owner));
4233
4234   for (ix = 0;
4235        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4236        ++ix)
4237     {
4238       bfd *abfd;
4239       const gdb_byte *info_ptr, *end_ptr;
4240       struct dwarf2_section_info *abbrev_section;
4241
4242       dwarf2_read_section (objfile, section);
4243       info_ptr = section->buffer;
4244
4245       if (info_ptr == NULL)
4246         continue;
4247
4248       /* We can't set abfd until now because the section may be empty or
4249          not present, in which case section->asection will be NULL.  */
4250       abfd = section->asection->owner;
4251
4252       if (dwo_file)
4253         abbrev_section = &dwo_file->sections.abbrev;
4254       else
4255         abbrev_section = &dwarf2_per_objfile->abbrev;
4256
4257       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4258          because we don't need to read any dies: the signature is in the
4259          header.  */
4260
4261       end_ptr = info_ptr + section->size;
4262       while (info_ptr < end_ptr)
4263         {
4264           sect_offset offset;
4265           cu_offset type_offset_in_tu;
4266           ULONGEST signature;
4267           struct signatured_type *sig_type;
4268           struct dwo_unit *dwo_tu;
4269           void **slot;
4270           const gdb_byte *ptr = info_ptr;
4271           struct comp_unit_head header;
4272           unsigned int length;
4273
4274           offset.sect_off = ptr - section->buffer;
4275
4276           /* We need to read the type's signature in order to build the hash
4277              table, but we don't need anything else just yet.  */
4278
4279           ptr = read_and_check_type_unit_head (&header, section,
4280                                                abbrev_section, ptr,
4281                                                &signature, &type_offset_in_tu);
4282
4283           length = get_cu_length (&header);
4284
4285           /* Skip dummy type units.  */
4286           if (ptr >= info_ptr + length
4287               || peek_abbrev_code (abfd, ptr) == 0)
4288             {
4289               info_ptr += length;
4290               continue;
4291             }
4292
4293           if (types_htab == NULL)
4294             {
4295               if (dwo_file)
4296                 types_htab = allocate_dwo_unit_table (objfile);
4297               else
4298                 types_htab = allocate_signatured_type_table (objfile);
4299             }
4300
4301           if (dwo_file)
4302             {
4303               sig_type = NULL;
4304               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4305                                        struct dwo_unit);
4306               dwo_tu->dwo_file = dwo_file;
4307               dwo_tu->signature = signature;
4308               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4309               dwo_tu->section = section;
4310               dwo_tu->offset = offset;
4311               dwo_tu->length = length;
4312             }
4313           else
4314             {
4315               /* N.B.: type_offset is not usable if this type uses a DWO file.
4316                  The real type_offset is in the DWO file.  */
4317               dwo_tu = NULL;
4318               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4319                                          struct signatured_type);
4320               sig_type->signature = signature;
4321               sig_type->type_offset_in_tu = type_offset_in_tu;
4322               sig_type->per_cu.objfile = objfile;
4323               sig_type->per_cu.is_debug_types = 1;
4324               sig_type->per_cu.section = section;
4325               sig_type->per_cu.offset = offset;
4326               sig_type->per_cu.length = length;
4327             }
4328
4329           slot = htab_find_slot (types_htab,
4330                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4331                                  INSERT);
4332           gdb_assert (slot != NULL);
4333           if (*slot != NULL)
4334             {
4335               sect_offset dup_offset;
4336
4337               if (dwo_file)
4338                 {
4339                   const struct dwo_unit *dup_tu = *slot;
4340
4341                   dup_offset = dup_tu->offset;
4342                 }
4343               else
4344                 {
4345                   const struct signatured_type *dup_tu = *slot;
4346
4347                   dup_offset = dup_tu->per_cu.offset;
4348                 }
4349
4350               complaint (&symfile_complaints,
4351                          _("debug type entry at offset 0x%x is duplicate to"
4352                            " the entry at offset 0x%x, signature %s"),
4353                          offset.sect_off, dup_offset.sect_off,
4354                          hex_string (signature));
4355             }
4356           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4357
4358           if (dwarf2_read_debug)
4359             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4360                                 offset.sect_off,
4361                                 hex_string (signature));
4362
4363           info_ptr += length;
4364         }
4365     }
4366
4367   return types_htab;
4368 }
4369
4370 /* Create the hash table of all entries in the .debug_types section,
4371    and initialize all_type_units.
4372    The result is zero if there is an error (e.g. missing .debug_types section),
4373    otherwise non-zero.  */
4374
4375 static int
4376 create_all_type_units (struct objfile *objfile)
4377 {
4378   htab_t types_htab;
4379   struct signatured_type **iter;
4380
4381   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4382   if (types_htab == NULL)
4383     {
4384       dwarf2_per_objfile->signatured_types = NULL;
4385       return 0;
4386     }
4387
4388   dwarf2_per_objfile->signatured_types = types_htab;
4389
4390   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4391   dwarf2_per_objfile->all_type_units
4392     = xmalloc (dwarf2_per_objfile->n_type_units
4393                * sizeof (struct signatured_type *));
4394   iter = &dwarf2_per_objfile->all_type_units[0];
4395   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4396   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4397               == dwarf2_per_objfile->n_type_units);
4398
4399   return 1;
4400 }
4401
4402 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4403    Fill in SIG_ENTRY with DWO_ENTRY.  */
4404
4405 static void
4406 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4407                                   struct signatured_type *sig_entry,
4408                                   struct dwo_unit *dwo_entry)
4409 {
4410   /* Make sure we're not clobbering something we don't expect to.  */
4411   gdb_assert (! sig_entry->per_cu.queued);
4412   gdb_assert (sig_entry->per_cu.cu == NULL);
4413   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4414   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4415   gdb_assert (sig_entry->signature == dwo_entry->signature);
4416   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4417   gdb_assert (sig_entry->type_unit_group == NULL);
4418   gdb_assert (sig_entry->dwo_unit == NULL);
4419
4420   sig_entry->per_cu.section = dwo_entry->section;
4421   sig_entry->per_cu.offset = dwo_entry->offset;
4422   sig_entry->per_cu.length = dwo_entry->length;
4423   sig_entry->per_cu.reading_dwo_directly = 1;
4424   sig_entry->per_cu.objfile = objfile;
4425   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4426   sig_entry->dwo_unit = dwo_entry;
4427 }
4428
4429 /* Subroutine of lookup_signatured_type.
4430    If we haven't read the TU yet, create the signatured_type data structure
4431    for a TU to be read in directly from a DWO file, bypassing the stub.
4432    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4433    using .gdb_index, then when reading a CU we want to stay in the DWO file
4434    containing that CU.  Otherwise we could end up reading several other DWO
4435    files (due to comdat folding) to process the transitive closure of all the
4436    mentioned TUs, and that can be slow.  The current DWO file will have every
4437    type signature that it needs.
4438    We only do this for .gdb_index because in the psymtab case we already have
4439    to read all the DWOs to build the type unit groups.  */
4440
4441 static struct signatured_type *
4442 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4443 {
4444   struct objfile *objfile = dwarf2_per_objfile->objfile;
4445   struct dwo_file *dwo_file;
4446   struct dwo_unit find_dwo_entry, *dwo_entry;
4447   struct signatured_type find_sig_entry, *sig_entry;
4448
4449   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4450
4451   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4452      dwo_unit of the TU itself.  */
4453   dwo_file = cu->dwo_unit->dwo_file;
4454
4455   /* We only ever need to read in one copy of a signatured type.
4456      Just use the global signatured_types array.  If this is the first time
4457      we're reading this type, replace the recorded data from .gdb_index with
4458      this TU.  */
4459
4460   if (dwarf2_per_objfile->signatured_types == NULL)
4461     return NULL;
4462   find_sig_entry.signature = sig;
4463   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4464   if (sig_entry == NULL)
4465     return NULL;
4466
4467   /* We can get here with the TU already read, *or* in the process of being
4468      read.  Don't reassign it if that's the case.  Also note that if the TU is
4469      already being read, it may not have come from a DWO, the program may be
4470      a mix of Fission-compiled code and non-Fission-compiled code.  */
4471   /* Have we already tried to read this TU?  */
4472   if (sig_entry->per_cu.tu_read)
4473     return sig_entry;
4474
4475   /* Ok, this is the first time we're reading this TU.  */
4476   if (dwo_file->tus == NULL)
4477     return NULL;
4478   find_dwo_entry.signature = sig;
4479   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4480   if (dwo_entry == NULL)
4481     return NULL;
4482
4483   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4484   sig_entry->per_cu.tu_read = 1;
4485   return sig_entry;
4486 }
4487
4488 /* Subroutine of lookup_dwp_signatured_type.
4489    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4490
4491 static struct signatured_type *
4492 add_type_unit (ULONGEST sig)
4493 {
4494   struct objfile *objfile = dwarf2_per_objfile->objfile;
4495   int n_type_units = dwarf2_per_objfile->n_type_units;
4496   struct signatured_type *sig_type;
4497   void **slot;
4498
4499   ++n_type_units;
4500   dwarf2_per_objfile->all_type_units =
4501     xrealloc (dwarf2_per_objfile->all_type_units,
4502               n_type_units * sizeof (struct signatured_type *));
4503   dwarf2_per_objfile->n_type_units = n_type_units;
4504   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4505                              struct signatured_type);
4506   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4507   sig_type->signature = sig;
4508   sig_type->per_cu.is_debug_types = 1;
4509   sig_type->per_cu.v.quick =
4510     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4511                     struct dwarf2_per_cu_quick_data);
4512   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4513                          sig_type, INSERT);
4514   gdb_assert (*slot == NULL);
4515   *slot = sig_type;
4516   /* The rest of sig_type must be filled in by the caller.  */
4517   return sig_type;
4518 }
4519
4520 /* Subroutine of lookup_signatured_type.
4521    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4522    then try the DWP file.
4523    Normally this "can't happen", but if there's a bug in signature
4524    generation and/or the DWP file is built incorrectly, it can happen.
4525    Using the type directly from the DWP file means we don't have the stub
4526    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4527    not critical.  [Eventually the stub may go away for type units anyway.]  */
4528
4529 static struct signatured_type *
4530 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4531 {
4532   struct objfile *objfile = dwarf2_per_objfile->objfile;
4533   struct dwp_file *dwp_file = get_dwp_file ();
4534   struct dwo_unit *dwo_entry;
4535   struct signatured_type find_sig_entry, *sig_entry;
4536
4537   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4538   gdb_assert (dwp_file != NULL);
4539
4540   if (dwarf2_per_objfile->signatured_types != NULL)
4541     {
4542       find_sig_entry.signature = sig;
4543       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4544                              &find_sig_entry);
4545       if (sig_entry != NULL)
4546         return sig_entry;
4547     }
4548
4549   /* This is the "shouldn't happen" case.
4550      Try the DWP file and hope for the best.  */
4551   if (dwp_file->tus == NULL)
4552     return NULL;
4553   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4554                                  sig, 1 /* is_debug_types */);
4555   if (dwo_entry == NULL)
4556     return NULL;
4557
4558   sig_entry = add_type_unit (sig);
4559   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4560
4561   /* The caller will signal a complaint if we return NULL.
4562      Here we don't return NULL but we still want to complain.  */
4563   complaint (&symfile_complaints,
4564              _("Bad type signature %s referenced by %s at 0x%x,"
4565                " coping by using copy in DWP [in module %s]"),
4566              hex_string (sig),
4567              cu->per_cu->is_debug_types ? "TU" : "CU",
4568              cu->per_cu->offset.sect_off,
4569              objfile->name);
4570
4571   return sig_entry;
4572 }
4573
4574 /* Lookup a signature based type for DW_FORM_ref_sig8.
4575    Returns NULL if signature SIG is not present in the table.
4576    It is up to the caller to complain about this.  */
4577
4578 static struct signatured_type *
4579 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4580 {
4581   if (cu->dwo_unit
4582       && dwarf2_per_objfile->using_index)
4583     {
4584       /* We're in a DWO/DWP file, and we're using .gdb_index.
4585          These cases require special processing.  */
4586       if (get_dwp_file () == NULL)
4587         return lookup_dwo_signatured_type (cu, sig);
4588       else
4589         return lookup_dwp_signatured_type (cu, sig);
4590     }
4591   else
4592     {
4593       struct signatured_type find_entry, *entry;
4594
4595       if (dwarf2_per_objfile->signatured_types == NULL)
4596         return NULL;
4597       find_entry.signature = sig;
4598       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4599       return entry;
4600     }
4601 }
4602 \f
4603 /* Low level DIE reading support.  */
4604
4605 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4606
4607 static void
4608 init_cu_die_reader (struct die_reader_specs *reader,
4609                     struct dwarf2_cu *cu,
4610                     struct dwarf2_section_info *section,
4611                     struct dwo_file *dwo_file)
4612 {
4613   gdb_assert (section->readin && section->buffer != NULL);
4614   reader->abfd = section->asection->owner;
4615   reader->cu = cu;
4616   reader->dwo_file = dwo_file;
4617   reader->die_section = section;
4618   reader->buffer = section->buffer;
4619   reader->buffer_end = section->buffer + section->size;
4620   reader->comp_dir = NULL;
4621 }
4622
4623 /* Subroutine of init_cutu_and_read_dies to simplify it.
4624    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4625    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4626    already.
4627
4628    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4629    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4630    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4631    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4632    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4633    COMP_DIR must be non-NULL.
4634    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4635    are filled in with the info of the DIE from the DWO file.
4636    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4637    provided an abbrev table to use.
4638    The result is non-zero if a valid (non-dummy) DIE was found.  */
4639
4640 static int
4641 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4642                         struct dwo_unit *dwo_unit,
4643                         int abbrev_table_provided,
4644                         struct die_info *stub_comp_unit_die,
4645                         const char *stub_comp_dir,
4646                         struct die_reader_specs *result_reader,
4647                         const gdb_byte **result_info_ptr,
4648                         struct die_info **result_comp_unit_die,
4649                         int *result_has_children)
4650 {
4651   struct objfile *objfile = dwarf2_per_objfile->objfile;
4652   struct dwarf2_cu *cu = this_cu->cu;
4653   struct dwarf2_section_info *section;
4654   bfd *abfd;
4655   const gdb_byte *begin_info_ptr, *info_ptr;
4656   const char *comp_dir_string;
4657   ULONGEST signature; /* Or dwo_id.  */
4658   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4659   int i,num_extra_attrs;
4660   struct dwarf2_section_info *dwo_abbrev_section;
4661   struct attribute *attr;
4662   struct attribute comp_dir_attr;
4663   struct die_info *comp_unit_die;
4664
4665   /* Both can't be provided.  */
4666   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4667
4668   /* These attributes aren't processed until later:
4669      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4670      However, the attribute is found in the stub which we won't have later.
4671      In order to not impose this complication on the rest of the code,
4672      we read them here and copy them to the DWO CU/TU die.  */
4673
4674   stmt_list = NULL;
4675   low_pc = NULL;
4676   high_pc = NULL;
4677   ranges = NULL;
4678   comp_dir = NULL;
4679
4680   if (stub_comp_unit_die != NULL)
4681     {
4682       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4683          DWO file.  */
4684       if (! this_cu->is_debug_types)
4685         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4686       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4687       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4688       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4689       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4690
4691       /* There should be a DW_AT_addr_base attribute here (if needed).
4692          We need the value before we can process DW_FORM_GNU_addr_index.  */
4693       cu->addr_base = 0;
4694       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4695       if (attr)
4696         cu->addr_base = DW_UNSND (attr);
4697
4698       /* There should be a DW_AT_ranges_base attribute here (if needed).
4699          We need the value before we can process DW_AT_ranges.  */
4700       cu->ranges_base = 0;
4701       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4702       if (attr)
4703         cu->ranges_base = DW_UNSND (attr);
4704     }
4705   else if (stub_comp_dir != NULL)
4706     {
4707       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4708       comp_dir = (struct attribute *)
4709         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4710       comp_dir->name = DW_AT_comp_dir;
4711       comp_dir->form = DW_FORM_string;
4712       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4713       DW_STRING (comp_dir) = stub_comp_dir;
4714     }
4715
4716   /* Set up for reading the DWO CU/TU.  */
4717   cu->dwo_unit = dwo_unit;
4718   section = dwo_unit->section;
4719   dwarf2_read_section (objfile, section);
4720   abfd = section->asection->owner;
4721   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4722   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4723   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4724
4725   if (this_cu->is_debug_types)
4726     {
4727       ULONGEST header_signature;
4728       cu_offset type_offset_in_tu;
4729       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4730
4731       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4732                                                 dwo_abbrev_section,
4733                                                 info_ptr,
4734                                                 &header_signature,
4735                                                 &type_offset_in_tu);
4736       /* This is not an assert because it can be caused by bad debug info.  */
4737       if (sig_type->signature != header_signature)
4738         {
4739           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4740                    " TU at offset 0x%x [in module %s]"),
4741                  hex_string (sig_type->signature),
4742                  hex_string (header_signature),
4743                  dwo_unit->offset.sect_off,
4744                  bfd_get_filename (abfd));
4745         }
4746       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4747       /* For DWOs coming from DWP files, we don't know the CU length
4748          nor the type's offset in the TU until now.  */
4749       dwo_unit->length = get_cu_length (&cu->header);
4750       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4751
4752       /* Establish the type offset that can be used to lookup the type.
4753          For DWO files, we don't know it until now.  */
4754       sig_type->type_offset_in_section.sect_off =
4755         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4756     }
4757   else
4758     {
4759       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4760                                                 dwo_abbrev_section,
4761                                                 info_ptr, 0);
4762       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4763       /* For DWOs coming from DWP files, we don't know the CU length
4764          until now.  */
4765       dwo_unit->length = get_cu_length (&cu->header);
4766     }
4767
4768   /* Replace the CU's original abbrev table with the DWO's.
4769      Reminder: We can't read the abbrev table until we've read the header.  */
4770   if (abbrev_table_provided)
4771     {
4772       /* Don't free the provided abbrev table, the caller of
4773          init_cutu_and_read_dies owns it.  */
4774       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4775       /* Ensure the DWO abbrev table gets freed.  */
4776       make_cleanup (dwarf2_free_abbrev_table, cu);
4777     }
4778   else
4779     {
4780       dwarf2_free_abbrev_table (cu);
4781       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4782       /* Leave any existing abbrev table cleanup as is.  */
4783     }
4784
4785   /* Read in the die, but leave space to copy over the attributes
4786      from the stub.  This has the benefit of simplifying the rest of
4787      the code - all the work to maintain the illusion of a single
4788      DW_TAG_{compile,type}_unit DIE is done here.  */
4789   num_extra_attrs = ((stmt_list != NULL)
4790                      + (low_pc != NULL)
4791                      + (high_pc != NULL)
4792                      + (ranges != NULL)
4793                      + (comp_dir != NULL));
4794   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4795                               result_has_children, num_extra_attrs);
4796
4797   /* Copy over the attributes from the stub to the DIE we just read in.  */
4798   comp_unit_die = *result_comp_unit_die;
4799   i = comp_unit_die->num_attrs;
4800   if (stmt_list != NULL)
4801     comp_unit_die->attrs[i++] = *stmt_list;
4802   if (low_pc != NULL)
4803     comp_unit_die->attrs[i++] = *low_pc;
4804   if (high_pc != NULL)
4805     comp_unit_die->attrs[i++] = *high_pc;
4806   if (ranges != NULL)
4807     comp_unit_die->attrs[i++] = *ranges;
4808   if (comp_dir != NULL)
4809     comp_unit_die->attrs[i++] = *comp_dir;
4810   comp_unit_die->num_attrs += num_extra_attrs;
4811
4812   if (dwarf2_die_debug)
4813     {
4814       fprintf_unfiltered (gdb_stdlog,
4815                           "Read die from %s@0x%x of %s:\n",
4816                           bfd_section_name (abfd, section->asection),
4817                           (unsigned) (begin_info_ptr - section->buffer),
4818                           bfd_get_filename (abfd));
4819       dump_die (comp_unit_die, dwarf2_die_debug);
4820     }
4821
4822   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4823      TUs by skipping the stub and going directly to the entry in the DWO file.
4824      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4825      to get it via circuitous means.  Blech.  */
4826   if (comp_dir != NULL)
4827     result_reader->comp_dir = DW_STRING (comp_dir);
4828
4829   /* Skip dummy compilation units.  */
4830   if (info_ptr >= begin_info_ptr + dwo_unit->length
4831       || peek_abbrev_code (abfd, info_ptr) == 0)
4832     return 0;
4833
4834   *result_info_ptr = info_ptr;
4835   return 1;
4836 }
4837
4838 /* Subroutine of init_cutu_and_read_dies to simplify it.
4839    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4840    Returns NULL if the specified DWO unit cannot be found.  */
4841
4842 static struct dwo_unit *
4843 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4844                  struct die_info *comp_unit_die)
4845 {
4846   struct dwarf2_cu *cu = this_cu->cu;
4847   struct attribute *attr;
4848   ULONGEST signature;
4849   struct dwo_unit *dwo_unit;
4850   const char *comp_dir, *dwo_name;
4851
4852   gdb_assert (cu != NULL);
4853
4854   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4855   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4856   gdb_assert (attr != NULL);
4857   dwo_name = DW_STRING (attr);
4858   comp_dir = NULL;
4859   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4860   if (attr)
4861     comp_dir = DW_STRING (attr);
4862
4863   if (this_cu->is_debug_types)
4864     {
4865       struct signatured_type *sig_type;
4866
4867       /* Since this_cu is the first member of struct signatured_type,
4868          we can go from a pointer to one to a pointer to the other.  */
4869       sig_type = (struct signatured_type *) this_cu;
4870       signature = sig_type->signature;
4871       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4872     }
4873   else
4874     {
4875       struct attribute *attr;
4876
4877       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4878       if (! attr)
4879         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4880                  " [in module %s]"),
4881                dwo_name, this_cu->objfile->name);
4882       signature = DW_UNSND (attr);
4883       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4884                                        signature);
4885     }
4886
4887   return dwo_unit;
4888 }
4889
4890 /* Subroutine of init_cutu_and_read_dies to simplify it.
4891    Read a TU directly from a DWO file, bypassing the stub.  */
4892
4893 static void
4894 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4895                            die_reader_func_ftype *die_reader_func,
4896                            void *data)
4897 {
4898   struct dwarf2_cu *cu;
4899   struct signatured_type *sig_type;
4900   struct cleanup *cleanups, *free_cu_cleanup;
4901   struct die_reader_specs reader;
4902   const gdb_byte *info_ptr;
4903   struct die_info *comp_unit_die;
4904   int has_children;
4905
4906   /* Verify we can do the following downcast, and that we have the
4907      data we need.  */
4908   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4909   sig_type = (struct signatured_type *) this_cu;
4910   gdb_assert (sig_type->dwo_unit != NULL);
4911
4912   cleanups = make_cleanup (null_cleanup, NULL);
4913
4914   gdb_assert (this_cu->cu == NULL);
4915   cu = xmalloc (sizeof (*cu));
4916   init_one_comp_unit (cu, this_cu);
4917   /* If an error occurs while loading, release our storage.  */
4918   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4919
4920   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4921                               0 /* abbrev_table_provided */,
4922                               NULL /* stub_comp_unit_die */,
4923                               sig_type->dwo_unit->dwo_file->comp_dir,
4924                               &reader, &info_ptr,
4925                               &comp_unit_die, &has_children) == 0)
4926     {
4927       /* Dummy die.  */
4928       do_cleanups (cleanups);
4929       return;
4930     }
4931
4932   /* All the "real" work is done here.  */
4933   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4934
4935   /* This duplicates some code in init_cutu_and_read_dies,
4936      but the alternative is making the latter more complex.
4937      This function is only for the special case of using DWO files directly:
4938      no point in overly complicating the general case just to handle this.  */
4939   if (keep)
4940     {
4941       /* We've successfully allocated this compilation unit.  Let our
4942          caller clean it up when finished with it.  */
4943       discard_cleanups (free_cu_cleanup);
4944
4945       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4946          So we have to manually free the abbrev table.  */
4947       dwarf2_free_abbrev_table (cu);
4948
4949       /* Link this CU into read_in_chain.  */
4950       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4951       dwarf2_per_objfile->read_in_chain = this_cu;
4952     }
4953   else
4954     do_cleanups (free_cu_cleanup);
4955
4956   do_cleanups (cleanups);
4957 }
4958
4959 /* Initialize a CU (or TU) and read its DIEs.
4960    If the CU defers to a DWO file, read the DWO file as well.
4961
4962    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4963    Otherwise the table specified in the comp unit header is read in and used.
4964    This is an optimization for when we already have the abbrev table.
4965
4966    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4967    Otherwise, a new CU is allocated with xmalloc.
4968
4969    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4970    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4971
4972    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4973    linker) then DIE_READER_FUNC will not get called.  */
4974
4975 static void
4976 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4977                          struct abbrev_table *abbrev_table,
4978                          int use_existing_cu, int keep,
4979                          die_reader_func_ftype *die_reader_func,
4980                          void *data)
4981 {
4982   struct objfile *objfile = dwarf2_per_objfile->objfile;
4983   struct dwarf2_section_info *section = this_cu->section;
4984   bfd *abfd = section->asection->owner;
4985   struct dwarf2_cu *cu;
4986   const gdb_byte *begin_info_ptr, *info_ptr;
4987   struct die_reader_specs reader;
4988   struct die_info *comp_unit_die;
4989   int has_children;
4990   struct attribute *attr;
4991   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4992   struct signatured_type *sig_type = NULL;
4993   struct dwarf2_section_info *abbrev_section;
4994   /* Non-zero if CU currently points to a DWO file and we need to
4995      reread it.  When this happens we need to reread the skeleton die
4996      before we can reread the DWO file (this only applies to CUs, not TUs).  */
4997   int rereading_dwo_cu = 0;
4998
4999   if (dwarf2_die_debug)
5000     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5001                         this_cu->is_debug_types ? "type" : "comp",
5002                         this_cu->offset.sect_off);
5003
5004   if (use_existing_cu)
5005     gdb_assert (keep);
5006
5007   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5008      file (instead of going through the stub), short-circuit all of this.  */
5009   if (this_cu->reading_dwo_directly)
5010     {
5011       /* Narrow down the scope of possibilities to have to understand.  */
5012       gdb_assert (this_cu->is_debug_types);
5013       gdb_assert (abbrev_table == NULL);
5014       gdb_assert (!use_existing_cu);
5015       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5016       return;
5017     }
5018
5019   cleanups = make_cleanup (null_cleanup, NULL);
5020
5021   /* This is cheap if the section is already read in.  */
5022   dwarf2_read_section (objfile, section);
5023
5024   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5025
5026   abbrev_section = get_abbrev_section_for_cu (this_cu);
5027
5028   if (use_existing_cu && this_cu->cu != NULL)
5029     {
5030       cu = this_cu->cu;
5031
5032       /* If this CU is from a DWO file we need to start over, we need to
5033          refetch the attributes from the skeleton CU.
5034          This could be optimized by retrieving those attributes from when we
5035          were here the first time: the previous comp_unit_die was stored in
5036          comp_unit_obstack.  But there's no data yet that we need this
5037          optimization.  */
5038       if (cu->dwo_unit != NULL)
5039         rereading_dwo_cu = 1;
5040     }
5041   else
5042     {
5043       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5044       gdb_assert (this_cu->cu == NULL);
5045
5046       cu = xmalloc (sizeof (*cu));
5047       init_one_comp_unit (cu, this_cu);
5048
5049       /* If an error occurs while loading, release our storage.  */
5050       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5051     }
5052
5053   /* Get the header.  */
5054   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5055     {
5056       /* We already have the header, there's no need to read it in again.  */
5057       info_ptr += cu->header.first_die_offset.cu_off;
5058     }
5059   else
5060     {
5061       if (this_cu->is_debug_types)
5062         {
5063           ULONGEST signature;
5064           cu_offset type_offset_in_tu;
5065
5066           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5067                                                     abbrev_section, info_ptr,
5068                                                     &signature,
5069                                                     &type_offset_in_tu);
5070
5071           /* Since per_cu is the first member of struct signatured_type,
5072              we can go from a pointer to one to a pointer to the other.  */
5073           sig_type = (struct signatured_type *) this_cu;
5074           gdb_assert (sig_type->signature == signature);
5075           gdb_assert (sig_type->type_offset_in_tu.cu_off
5076                       == type_offset_in_tu.cu_off);
5077           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5078
5079           /* LENGTH has not been set yet for type units if we're
5080              using .gdb_index.  */
5081           this_cu->length = get_cu_length (&cu->header);
5082
5083           /* Establish the type offset that can be used to lookup the type.  */
5084           sig_type->type_offset_in_section.sect_off =
5085             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5086         }
5087       else
5088         {
5089           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5090                                                     abbrev_section,
5091                                                     info_ptr, 0);
5092
5093           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5094           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5095         }
5096     }
5097
5098   /* Skip dummy compilation units.  */
5099   if (info_ptr >= begin_info_ptr + this_cu->length
5100       || peek_abbrev_code (abfd, info_ptr) == 0)
5101     {
5102       do_cleanups (cleanups);
5103       return;
5104     }
5105
5106   /* If we don't have them yet, read the abbrevs for this compilation unit.
5107      And if we need to read them now, make sure they're freed when we're
5108      done.  Note that it's important that if the CU had an abbrev table
5109      on entry we don't free it when we're done: Somewhere up the call stack
5110      it may be in use.  */
5111   if (abbrev_table != NULL)
5112     {
5113       gdb_assert (cu->abbrev_table == NULL);
5114       gdb_assert (cu->header.abbrev_offset.sect_off
5115                   == abbrev_table->offset.sect_off);
5116       cu->abbrev_table = abbrev_table;
5117     }
5118   else if (cu->abbrev_table == NULL)
5119     {
5120       dwarf2_read_abbrevs (cu, abbrev_section);
5121       make_cleanup (dwarf2_free_abbrev_table, cu);
5122     }
5123   else if (rereading_dwo_cu)
5124     {
5125       dwarf2_free_abbrev_table (cu);
5126       dwarf2_read_abbrevs (cu, abbrev_section);
5127     }
5128
5129   /* Read the top level CU/TU die.  */
5130   init_cu_die_reader (&reader, cu, section, NULL);
5131   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5132
5133   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5134      from the DWO file.
5135      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5136      DWO CU, that this test will fail (the attribute will not be present).  */
5137   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5138   if (attr)
5139     {
5140       struct dwo_unit *dwo_unit;
5141       struct die_info *dwo_comp_unit_die;
5142
5143       if (has_children)
5144         {
5145           complaint (&symfile_complaints,
5146                      _("compilation unit with DW_AT_GNU_dwo_name"
5147                        " has children (offset 0x%x) [in module %s]"),
5148                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5149         }
5150       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5151       if (dwo_unit != NULL)
5152         {
5153           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5154                                       abbrev_table != NULL,
5155                                       comp_unit_die, NULL,
5156                                       &reader, &info_ptr,
5157                                       &dwo_comp_unit_die, &has_children) == 0)
5158             {
5159               /* Dummy die.  */
5160               do_cleanups (cleanups);
5161               return;
5162             }
5163           comp_unit_die = dwo_comp_unit_die;
5164         }
5165       else
5166         {
5167           /* Yikes, we couldn't find the rest of the DIE, we only have
5168              the stub.  A complaint has already been logged.  There's
5169              not much more we can do except pass on the stub DIE to
5170              die_reader_func.  We don't want to throw an error on bad
5171              debug info.  */
5172         }
5173     }
5174
5175   /* All of the above is setup for this call.  Yikes.  */
5176   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5177
5178   /* Done, clean up.  */
5179   if (free_cu_cleanup != NULL)
5180     {
5181       if (keep)
5182         {
5183           /* We've successfully allocated this compilation unit.  Let our
5184              caller clean it up when finished with it.  */
5185           discard_cleanups (free_cu_cleanup);
5186
5187           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5188              So we have to manually free the abbrev table.  */
5189           dwarf2_free_abbrev_table (cu);
5190
5191           /* Link this CU into read_in_chain.  */
5192           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5193           dwarf2_per_objfile->read_in_chain = this_cu;
5194         }
5195       else
5196         do_cleanups (free_cu_cleanup);
5197     }
5198
5199   do_cleanups (cleanups);
5200 }
5201
5202 /* Read CU/TU THIS_CU in section SECTION,
5203    but do not follow DW_AT_GNU_dwo_name if present.
5204    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5205    to have already done the lookup to find the DWO/DWP file).
5206
5207    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5208    THIS_CU->is_debug_types, but nothing else.
5209
5210    We fill in THIS_CU->length.
5211
5212    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5213    linker) then DIE_READER_FUNC will not get called.
5214
5215    THIS_CU->cu is always freed when done.
5216    This is done in order to not leave THIS_CU->cu in a state where we have
5217    to care whether it refers to the "main" CU or the DWO CU.  */
5218
5219 static void
5220 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5221                                    struct dwarf2_section_info *abbrev_section,
5222                                    struct dwo_file *dwo_file,
5223                                    die_reader_func_ftype *die_reader_func,
5224                                    void *data)
5225 {
5226   struct objfile *objfile = dwarf2_per_objfile->objfile;
5227   struct dwarf2_section_info *section = this_cu->section;
5228   bfd *abfd = section->asection->owner;
5229   struct dwarf2_cu cu;
5230   const gdb_byte *begin_info_ptr, *info_ptr;
5231   struct die_reader_specs reader;
5232   struct cleanup *cleanups;
5233   struct die_info *comp_unit_die;
5234   int has_children;
5235
5236   if (dwarf2_die_debug)
5237     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5238                         this_cu->is_debug_types ? "type" : "comp",
5239                         this_cu->offset.sect_off);
5240
5241   gdb_assert (this_cu->cu == NULL);
5242
5243   /* This is cheap if the section is already read in.  */
5244   dwarf2_read_section (objfile, section);
5245
5246   init_one_comp_unit (&cu, this_cu);
5247
5248   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5249
5250   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5251   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5252                                             abbrev_section, info_ptr,
5253                                             this_cu->is_debug_types);
5254
5255   this_cu->length = get_cu_length (&cu.header);
5256
5257   /* Skip dummy compilation units.  */
5258   if (info_ptr >= begin_info_ptr + this_cu->length
5259       || peek_abbrev_code (abfd, info_ptr) == 0)
5260     {
5261       do_cleanups (cleanups);
5262       return;
5263     }
5264
5265   dwarf2_read_abbrevs (&cu, abbrev_section);
5266   make_cleanup (dwarf2_free_abbrev_table, &cu);
5267
5268   init_cu_die_reader (&reader, &cu, section, dwo_file);
5269   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5270
5271   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5272
5273   do_cleanups (cleanups);
5274 }
5275
5276 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5277    does not lookup the specified DWO file.
5278    This cannot be used to read DWO files.
5279
5280    THIS_CU->cu is always freed when done.
5281    This is done in order to not leave THIS_CU->cu in a state where we have
5282    to care whether it refers to the "main" CU or the DWO CU.
5283    We can revisit this if the data shows there's a performance issue.  */
5284
5285 static void
5286 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5287                                 die_reader_func_ftype *die_reader_func,
5288                                 void *data)
5289 {
5290   init_cutu_and_read_dies_no_follow (this_cu,
5291                                      get_abbrev_section_for_cu (this_cu),
5292                                      NULL,
5293                                      die_reader_func, data);
5294 }
5295 \f
5296 /* Type Unit Groups.
5297
5298    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5299    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5300    so that all types coming from the same compilation (.o file) are grouped
5301    together.  A future step could be to put the types in the same symtab as
5302    the CU the types ultimately came from.  */
5303
5304 static hashval_t
5305 hash_type_unit_group (const void *item)
5306 {
5307   const struct type_unit_group *tu_group = item;
5308
5309   return hash_stmt_list_entry (&tu_group->hash);
5310 }
5311
5312 static int
5313 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5314 {
5315   const struct type_unit_group *lhs = item_lhs;
5316   const struct type_unit_group *rhs = item_rhs;
5317
5318   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5319 }
5320
5321 /* Allocate a hash table for type unit groups.  */
5322
5323 static htab_t
5324 allocate_type_unit_groups_table (void)
5325 {
5326   return htab_create_alloc_ex (3,
5327                                hash_type_unit_group,
5328                                eq_type_unit_group,
5329                                NULL,
5330                                &dwarf2_per_objfile->objfile->objfile_obstack,
5331                                hashtab_obstack_allocate,
5332                                dummy_obstack_deallocate);
5333 }
5334
5335 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5336    partial symtabs.  We combine several TUs per psymtab to not let the size
5337    of any one psymtab grow too big.  */
5338 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5339 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5340
5341 /* Helper routine for get_type_unit_group.
5342    Create the type_unit_group object used to hold one or more TUs.  */
5343
5344 static struct type_unit_group *
5345 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5346 {
5347   struct objfile *objfile = dwarf2_per_objfile->objfile;
5348   struct dwarf2_per_cu_data *per_cu;
5349   struct type_unit_group *tu_group;
5350
5351   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5352                              struct type_unit_group);
5353   per_cu = &tu_group->per_cu;
5354   per_cu->objfile = objfile;
5355
5356   if (dwarf2_per_objfile->using_index)
5357     {
5358       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5359                                         struct dwarf2_per_cu_quick_data);
5360     }
5361   else
5362     {
5363       unsigned int line_offset = line_offset_struct.sect_off;
5364       struct partial_symtab *pst;
5365       char *name;
5366
5367       /* Give the symtab a useful name for debug purposes.  */
5368       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5369         name = xstrprintf ("<type_units_%d>",
5370                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5371       else
5372         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5373
5374       pst = create_partial_symtab (per_cu, name);
5375       pst->anonymous = 1;
5376
5377       xfree (name);
5378     }
5379
5380   tu_group->hash.dwo_unit = cu->dwo_unit;
5381   tu_group->hash.line_offset = line_offset_struct;
5382
5383   return tu_group;
5384 }
5385
5386 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5387    STMT_LIST is a DW_AT_stmt_list attribute.  */
5388
5389 static struct type_unit_group *
5390 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5391 {
5392   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5393   struct type_unit_group *tu_group;
5394   void **slot;
5395   unsigned int line_offset;
5396   struct type_unit_group type_unit_group_for_lookup;
5397
5398   if (dwarf2_per_objfile->type_unit_groups == NULL)
5399     {
5400       dwarf2_per_objfile->type_unit_groups =
5401         allocate_type_unit_groups_table ();
5402     }
5403
5404   /* Do we need to create a new group, or can we use an existing one?  */
5405
5406   if (stmt_list)
5407     {
5408       line_offset = DW_UNSND (stmt_list);
5409       ++tu_stats->nr_symtab_sharers;
5410     }
5411   else
5412     {
5413       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5414          We can do various things here like create one group per TU or
5415          spread them over multiple groups to split up the expansion work.
5416          To avoid worst case scenarios (too many groups or too large groups)
5417          we, umm, group them in bunches.  */
5418       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5419                      | (tu_stats->nr_stmt_less_type_units
5420                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5421       ++tu_stats->nr_stmt_less_type_units;
5422     }
5423
5424   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5425   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5426   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5427                          &type_unit_group_for_lookup, INSERT);
5428   if (*slot != NULL)
5429     {
5430       tu_group = *slot;
5431       gdb_assert (tu_group != NULL);
5432     }
5433   else
5434     {
5435       sect_offset line_offset_struct;
5436
5437       line_offset_struct.sect_off = line_offset;
5438       tu_group = create_type_unit_group (cu, line_offset_struct);
5439       *slot = tu_group;
5440       ++tu_stats->nr_symtabs;
5441     }
5442
5443   return tu_group;
5444 }
5445
5446 /* Struct used to sort TUs by their abbreviation table offset.  */
5447
5448 struct tu_abbrev_offset
5449 {
5450   struct signatured_type *sig_type;
5451   sect_offset abbrev_offset;
5452 };
5453
5454 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5455
5456 static int
5457 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5458 {
5459   const struct tu_abbrev_offset * const *a = ap;
5460   const struct tu_abbrev_offset * const *b = bp;
5461   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5462   unsigned int boff = (*b)->abbrev_offset.sect_off;
5463
5464   return (aoff > boff) - (aoff < boff);
5465 }
5466
5467 /* A helper function to add a type_unit_group to a table.  */
5468
5469 static int
5470 add_type_unit_group_to_table (void **slot, void *datum)
5471 {
5472   struct type_unit_group *tu_group = *slot;
5473   struct type_unit_group ***datap = datum;
5474
5475   **datap = tu_group;
5476   ++*datap;
5477
5478   return 1;
5479 }
5480
5481 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5482    each one passing FUNC,DATA.
5483
5484    The efficiency is because we sort TUs by the abbrev table they use and
5485    only read each abbrev table once.  In one program there are 200K TUs
5486    sharing 8K abbrev tables.
5487
5488    The main purpose of this function is to support building the
5489    dwarf2_per_objfile->type_unit_groups table.
5490    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5491    can collapse the search space by grouping them by stmt_list.
5492    The savings can be significant, in the same program from above the 200K TUs
5493    share 8K stmt_list tables.
5494
5495    FUNC is expected to call get_type_unit_group, which will create the
5496    struct type_unit_group if necessary and add it to
5497    dwarf2_per_objfile->type_unit_groups.  */
5498
5499 static void
5500 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5501 {
5502   struct objfile *objfile = dwarf2_per_objfile->objfile;
5503   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5504   struct cleanup *cleanups;
5505   struct abbrev_table *abbrev_table;
5506   sect_offset abbrev_offset;
5507   struct tu_abbrev_offset *sorted_by_abbrev;
5508   struct type_unit_group **iter;
5509   int i;
5510
5511   /* It's up to the caller to not call us multiple times.  */
5512   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5513
5514   if (dwarf2_per_objfile->n_type_units == 0)
5515     return;
5516
5517   /* TUs typically share abbrev tables, and there can be way more TUs than
5518      abbrev tables.  Sort by abbrev table to reduce the number of times we
5519      read each abbrev table in.
5520      Alternatives are to punt or to maintain a cache of abbrev tables.
5521      This is simpler and efficient enough for now.
5522
5523      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5524      symtab to use).  Typically TUs with the same abbrev offset have the same
5525      stmt_list value too so in practice this should work well.
5526
5527      The basic algorithm here is:
5528
5529       sort TUs by abbrev table
5530       for each TU with same abbrev table:
5531         read abbrev table if first user
5532         read TU top level DIE
5533           [IWBN if DWO skeletons had DW_AT_stmt_list]
5534         call FUNC  */
5535
5536   if (dwarf2_read_debug)
5537     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5538
5539   /* Sort in a separate table to maintain the order of all_type_units
5540      for .gdb_index: TU indices directly index all_type_units.  */
5541   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5542                               dwarf2_per_objfile->n_type_units);
5543   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5544     {
5545       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5546
5547       sorted_by_abbrev[i].sig_type = sig_type;
5548       sorted_by_abbrev[i].abbrev_offset =
5549         read_abbrev_offset (sig_type->per_cu.section,
5550                             sig_type->per_cu.offset);
5551     }
5552   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5553   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5554          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5555
5556   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5557      called any number of times, so we don't reset tu_stats here.  */
5558
5559   abbrev_offset.sect_off = ~(unsigned) 0;
5560   abbrev_table = NULL;
5561   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5562
5563   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5564     {
5565       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5566
5567       /* Switch to the next abbrev table if necessary.  */
5568       if (abbrev_table == NULL
5569           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5570         {
5571           if (abbrev_table != NULL)
5572             {
5573               abbrev_table_free (abbrev_table);
5574               /* Reset to NULL in case abbrev_table_read_table throws
5575                  an error: abbrev_table_free_cleanup will get called.  */
5576               abbrev_table = NULL;
5577             }
5578           abbrev_offset = tu->abbrev_offset;
5579           abbrev_table =
5580             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5581                                      abbrev_offset);
5582           ++tu_stats->nr_uniq_abbrev_tables;
5583         }
5584
5585       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5586                                func, data);
5587     }
5588
5589   /* type_unit_groups can be NULL if there is an error in the debug info.
5590      Just create an empty table so the rest of gdb doesn't have to watch
5591      for this error case.  */
5592   if (dwarf2_per_objfile->type_unit_groups == NULL)
5593     {
5594       dwarf2_per_objfile->type_unit_groups =
5595         allocate_type_unit_groups_table ();
5596       dwarf2_per_objfile->n_type_unit_groups = 0;
5597     }
5598
5599   /* Create a vector of pointers to primary type units to make it easy to
5600      iterate over them and CUs.  See dw2_get_primary_cu.  */
5601   dwarf2_per_objfile->n_type_unit_groups =
5602     htab_elements (dwarf2_per_objfile->type_unit_groups);
5603   dwarf2_per_objfile->all_type_unit_groups =
5604     obstack_alloc (&objfile->objfile_obstack,
5605                    dwarf2_per_objfile->n_type_unit_groups
5606                    * sizeof (struct type_unit_group *));
5607   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5608   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5609                           add_type_unit_group_to_table, &iter);
5610   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5611               == dwarf2_per_objfile->n_type_unit_groups);
5612
5613   do_cleanups (cleanups);
5614
5615   if (dwarf2_read_debug)
5616     {
5617       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5618       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5619                           dwarf2_per_objfile->n_type_units);
5620       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5621                           tu_stats->nr_uniq_abbrev_tables);
5622       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5623                           tu_stats->nr_symtabs);
5624       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5625                           tu_stats->nr_symtab_sharers);
5626       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5627                           tu_stats->nr_stmt_less_type_units);
5628     }
5629 }
5630 \f
5631 /* Partial symbol tables.  */
5632
5633 /* Create a psymtab named NAME and assign it to PER_CU.
5634
5635    The caller must fill in the following details:
5636    dirname, textlow, texthigh.  */
5637
5638 static struct partial_symtab *
5639 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5640 {
5641   struct objfile *objfile = per_cu->objfile;
5642   struct partial_symtab *pst;
5643
5644   pst = start_psymtab_common (objfile, objfile->section_offsets,
5645                               name, 0,
5646                               objfile->global_psymbols.next,
5647                               objfile->static_psymbols.next);
5648
5649   pst->psymtabs_addrmap_supported = 1;
5650
5651   /* This is the glue that links PST into GDB's symbol API.  */
5652   pst->read_symtab_private = per_cu;
5653   pst->read_symtab = dwarf2_read_symtab;
5654   per_cu->v.psymtab = pst;
5655
5656   return pst;
5657 }
5658
5659 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5660    type.  */
5661
5662 struct process_psymtab_comp_unit_data
5663 {
5664   /* True if we are reading a DW_TAG_partial_unit.  */
5665
5666   int want_partial_unit;
5667
5668   /* The "pretend" language that is used if the CU doesn't declare a
5669      language.  */
5670
5671   enum language pretend_language;
5672 };
5673
5674 /* die_reader_func for process_psymtab_comp_unit.  */
5675
5676 static void
5677 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5678                                   const gdb_byte *info_ptr,
5679                                   struct die_info *comp_unit_die,
5680                                   int has_children,
5681                                   void *data)
5682 {
5683   struct dwarf2_cu *cu = reader->cu;
5684   struct objfile *objfile = cu->objfile;
5685   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5686   struct attribute *attr;
5687   CORE_ADDR baseaddr;
5688   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5689   struct partial_symtab *pst;
5690   int has_pc_info;
5691   const char *filename;
5692   struct process_psymtab_comp_unit_data *info = data;
5693
5694   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5695     return;
5696
5697   gdb_assert (! per_cu->is_debug_types);
5698
5699   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5700
5701   cu->list_in_scope = &file_symbols;
5702
5703   /* Allocate a new partial symbol table structure.  */
5704   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5705   if (attr == NULL || !DW_STRING (attr))
5706     filename = "";
5707   else
5708     filename = DW_STRING (attr);
5709
5710   pst = create_partial_symtab (per_cu, filename);
5711
5712   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5713   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5714   if (attr != NULL)
5715     pst->dirname = DW_STRING (attr);
5716
5717   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5718
5719   dwarf2_find_base_address (comp_unit_die, cu);
5720
5721   /* Possibly set the default values of LOWPC and HIGHPC from
5722      `DW_AT_ranges'.  */
5723   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5724                                       &best_highpc, cu, pst);
5725   if (has_pc_info == 1 && best_lowpc < best_highpc)
5726     /* Store the contiguous range if it is not empty; it can be empty for
5727        CUs with no code.  */
5728     addrmap_set_empty (objfile->psymtabs_addrmap,
5729                        best_lowpc + baseaddr,
5730                        best_highpc + baseaddr - 1, pst);
5731
5732   /* Check if comp unit has_children.
5733      If so, read the rest of the partial symbols from this comp unit.
5734      If not, there's no more debug_info for this comp unit.  */
5735   if (has_children)
5736     {
5737       struct partial_die_info *first_die;
5738       CORE_ADDR lowpc, highpc;
5739
5740       lowpc = ((CORE_ADDR) -1);
5741       highpc = ((CORE_ADDR) 0);
5742
5743       first_die = load_partial_dies (reader, info_ptr, 1);
5744
5745       scan_partial_symbols (first_die, &lowpc, &highpc,
5746                             ! has_pc_info, cu);
5747
5748       /* If we didn't find a lowpc, set it to highpc to avoid
5749          complaints from `maint check'.  */
5750       if (lowpc == ((CORE_ADDR) -1))
5751         lowpc = highpc;
5752
5753       /* If the compilation unit didn't have an explicit address range,
5754          then use the information extracted from its child dies.  */
5755       if (! has_pc_info)
5756         {
5757           best_lowpc = lowpc;
5758           best_highpc = highpc;
5759         }
5760     }
5761   pst->textlow = best_lowpc + baseaddr;
5762   pst->texthigh = best_highpc + baseaddr;
5763
5764   pst->n_global_syms = objfile->global_psymbols.next -
5765     (objfile->global_psymbols.list + pst->globals_offset);
5766   pst->n_static_syms = objfile->static_psymbols.next -
5767     (objfile->static_psymbols.list + pst->statics_offset);
5768   sort_pst_symbols (objfile, pst);
5769
5770   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5771     {
5772       int i;
5773       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5774       struct dwarf2_per_cu_data *iter;
5775
5776       /* Fill in 'dependencies' here; we fill in 'users' in a
5777          post-pass.  */
5778       pst->number_of_dependencies = len;
5779       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5780                                          len * sizeof (struct symtab *));
5781       for (i = 0;
5782            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5783                         i, iter);
5784            ++i)
5785         pst->dependencies[i] = iter->v.psymtab;
5786
5787       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5788     }
5789
5790   /* Get the list of files included in the current compilation unit,
5791      and build a psymtab for each of them.  */
5792   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5793
5794   if (dwarf2_read_debug)
5795     {
5796       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5797
5798       fprintf_unfiltered (gdb_stdlog,
5799                           "Psymtab for %s unit @0x%x: %s - %s"
5800                           ", %d global, %d static syms\n",
5801                           per_cu->is_debug_types ? "type" : "comp",
5802                           per_cu->offset.sect_off,
5803                           paddress (gdbarch, pst->textlow),
5804                           paddress (gdbarch, pst->texthigh),
5805                           pst->n_global_syms, pst->n_static_syms);
5806     }
5807 }
5808
5809 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5810    Process compilation unit THIS_CU for a psymtab.  */
5811
5812 static void
5813 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5814                            int want_partial_unit,
5815                            enum language pretend_language)
5816 {
5817   struct process_psymtab_comp_unit_data info;
5818
5819   /* If this compilation unit was already read in, free the
5820      cached copy in order to read it in again.  This is
5821      necessary because we skipped some symbols when we first
5822      read in the compilation unit (see load_partial_dies).
5823      This problem could be avoided, but the benefit is unclear.  */
5824   if (this_cu->cu != NULL)
5825     free_one_cached_comp_unit (this_cu);
5826
5827   gdb_assert (! this_cu->is_debug_types);
5828   info.want_partial_unit = want_partial_unit;
5829   info.pretend_language = pretend_language;
5830   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5831                            process_psymtab_comp_unit_reader,
5832                            &info);
5833
5834   /* Age out any secondary CUs.  */
5835   age_cached_comp_units ();
5836 }
5837
5838 /* Reader function for build_type_psymtabs.  */
5839
5840 static void
5841 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5842                             const gdb_byte *info_ptr,
5843                             struct die_info *type_unit_die,
5844                             int has_children,
5845                             void *data)
5846 {
5847   struct objfile *objfile = dwarf2_per_objfile->objfile;
5848   struct dwarf2_cu *cu = reader->cu;
5849   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5850   struct signatured_type *sig_type;
5851   struct type_unit_group *tu_group;
5852   struct attribute *attr;
5853   struct partial_die_info *first_die;
5854   CORE_ADDR lowpc, highpc;
5855   struct partial_symtab *pst;
5856
5857   gdb_assert (data == NULL);
5858   gdb_assert (per_cu->is_debug_types);
5859   sig_type = (struct signatured_type *) per_cu;
5860
5861   if (! has_children)
5862     return;
5863
5864   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5865   tu_group = get_type_unit_group (cu, attr);
5866
5867   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5868
5869   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5870   cu->list_in_scope = &file_symbols;
5871   pst = create_partial_symtab (per_cu, "");
5872   pst->anonymous = 1;
5873
5874   first_die = load_partial_dies (reader, info_ptr, 1);
5875
5876   lowpc = (CORE_ADDR) -1;
5877   highpc = (CORE_ADDR) 0;
5878   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5879
5880   pst->n_global_syms = objfile->global_psymbols.next -
5881     (objfile->global_psymbols.list + pst->globals_offset);
5882   pst->n_static_syms = objfile->static_psymbols.next -
5883     (objfile->static_psymbols.list + pst->statics_offset);
5884   sort_pst_symbols (objfile, pst);
5885 }
5886
5887 /* Traversal function for build_type_psymtabs.  */
5888
5889 static int
5890 build_type_psymtab_dependencies (void **slot, void *info)
5891 {
5892   struct objfile *objfile = dwarf2_per_objfile->objfile;
5893   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5894   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5895   struct partial_symtab *pst = per_cu->v.psymtab;
5896   int len = VEC_length (sig_type_ptr, tu_group->tus);
5897   struct signatured_type *iter;
5898   int i;
5899
5900   gdb_assert (len > 0);
5901   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5902
5903   pst->number_of_dependencies = len;
5904   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5905                                      len * sizeof (struct psymtab *));
5906   for (i = 0;
5907        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5908        ++i)
5909     {
5910       gdb_assert (iter->per_cu.is_debug_types);
5911       pst->dependencies[i] = iter->per_cu.v.psymtab;
5912       iter->type_unit_group = tu_group;
5913     }
5914
5915   VEC_free (sig_type_ptr, tu_group->tus);
5916
5917   return 1;
5918 }
5919
5920 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5921    Build partial symbol tables for the .debug_types comp-units.  */
5922
5923 static void
5924 build_type_psymtabs (struct objfile *objfile)
5925 {
5926   if (! create_all_type_units (objfile))
5927     return;
5928
5929   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5930
5931   /* Now that all TUs have been processed we can fill in the dependencies.  */
5932   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5933                           build_type_psymtab_dependencies, NULL);
5934 }
5935
5936 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5937
5938 static void
5939 psymtabs_addrmap_cleanup (void *o)
5940 {
5941   struct objfile *objfile = o;
5942
5943   objfile->psymtabs_addrmap = NULL;
5944 }
5945
5946 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5947
5948 static void
5949 set_partial_user (struct objfile *objfile)
5950 {
5951   int i;
5952
5953   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5954     {
5955       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5956       struct partial_symtab *pst = per_cu->v.psymtab;
5957       int j;
5958
5959       if (pst == NULL)
5960         continue;
5961
5962       for (j = 0; j < pst->number_of_dependencies; ++j)
5963         {
5964           /* Set the 'user' field only if it is not already set.  */
5965           if (pst->dependencies[j]->user == NULL)
5966             pst->dependencies[j]->user = pst;
5967         }
5968     }
5969 }
5970
5971 /* Build the partial symbol table by doing a quick pass through the
5972    .debug_info and .debug_abbrev sections.  */
5973
5974 static void
5975 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5976 {
5977   struct cleanup *back_to, *addrmap_cleanup;
5978   struct obstack temp_obstack;
5979   int i;
5980
5981   if (dwarf2_read_debug)
5982     {
5983       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5984                           objfile->name);
5985     }
5986
5987   dwarf2_per_objfile->reading_partial_symbols = 1;
5988
5989   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5990
5991   /* Any cached compilation units will be linked by the per-objfile
5992      read_in_chain.  Make sure to free them when we're done.  */
5993   back_to = make_cleanup (free_cached_comp_units, NULL);
5994
5995   build_type_psymtabs (objfile);
5996
5997   create_all_comp_units (objfile);
5998
5999   /* Create a temporary address map on a temporary obstack.  We later
6000      copy this to the final obstack.  */
6001   obstack_init (&temp_obstack);
6002   make_cleanup_obstack_free (&temp_obstack);
6003   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6004   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6005
6006   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6007     {
6008       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6009
6010       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6011     }
6012
6013   set_partial_user (objfile);
6014
6015   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6016                                                     &objfile->objfile_obstack);
6017   discard_cleanups (addrmap_cleanup);
6018
6019   do_cleanups (back_to);
6020
6021   if (dwarf2_read_debug)
6022     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6023                         objfile->name);
6024 }
6025
6026 /* die_reader_func for load_partial_comp_unit.  */
6027
6028 static void
6029 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6030                                const gdb_byte *info_ptr,
6031                                struct die_info *comp_unit_die,
6032                                int has_children,
6033                                void *data)
6034 {
6035   struct dwarf2_cu *cu = reader->cu;
6036
6037   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6038
6039   /* Check if comp unit has_children.
6040      If so, read the rest of the partial symbols from this comp unit.
6041      If not, there's no more debug_info for this comp unit.  */
6042   if (has_children)
6043     load_partial_dies (reader, info_ptr, 0);
6044 }
6045
6046 /* Load the partial DIEs for a secondary CU into memory.
6047    This is also used when rereading a primary CU with load_all_dies.  */
6048
6049 static void
6050 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6051 {
6052   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6053                            load_partial_comp_unit_reader, NULL);
6054 }
6055
6056 static void
6057 read_comp_units_from_section (struct objfile *objfile,
6058                               struct dwarf2_section_info *section,
6059                               unsigned int is_dwz,
6060                               int *n_allocated,
6061                               int *n_comp_units,
6062                               struct dwarf2_per_cu_data ***all_comp_units)
6063 {
6064   const gdb_byte *info_ptr;
6065   bfd *abfd = section->asection->owner;
6066
6067   if (dwarf2_read_debug)
6068     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6069                         section->asection->name, bfd_get_filename (abfd));
6070
6071   dwarf2_read_section (objfile, section);
6072
6073   info_ptr = section->buffer;
6074
6075   while (info_ptr < section->buffer + section->size)
6076     {
6077       unsigned int length, initial_length_size;
6078       struct dwarf2_per_cu_data *this_cu;
6079       sect_offset offset;
6080
6081       offset.sect_off = info_ptr - section->buffer;
6082
6083       /* Read just enough information to find out where the next
6084          compilation unit is.  */
6085       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6086
6087       /* Save the compilation unit for later lookup.  */
6088       this_cu = obstack_alloc (&objfile->objfile_obstack,
6089                                sizeof (struct dwarf2_per_cu_data));
6090       memset (this_cu, 0, sizeof (*this_cu));
6091       this_cu->offset = offset;
6092       this_cu->length = length + initial_length_size;
6093       this_cu->is_dwz = is_dwz;
6094       this_cu->objfile = objfile;
6095       this_cu->section = section;
6096
6097       if (*n_comp_units == *n_allocated)
6098         {
6099           *n_allocated *= 2;
6100           *all_comp_units = xrealloc (*all_comp_units,
6101                                       *n_allocated
6102                                       * sizeof (struct dwarf2_per_cu_data *));
6103         }
6104       (*all_comp_units)[*n_comp_units] = this_cu;
6105       ++*n_comp_units;
6106
6107       info_ptr = info_ptr + this_cu->length;
6108     }
6109 }
6110
6111 /* Create a list of all compilation units in OBJFILE.
6112    This is only done for -readnow and building partial symtabs.  */
6113
6114 static void
6115 create_all_comp_units (struct objfile *objfile)
6116 {
6117   int n_allocated;
6118   int n_comp_units;
6119   struct dwarf2_per_cu_data **all_comp_units;
6120   struct dwz_file *dwz;
6121
6122   n_comp_units = 0;
6123   n_allocated = 10;
6124   all_comp_units = xmalloc (n_allocated
6125                             * sizeof (struct dwarf2_per_cu_data *));
6126
6127   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6128                                 &n_allocated, &n_comp_units, &all_comp_units);
6129
6130   dwz = dwarf2_get_dwz_file ();
6131   if (dwz != NULL)
6132     read_comp_units_from_section (objfile, &dwz->info, 1,
6133                                   &n_allocated, &n_comp_units,
6134                                   &all_comp_units);
6135
6136   dwarf2_per_objfile->all_comp_units
6137     = obstack_alloc (&objfile->objfile_obstack,
6138                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6139   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6140           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6141   xfree (all_comp_units);
6142   dwarf2_per_objfile->n_comp_units = n_comp_units;
6143 }
6144
6145 /* Process all loaded DIEs for compilation unit CU, starting at
6146    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6147    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6148    DW_AT_ranges).  If NEED_PC is set, then this function will set
6149    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6150    and record the covered ranges in the addrmap.  */
6151
6152 static void
6153 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6154                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6155 {
6156   struct partial_die_info *pdi;
6157
6158   /* Now, march along the PDI's, descending into ones which have
6159      interesting children but skipping the children of the other ones,
6160      until we reach the end of the compilation unit.  */
6161
6162   pdi = first_die;
6163
6164   while (pdi != NULL)
6165     {
6166       fixup_partial_die (pdi, cu);
6167
6168       /* Anonymous namespaces or modules have no name but have interesting
6169          children, so we need to look at them.  Ditto for anonymous
6170          enums.  */
6171
6172       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6173           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6174           || pdi->tag == DW_TAG_imported_unit)
6175         {
6176           switch (pdi->tag)
6177             {
6178             case DW_TAG_subprogram:
6179               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6180               break;
6181             case DW_TAG_constant:
6182             case DW_TAG_variable:
6183             case DW_TAG_typedef:
6184             case DW_TAG_union_type:
6185               if (!pdi->is_declaration)
6186                 {
6187                   add_partial_symbol (pdi, cu);
6188                 }
6189               break;
6190             case DW_TAG_class_type:
6191             case DW_TAG_interface_type:
6192             case DW_TAG_structure_type:
6193               if (!pdi->is_declaration)
6194                 {
6195                   add_partial_symbol (pdi, cu);
6196                 }
6197               break;
6198             case DW_TAG_enumeration_type:
6199               if (!pdi->is_declaration)
6200                 add_partial_enumeration (pdi, cu);
6201               break;
6202             case DW_TAG_base_type:
6203             case DW_TAG_subrange_type:
6204               /* File scope base type definitions are added to the partial
6205                  symbol table.  */
6206               add_partial_symbol (pdi, cu);
6207               break;
6208             case DW_TAG_namespace:
6209               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6210               break;
6211             case DW_TAG_module:
6212               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6213               break;
6214             case DW_TAG_imported_unit:
6215               {
6216                 struct dwarf2_per_cu_data *per_cu;
6217
6218                 /* For now we don't handle imported units in type units.  */
6219                 if (cu->per_cu->is_debug_types)
6220                   {
6221                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6222                              " supported in type units [in module %s]"),
6223                            cu->objfile->name);
6224                   }
6225
6226                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6227                                                            pdi->is_dwz,
6228                                                            cu->objfile);
6229
6230                 /* Go read the partial unit, if needed.  */
6231                 if (per_cu->v.psymtab == NULL)
6232                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6233
6234                 VEC_safe_push (dwarf2_per_cu_ptr,
6235                                cu->per_cu->imported_symtabs, per_cu);
6236               }
6237               break;
6238             default:
6239               break;
6240             }
6241         }
6242
6243       /* If the die has a sibling, skip to the sibling.  */
6244
6245       pdi = pdi->die_sibling;
6246     }
6247 }
6248
6249 /* Functions used to compute the fully scoped name of a partial DIE.
6250
6251    Normally, this is simple.  For C++, the parent DIE's fully scoped
6252    name is concatenated with "::" and the partial DIE's name.  For
6253    Java, the same thing occurs except that "." is used instead of "::".
6254    Enumerators are an exception; they use the scope of their parent
6255    enumeration type, i.e. the name of the enumeration type is not
6256    prepended to the enumerator.
6257
6258    There are two complexities.  One is DW_AT_specification; in this
6259    case "parent" means the parent of the target of the specification,
6260    instead of the direct parent of the DIE.  The other is compilers
6261    which do not emit DW_TAG_namespace; in this case we try to guess
6262    the fully qualified name of structure types from their members'
6263    linkage names.  This must be done using the DIE's children rather
6264    than the children of any DW_AT_specification target.  We only need
6265    to do this for structures at the top level, i.e. if the target of
6266    any DW_AT_specification (if any; otherwise the DIE itself) does not
6267    have a parent.  */
6268
6269 /* Compute the scope prefix associated with PDI's parent, in
6270    compilation unit CU.  The result will be allocated on CU's
6271    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6272    field.  NULL is returned if no prefix is necessary.  */
6273 static const char *
6274 partial_die_parent_scope (struct partial_die_info *pdi,
6275                           struct dwarf2_cu *cu)
6276 {
6277   const char *grandparent_scope;
6278   struct partial_die_info *parent, *real_pdi;
6279
6280   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6281      then this means the parent of the specification DIE.  */
6282
6283   real_pdi = pdi;
6284   while (real_pdi->has_specification)
6285     real_pdi = find_partial_die (real_pdi->spec_offset,
6286                                  real_pdi->spec_is_dwz, cu);
6287
6288   parent = real_pdi->die_parent;
6289   if (parent == NULL)
6290     return NULL;
6291
6292   if (parent->scope_set)
6293     return parent->scope;
6294
6295   fixup_partial_die (parent, cu);
6296
6297   grandparent_scope = partial_die_parent_scope (parent, cu);
6298
6299   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6300      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6301      Work around this problem here.  */
6302   if (cu->language == language_cplus
6303       && parent->tag == DW_TAG_namespace
6304       && strcmp (parent->name, "::") == 0
6305       && grandparent_scope == NULL)
6306     {
6307       parent->scope = NULL;
6308       parent->scope_set = 1;
6309       return NULL;
6310     }
6311
6312   if (pdi->tag == DW_TAG_enumerator)
6313     /* Enumerators should not get the name of the enumeration as a prefix.  */
6314     parent->scope = grandparent_scope;
6315   else if (parent->tag == DW_TAG_namespace
6316       || parent->tag == DW_TAG_module
6317       || parent->tag == DW_TAG_structure_type
6318       || parent->tag == DW_TAG_class_type
6319       || parent->tag == DW_TAG_interface_type
6320       || parent->tag == DW_TAG_union_type
6321       || parent->tag == DW_TAG_enumeration_type)
6322     {
6323       if (grandparent_scope == NULL)
6324         parent->scope = parent->name;
6325       else
6326         parent->scope = typename_concat (&cu->comp_unit_obstack,
6327                                          grandparent_scope,
6328                                          parent->name, 0, cu);
6329     }
6330   else
6331     {
6332       /* FIXME drow/2004-04-01: What should we be doing with
6333          function-local names?  For partial symbols, we should probably be
6334          ignoring them.  */
6335       complaint (&symfile_complaints,
6336                  _("unhandled containing DIE tag %d for DIE at %d"),
6337                  parent->tag, pdi->offset.sect_off);
6338       parent->scope = grandparent_scope;
6339     }
6340
6341   parent->scope_set = 1;
6342   return parent->scope;
6343 }
6344
6345 /* Return the fully scoped name associated with PDI, from compilation unit
6346    CU.  The result will be allocated with malloc.  */
6347
6348 static char *
6349 partial_die_full_name (struct partial_die_info *pdi,
6350                        struct dwarf2_cu *cu)
6351 {
6352   const char *parent_scope;
6353
6354   /* If this is a template instantiation, we can not work out the
6355      template arguments from partial DIEs.  So, unfortunately, we have
6356      to go through the full DIEs.  At least any work we do building
6357      types here will be reused if full symbols are loaded later.  */
6358   if (pdi->has_template_arguments)
6359     {
6360       fixup_partial_die (pdi, cu);
6361
6362       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6363         {
6364           struct die_info *die;
6365           struct attribute attr;
6366           struct dwarf2_cu *ref_cu = cu;
6367
6368           /* DW_FORM_ref_addr is using section offset.  */
6369           attr.name = 0;
6370           attr.form = DW_FORM_ref_addr;
6371           attr.u.unsnd = pdi->offset.sect_off;
6372           die = follow_die_ref (NULL, &attr, &ref_cu);
6373
6374           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6375         }
6376     }
6377
6378   parent_scope = partial_die_parent_scope (pdi, cu);
6379   if (parent_scope == NULL)
6380     return NULL;
6381   else
6382     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6383 }
6384
6385 static void
6386 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6387 {
6388   struct objfile *objfile = cu->objfile;
6389   CORE_ADDR addr = 0;
6390   const char *actual_name = NULL;
6391   CORE_ADDR baseaddr;
6392   char *built_actual_name;
6393
6394   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6395
6396   built_actual_name = partial_die_full_name (pdi, cu);
6397   if (built_actual_name != NULL)
6398     actual_name = built_actual_name;
6399
6400   if (actual_name == NULL)
6401     actual_name = pdi->name;
6402
6403   switch (pdi->tag)
6404     {
6405     case DW_TAG_subprogram:
6406       if (pdi->is_external || cu->language == language_ada)
6407         {
6408           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6409              of the global scope.  But in Ada, we want to be able to access
6410              nested procedures globally.  So all Ada subprograms are stored
6411              in the global scope.  */
6412           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6413              mst_text, objfile); */
6414           add_psymbol_to_list (actual_name, strlen (actual_name),
6415                                built_actual_name != NULL,
6416                                VAR_DOMAIN, LOC_BLOCK,
6417                                &objfile->global_psymbols,
6418                                0, pdi->lowpc + baseaddr,
6419                                cu->language, objfile);
6420         }
6421       else
6422         {
6423           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6424              mst_file_text, objfile); */
6425           add_psymbol_to_list (actual_name, strlen (actual_name),
6426                                built_actual_name != NULL,
6427                                VAR_DOMAIN, LOC_BLOCK,
6428                                &objfile->static_psymbols,
6429                                0, pdi->lowpc + baseaddr,
6430                                cu->language, objfile);
6431         }
6432       break;
6433     case DW_TAG_constant:
6434       {
6435         struct psymbol_allocation_list *list;
6436
6437         if (pdi->is_external)
6438           list = &objfile->global_psymbols;
6439         else
6440           list = &objfile->static_psymbols;
6441         add_psymbol_to_list (actual_name, strlen (actual_name),
6442                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6443                              list, 0, 0, cu->language, objfile);
6444       }
6445       break;
6446     case DW_TAG_variable:
6447       if (pdi->d.locdesc)
6448         addr = decode_locdesc (pdi->d.locdesc, cu);
6449
6450       if (pdi->d.locdesc
6451           && addr == 0
6452           && !dwarf2_per_objfile->has_section_at_zero)
6453         {
6454           /* A global or static variable may also have been stripped
6455              out by the linker if unused, in which case its address
6456              will be nullified; do not add such variables into partial
6457              symbol table then.  */
6458         }
6459       else if (pdi->is_external)
6460         {
6461           /* Global Variable.
6462              Don't enter into the minimal symbol tables as there is
6463              a minimal symbol table entry from the ELF symbols already.
6464              Enter into partial symbol table if it has a location
6465              descriptor or a type.
6466              If the location descriptor is missing, new_symbol will create
6467              a LOC_UNRESOLVED symbol, the address of the variable will then
6468              be determined from the minimal symbol table whenever the variable
6469              is referenced.
6470              The address for the partial symbol table entry is not
6471              used by GDB, but it comes in handy for debugging partial symbol
6472              table building.  */
6473
6474           if (pdi->d.locdesc || pdi->has_type)
6475             add_psymbol_to_list (actual_name, strlen (actual_name),
6476                                  built_actual_name != NULL,
6477                                  VAR_DOMAIN, LOC_STATIC,
6478                                  &objfile->global_psymbols,
6479                                  0, addr + baseaddr,
6480                                  cu->language, objfile);
6481         }
6482       else
6483         {
6484           /* Static Variable.  Skip symbols without location descriptors.  */
6485           if (pdi->d.locdesc == NULL)
6486             {
6487               xfree (built_actual_name);
6488               return;
6489             }
6490           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6491              mst_file_data, objfile); */
6492           add_psymbol_to_list (actual_name, strlen (actual_name),
6493                                built_actual_name != NULL,
6494                                VAR_DOMAIN, LOC_STATIC,
6495                                &objfile->static_psymbols,
6496                                0, addr + baseaddr,
6497                                cu->language, objfile);
6498         }
6499       break;
6500     case DW_TAG_typedef:
6501     case DW_TAG_base_type:
6502     case DW_TAG_subrange_type:
6503       add_psymbol_to_list (actual_name, strlen (actual_name),
6504                            built_actual_name != NULL,
6505                            VAR_DOMAIN, LOC_TYPEDEF,
6506                            &objfile->static_psymbols,
6507                            0, (CORE_ADDR) 0, cu->language, objfile);
6508       break;
6509     case DW_TAG_namespace:
6510       add_psymbol_to_list (actual_name, strlen (actual_name),
6511                            built_actual_name != NULL,
6512                            VAR_DOMAIN, LOC_TYPEDEF,
6513                            &objfile->global_psymbols,
6514                            0, (CORE_ADDR) 0, cu->language, objfile);
6515       break;
6516     case DW_TAG_class_type:
6517     case DW_TAG_interface_type:
6518     case DW_TAG_structure_type:
6519     case DW_TAG_union_type:
6520     case DW_TAG_enumeration_type:
6521       /* Skip external references.  The DWARF standard says in the section
6522          about "Structure, Union, and Class Type Entries": "An incomplete
6523          structure, union or class type is represented by a structure,
6524          union or class entry that does not have a byte size attribute
6525          and that has a DW_AT_declaration attribute."  */
6526       if (!pdi->has_byte_size && pdi->is_declaration)
6527         {
6528           xfree (built_actual_name);
6529           return;
6530         }
6531
6532       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6533          static vs. global.  */
6534       add_psymbol_to_list (actual_name, strlen (actual_name),
6535                            built_actual_name != NULL,
6536                            STRUCT_DOMAIN, LOC_TYPEDEF,
6537                            (cu->language == language_cplus
6538                             || cu->language == language_java)
6539                            ? &objfile->global_psymbols
6540                            : &objfile->static_psymbols,
6541                            0, (CORE_ADDR) 0, cu->language, objfile);
6542
6543       break;
6544     case DW_TAG_enumerator:
6545       add_psymbol_to_list (actual_name, strlen (actual_name),
6546                            built_actual_name != NULL,
6547                            VAR_DOMAIN, LOC_CONST,
6548                            (cu->language == language_cplus
6549                             || cu->language == language_java)
6550                            ? &objfile->global_psymbols
6551                            : &objfile->static_psymbols,
6552                            0, (CORE_ADDR) 0, cu->language, objfile);
6553       break;
6554     default:
6555       break;
6556     }
6557
6558   xfree (built_actual_name);
6559 }
6560
6561 /* Read a partial die corresponding to a namespace; also, add a symbol
6562    corresponding to that namespace to the symbol table.  NAMESPACE is
6563    the name of the enclosing namespace.  */
6564
6565 static void
6566 add_partial_namespace (struct partial_die_info *pdi,
6567                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6568                        int need_pc, struct dwarf2_cu *cu)
6569 {
6570   /* Add a symbol for the namespace.  */
6571
6572   add_partial_symbol (pdi, cu);
6573
6574   /* Now scan partial symbols in that namespace.  */
6575
6576   if (pdi->has_children)
6577     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6578 }
6579
6580 /* Read a partial die corresponding to a Fortran module.  */
6581
6582 static void
6583 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6584                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6585 {
6586   /* Now scan partial symbols in that module.  */
6587
6588   if (pdi->has_children)
6589     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6590 }
6591
6592 /* Read a partial die corresponding to a subprogram and create a partial
6593    symbol for that subprogram.  When the CU language allows it, this
6594    routine also defines a partial symbol for each nested subprogram
6595    that this subprogram contains.
6596
6597    DIE my also be a lexical block, in which case we simply search
6598    recursively for suprograms defined inside that lexical block.
6599    Again, this is only performed when the CU language allows this
6600    type of definitions.  */
6601
6602 static void
6603 add_partial_subprogram (struct partial_die_info *pdi,
6604                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6605                         int need_pc, struct dwarf2_cu *cu)
6606 {
6607   if (pdi->tag == DW_TAG_subprogram)
6608     {
6609       if (pdi->has_pc_info)
6610         {
6611           if (pdi->lowpc < *lowpc)
6612             *lowpc = pdi->lowpc;
6613           if (pdi->highpc > *highpc)
6614             *highpc = pdi->highpc;
6615           if (need_pc)
6616             {
6617               CORE_ADDR baseaddr;
6618               struct objfile *objfile = cu->objfile;
6619
6620               baseaddr = ANOFFSET (objfile->section_offsets,
6621                                    SECT_OFF_TEXT (objfile));
6622               addrmap_set_empty (objfile->psymtabs_addrmap,
6623                                  pdi->lowpc + baseaddr,
6624                                  pdi->highpc - 1 + baseaddr,
6625                                  cu->per_cu->v.psymtab);
6626             }
6627         }
6628
6629       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6630         {
6631           if (!pdi->is_declaration)
6632             /* Ignore subprogram DIEs that do not have a name, they are
6633                illegal.  Do not emit a complaint at this point, we will
6634                do so when we convert this psymtab into a symtab.  */
6635             if (pdi->name)
6636               add_partial_symbol (pdi, cu);
6637         }
6638     }
6639
6640   if (! pdi->has_children)
6641     return;
6642
6643   if (cu->language == language_ada)
6644     {
6645       pdi = pdi->die_child;
6646       while (pdi != NULL)
6647         {
6648           fixup_partial_die (pdi, cu);
6649           if (pdi->tag == DW_TAG_subprogram
6650               || pdi->tag == DW_TAG_lexical_block)
6651             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6652           pdi = pdi->die_sibling;
6653         }
6654     }
6655 }
6656
6657 /* Read a partial die corresponding to an enumeration type.  */
6658
6659 static void
6660 add_partial_enumeration (struct partial_die_info *enum_pdi,
6661                          struct dwarf2_cu *cu)
6662 {
6663   struct partial_die_info *pdi;
6664
6665   if (enum_pdi->name != NULL)
6666     add_partial_symbol (enum_pdi, cu);
6667
6668   pdi = enum_pdi->die_child;
6669   while (pdi)
6670     {
6671       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6672         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6673       else
6674         add_partial_symbol (pdi, cu);
6675       pdi = pdi->die_sibling;
6676     }
6677 }
6678
6679 /* Return the initial uleb128 in the die at INFO_PTR.  */
6680
6681 static unsigned int
6682 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6683 {
6684   unsigned int bytes_read;
6685
6686   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6687 }
6688
6689 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6690    Return the corresponding abbrev, or NULL if the number is zero (indicating
6691    an empty DIE).  In either case *BYTES_READ will be set to the length of
6692    the initial number.  */
6693
6694 static struct abbrev_info *
6695 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6696                  struct dwarf2_cu *cu)
6697 {
6698   bfd *abfd = cu->objfile->obfd;
6699   unsigned int abbrev_number;
6700   struct abbrev_info *abbrev;
6701
6702   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6703
6704   if (abbrev_number == 0)
6705     return NULL;
6706
6707   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6708   if (!abbrev)
6709     {
6710       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6711              abbrev_number, bfd_get_filename (abfd));
6712     }
6713
6714   return abbrev;
6715 }
6716
6717 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6718    Returns a pointer to the end of a series of DIEs, terminated by an empty
6719    DIE.  Any children of the skipped DIEs will also be skipped.  */
6720
6721 static const gdb_byte *
6722 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6723 {
6724   struct dwarf2_cu *cu = reader->cu;
6725   struct abbrev_info *abbrev;
6726   unsigned int bytes_read;
6727
6728   while (1)
6729     {
6730       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6731       if (abbrev == NULL)
6732         return info_ptr + bytes_read;
6733       else
6734         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6735     }
6736 }
6737
6738 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6739    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6740    abbrev corresponding to that skipped uleb128 should be passed in
6741    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6742    children.  */
6743
6744 static const gdb_byte *
6745 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6746               struct abbrev_info *abbrev)
6747 {
6748   unsigned int bytes_read;
6749   struct attribute attr;
6750   bfd *abfd = reader->abfd;
6751   struct dwarf2_cu *cu = reader->cu;
6752   const gdb_byte *buffer = reader->buffer;
6753   const gdb_byte *buffer_end = reader->buffer_end;
6754   const gdb_byte *start_info_ptr = info_ptr;
6755   unsigned int form, i;
6756
6757   for (i = 0; i < abbrev->num_attrs; i++)
6758     {
6759       /* The only abbrev we care about is DW_AT_sibling.  */
6760       if (abbrev->attrs[i].name == DW_AT_sibling)
6761         {
6762           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6763           if (attr.form == DW_FORM_ref_addr)
6764             complaint (&symfile_complaints,
6765                        _("ignoring absolute DW_AT_sibling"));
6766           else
6767             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6768         }
6769
6770       /* If it isn't DW_AT_sibling, skip this attribute.  */
6771       form = abbrev->attrs[i].form;
6772     skip_attribute:
6773       switch (form)
6774         {
6775         case DW_FORM_ref_addr:
6776           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6777              and later it is offset sized.  */
6778           if (cu->header.version == 2)
6779             info_ptr += cu->header.addr_size;
6780           else
6781             info_ptr += cu->header.offset_size;
6782           break;
6783         case DW_FORM_GNU_ref_alt:
6784           info_ptr += cu->header.offset_size;
6785           break;
6786         case DW_FORM_addr:
6787           info_ptr += cu->header.addr_size;
6788           break;
6789         case DW_FORM_data1:
6790         case DW_FORM_ref1:
6791         case DW_FORM_flag:
6792           info_ptr += 1;
6793           break;
6794         case DW_FORM_flag_present:
6795           break;
6796         case DW_FORM_data2:
6797         case DW_FORM_ref2:
6798           info_ptr += 2;
6799           break;
6800         case DW_FORM_data4:
6801         case DW_FORM_ref4:
6802           info_ptr += 4;
6803           break;
6804         case DW_FORM_data8:
6805         case DW_FORM_ref8:
6806         case DW_FORM_ref_sig8:
6807           info_ptr += 8;
6808           break;
6809         case DW_FORM_string:
6810           read_direct_string (abfd, info_ptr, &bytes_read);
6811           info_ptr += bytes_read;
6812           break;
6813         case DW_FORM_sec_offset:
6814         case DW_FORM_strp:
6815         case DW_FORM_GNU_strp_alt:
6816           info_ptr += cu->header.offset_size;
6817           break;
6818         case DW_FORM_exprloc:
6819         case DW_FORM_block:
6820           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6821           info_ptr += bytes_read;
6822           break;
6823         case DW_FORM_block1:
6824           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6825           break;
6826         case DW_FORM_block2:
6827           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6828           break;
6829         case DW_FORM_block4:
6830           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6831           break;
6832         case DW_FORM_sdata:
6833         case DW_FORM_udata:
6834         case DW_FORM_ref_udata:
6835         case DW_FORM_GNU_addr_index:
6836         case DW_FORM_GNU_str_index:
6837           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6838           break;
6839         case DW_FORM_indirect:
6840           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6841           info_ptr += bytes_read;
6842           /* We need to continue parsing from here, so just go back to
6843              the top.  */
6844           goto skip_attribute;
6845
6846         default:
6847           error (_("Dwarf Error: Cannot handle %s "
6848                    "in DWARF reader [in module %s]"),
6849                  dwarf_form_name (form),
6850                  bfd_get_filename (abfd));
6851         }
6852     }
6853
6854   if (abbrev->has_children)
6855     return skip_children (reader, info_ptr);
6856   else
6857     return info_ptr;
6858 }
6859
6860 /* Locate ORIG_PDI's sibling.
6861    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6862
6863 static const gdb_byte *
6864 locate_pdi_sibling (const struct die_reader_specs *reader,
6865                     struct partial_die_info *orig_pdi,
6866                     const gdb_byte *info_ptr)
6867 {
6868   /* Do we know the sibling already?  */
6869
6870   if (orig_pdi->sibling)
6871     return orig_pdi->sibling;
6872
6873   /* Are there any children to deal with?  */
6874
6875   if (!orig_pdi->has_children)
6876     return info_ptr;
6877
6878   /* Skip the children the long way.  */
6879
6880   return skip_children (reader, info_ptr);
6881 }
6882
6883 /* Expand this partial symbol table into a full symbol table.  SELF is
6884    not NULL.  */
6885
6886 static void
6887 dwarf2_read_symtab (struct partial_symtab *self,
6888                     struct objfile *objfile)
6889 {
6890   if (self->readin)
6891     {
6892       warning (_("bug: psymtab for %s is already read in."),
6893                self->filename);
6894     }
6895   else
6896     {
6897       if (info_verbose)
6898         {
6899           printf_filtered (_("Reading in symbols for %s..."),
6900                            self->filename);
6901           gdb_flush (gdb_stdout);
6902         }
6903
6904       /* Restore our global data.  */
6905       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6906
6907       /* If this psymtab is constructed from a debug-only objfile, the
6908          has_section_at_zero flag will not necessarily be correct.  We
6909          can get the correct value for this flag by looking at the data
6910          associated with the (presumably stripped) associated objfile.  */
6911       if (objfile->separate_debug_objfile_backlink)
6912         {
6913           struct dwarf2_per_objfile *dpo_backlink
6914             = objfile_data (objfile->separate_debug_objfile_backlink,
6915                             dwarf2_objfile_data_key);
6916
6917           dwarf2_per_objfile->has_section_at_zero
6918             = dpo_backlink->has_section_at_zero;
6919         }
6920
6921       dwarf2_per_objfile->reading_partial_symbols = 0;
6922
6923       psymtab_to_symtab_1 (self);
6924
6925       /* Finish up the debug error message.  */
6926       if (info_verbose)
6927         printf_filtered (_("done.\n"));
6928     }
6929
6930   process_cu_includes ();
6931 }
6932 \f
6933 /* Reading in full CUs.  */
6934
6935 /* Add PER_CU to the queue.  */
6936
6937 static void
6938 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6939                  enum language pretend_language)
6940 {
6941   struct dwarf2_queue_item *item;
6942
6943   per_cu->queued = 1;
6944   item = xmalloc (sizeof (*item));
6945   item->per_cu = per_cu;
6946   item->pretend_language = pretend_language;
6947   item->next = NULL;
6948
6949   if (dwarf2_queue == NULL)
6950     dwarf2_queue = item;
6951   else
6952     dwarf2_queue_tail->next = item;
6953
6954   dwarf2_queue_tail = item;
6955 }
6956
6957 /* If PER_CU is not yet queued, add it to the queue.
6958    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
6959    dependency.
6960    The result is non-zero if PER_CU was queued, otherwise the result is zero
6961    meaning either PER_CU is already queued or it is already loaded.
6962
6963    N.B. There is an invariant here that if a CU is queued then it is loaded.
6964    The caller is required to load PER_CU if we return non-zero.  */
6965
6966 static int
6967 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
6968                        struct dwarf2_per_cu_data *per_cu,
6969                        enum language pretend_language)
6970 {
6971   /* We may arrive here during partial symbol reading, if we need full
6972      DIEs to process an unusual case (e.g. template arguments).  Do
6973      not queue PER_CU, just tell our caller to load its DIEs.  */
6974   if (dwarf2_per_objfile->reading_partial_symbols)
6975     {
6976       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6977         return 1;
6978       return 0;
6979     }
6980
6981   /* Mark the dependence relation so that we don't flush PER_CU
6982      too early.  */
6983   if (dependent_cu != NULL)
6984     dwarf2_add_dependence (dependent_cu, per_cu);
6985
6986   /* If it's already on the queue, we have nothing to do.  */
6987   if (per_cu->queued)
6988     return 0;
6989
6990   /* If the compilation unit is already loaded, just mark it as
6991      used.  */
6992   if (per_cu->cu != NULL)
6993     {
6994       per_cu->cu->last_used = 0;
6995       return 0;
6996     }
6997
6998   /* Add it to the queue.  */
6999   queue_comp_unit (per_cu, pretend_language);
7000
7001   return 1;
7002 }
7003
7004 /* Process the queue.  */
7005
7006 static void
7007 process_queue (void)
7008 {
7009   struct dwarf2_queue_item *item, *next_item;
7010
7011   if (dwarf2_read_debug)
7012     {
7013       fprintf_unfiltered (gdb_stdlog,
7014                           "Expanding one or more symtabs of objfile %s ...\n",
7015                           dwarf2_per_objfile->objfile->name);
7016     }
7017
7018   /* The queue starts out with one item, but following a DIE reference
7019      may load a new CU, adding it to the end of the queue.  */
7020   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7021     {
7022       if (dwarf2_per_objfile->using_index
7023           ? !item->per_cu->v.quick->symtab
7024           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7025         {
7026           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7027           char buf[100];
7028
7029           if (per_cu->is_debug_types)
7030             {
7031               struct signatured_type *sig_type =
7032                 (struct signatured_type *) per_cu;
7033
7034               sprintf (buf, "TU %s at offset 0x%x",
7035                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7036             }
7037           else
7038             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7039
7040           if (dwarf2_read_debug)
7041             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7042
7043           if (per_cu->is_debug_types)
7044             process_full_type_unit (per_cu, item->pretend_language);
7045           else
7046             process_full_comp_unit (per_cu, item->pretend_language);
7047
7048           if (dwarf2_read_debug)
7049             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7050         }
7051
7052       item->per_cu->queued = 0;
7053       next_item = item->next;
7054       xfree (item);
7055     }
7056
7057   dwarf2_queue_tail = NULL;
7058
7059   if (dwarf2_read_debug)
7060     {
7061       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7062                           dwarf2_per_objfile->objfile->name);
7063     }
7064 }
7065
7066 /* Free all allocated queue entries.  This function only releases anything if
7067    an error was thrown; if the queue was processed then it would have been
7068    freed as we went along.  */
7069
7070 static void
7071 dwarf2_release_queue (void *dummy)
7072 {
7073   struct dwarf2_queue_item *item, *last;
7074
7075   item = dwarf2_queue;
7076   while (item)
7077     {
7078       /* Anything still marked queued is likely to be in an
7079          inconsistent state, so discard it.  */
7080       if (item->per_cu->queued)
7081         {
7082           if (item->per_cu->cu != NULL)
7083             free_one_cached_comp_unit (item->per_cu);
7084           item->per_cu->queued = 0;
7085         }
7086
7087       last = item;
7088       item = item->next;
7089       xfree (last);
7090     }
7091
7092   dwarf2_queue = dwarf2_queue_tail = NULL;
7093 }
7094
7095 /* Read in full symbols for PST, and anything it depends on.  */
7096
7097 static void
7098 psymtab_to_symtab_1 (struct partial_symtab *pst)
7099 {
7100   struct dwarf2_per_cu_data *per_cu;
7101   int i;
7102
7103   if (pst->readin)
7104     return;
7105
7106   for (i = 0; i < pst->number_of_dependencies; i++)
7107     if (!pst->dependencies[i]->readin
7108         && pst->dependencies[i]->user == NULL)
7109       {
7110         /* Inform about additional files that need to be read in.  */
7111         if (info_verbose)
7112           {
7113             /* FIXME: i18n: Need to make this a single string.  */
7114             fputs_filtered (" ", gdb_stdout);
7115             wrap_here ("");
7116             fputs_filtered ("and ", gdb_stdout);
7117             wrap_here ("");
7118             printf_filtered ("%s...", pst->dependencies[i]->filename);
7119             wrap_here ("");     /* Flush output.  */
7120             gdb_flush (gdb_stdout);
7121           }
7122         psymtab_to_symtab_1 (pst->dependencies[i]);
7123       }
7124
7125   per_cu = pst->read_symtab_private;
7126
7127   if (per_cu == NULL)
7128     {
7129       /* It's an include file, no symbols to read for it.
7130          Everything is in the parent symtab.  */
7131       pst->readin = 1;
7132       return;
7133     }
7134
7135   dw2_do_instantiate_symtab (per_cu);
7136 }
7137
7138 /* Trivial hash function for die_info: the hash value of a DIE
7139    is its offset in .debug_info for this objfile.  */
7140
7141 static hashval_t
7142 die_hash (const void *item)
7143 {
7144   const struct die_info *die = item;
7145
7146   return die->offset.sect_off;
7147 }
7148
7149 /* Trivial comparison function for die_info structures: two DIEs
7150    are equal if they have the same offset.  */
7151
7152 static int
7153 die_eq (const void *item_lhs, const void *item_rhs)
7154 {
7155   const struct die_info *die_lhs = item_lhs;
7156   const struct die_info *die_rhs = item_rhs;
7157
7158   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7159 }
7160
7161 /* die_reader_func for load_full_comp_unit.
7162    This is identical to read_signatured_type_reader,
7163    but is kept separate for now.  */
7164
7165 static void
7166 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7167                             const gdb_byte *info_ptr,
7168                             struct die_info *comp_unit_die,
7169                             int has_children,
7170                             void *data)
7171 {
7172   struct dwarf2_cu *cu = reader->cu;
7173   enum language *language_ptr = data;
7174
7175   gdb_assert (cu->die_hash == NULL);
7176   cu->die_hash =
7177     htab_create_alloc_ex (cu->header.length / 12,
7178                           die_hash,
7179                           die_eq,
7180                           NULL,
7181                           &cu->comp_unit_obstack,
7182                           hashtab_obstack_allocate,
7183                           dummy_obstack_deallocate);
7184
7185   if (has_children)
7186     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7187                                                   &info_ptr, comp_unit_die);
7188   cu->dies = comp_unit_die;
7189   /* comp_unit_die is not stored in die_hash, no need.  */
7190
7191   /* We try not to read any attributes in this function, because not
7192      all CUs needed for references have been loaded yet, and symbol
7193      table processing isn't initialized.  But we have to set the CU language,
7194      or we won't be able to build types correctly.
7195      Similarly, if we do not read the producer, we can not apply
7196      producer-specific interpretation.  */
7197   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7198 }
7199
7200 /* Load the DIEs associated with PER_CU into memory.  */
7201
7202 static void
7203 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7204                      enum language pretend_language)
7205 {
7206   gdb_assert (! this_cu->is_debug_types);
7207
7208   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7209                            load_full_comp_unit_reader, &pretend_language);
7210 }
7211
7212 /* Add a DIE to the delayed physname list.  */
7213
7214 static void
7215 add_to_method_list (struct type *type, int fnfield_index, int index,
7216                     const char *name, struct die_info *die,
7217                     struct dwarf2_cu *cu)
7218 {
7219   struct delayed_method_info mi;
7220   mi.type = type;
7221   mi.fnfield_index = fnfield_index;
7222   mi.index = index;
7223   mi.name = name;
7224   mi.die = die;
7225   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7226 }
7227
7228 /* A cleanup for freeing the delayed method list.  */
7229
7230 static void
7231 free_delayed_list (void *ptr)
7232 {
7233   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7234   if (cu->method_list != NULL)
7235     {
7236       VEC_free (delayed_method_info, cu->method_list);
7237       cu->method_list = NULL;
7238     }
7239 }
7240
7241 /* Compute the physnames of any methods on the CU's method list.
7242
7243    The computation of method physnames is delayed in order to avoid the
7244    (bad) condition that one of the method's formal parameters is of an as yet
7245    incomplete type.  */
7246
7247 static void
7248 compute_delayed_physnames (struct dwarf2_cu *cu)
7249 {
7250   int i;
7251   struct delayed_method_info *mi;
7252   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7253     {
7254       const char *physname;
7255       struct fn_fieldlist *fn_flp
7256         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7257       physname = dwarf2_physname (mi->name, mi->die, cu);
7258       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7259     }
7260 }
7261
7262 /* Go objects should be embedded in a DW_TAG_module DIE,
7263    and it's not clear if/how imported objects will appear.
7264    To keep Go support simple until that's worked out,
7265    go back through what we've read and create something usable.
7266    We could do this while processing each DIE, and feels kinda cleaner,
7267    but that way is more invasive.
7268    This is to, for example, allow the user to type "p var" or "b main"
7269    without having to specify the package name, and allow lookups
7270    of module.object to work in contexts that use the expression
7271    parser.  */
7272
7273 static void
7274 fixup_go_packaging (struct dwarf2_cu *cu)
7275 {
7276   char *package_name = NULL;
7277   struct pending *list;
7278   int i;
7279
7280   for (list = global_symbols; list != NULL; list = list->next)
7281     {
7282       for (i = 0; i < list->nsyms; ++i)
7283         {
7284           struct symbol *sym = list->symbol[i];
7285
7286           if (SYMBOL_LANGUAGE (sym) == language_go
7287               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7288             {
7289               char *this_package_name = go_symbol_package_name (sym);
7290
7291               if (this_package_name == NULL)
7292                 continue;
7293               if (package_name == NULL)
7294                 package_name = this_package_name;
7295               else
7296                 {
7297                   if (strcmp (package_name, this_package_name) != 0)
7298                     complaint (&symfile_complaints,
7299                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7300                                (SYMBOL_SYMTAB (sym)
7301                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7302                                 : cu->objfile->name),
7303                                this_package_name, package_name);
7304                   xfree (this_package_name);
7305                 }
7306             }
7307         }
7308     }
7309
7310   if (package_name != NULL)
7311     {
7312       struct objfile *objfile = cu->objfile;
7313       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7314                                                       package_name,
7315                                                       strlen (package_name));
7316       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7317                                      saved_package_name, objfile);
7318       struct symbol *sym;
7319
7320       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7321
7322       sym = allocate_symbol (objfile);
7323       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7324       SYMBOL_SET_NAMES (sym, saved_package_name,
7325                         strlen (saved_package_name), 0, objfile);
7326       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7327          e.g., "main" finds the "main" module and not C's main().  */
7328       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7329       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7330       SYMBOL_TYPE (sym) = type;
7331
7332       add_symbol_to_list (sym, &global_symbols);
7333
7334       xfree (package_name);
7335     }
7336 }
7337
7338 /* Return the symtab for PER_CU.  This works properly regardless of
7339    whether we're using the index or psymtabs.  */
7340
7341 static struct symtab *
7342 get_symtab (struct dwarf2_per_cu_data *per_cu)
7343 {
7344   return (dwarf2_per_objfile->using_index
7345           ? per_cu->v.quick->symtab
7346           : per_cu->v.psymtab->symtab);
7347 }
7348
7349 /* A helper function for computing the list of all symbol tables
7350    included by PER_CU.  */
7351
7352 static void
7353 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7354                                 htab_t all_children, htab_t all_type_symtabs,
7355                                 struct dwarf2_per_cu_data *per_cu,
7356                                 struct symtab *immediate_parent)
7357 {
7358   void **slot;
7359   int ix;
7360   struct symtab *symtab;
7361   struct dwarf2_per_cu_data *iter;
7362
7363   slot = htab_find_slot (all_children, per_cu, INSERT);
7364   if (*slot != NULL)
7365     {
7366       /* This inclusion and its children have been processed.  */
7367       return;
7368     }
7369
7370   *slot = per_cu;
7371   /* Only add a CU if it has a symbol table.  */
7372   symtab = get_symtab (per_cu);
7373   if (symtab != NULL)
7374     {
7375       /* If this is a type unit only add its symbol table if we haven't
7376          seen it yet (type unit per_cu's can share symtabs).  */
7377       if (per_cu->is_debug_types)
7378         {
7379           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7380           if (*slot == NULL)
7381             {
7382               *slot = symtab;
7383               VEC_safe_push (symtab_ptr, *result, symtab);
7384               if (symtab->user == NULL)
7385                 symtab->user = immediate_parent;
7386             }
7387         }
7388       else
7389         {
7390           VEC_safe_push (symtab_ptr, *result, symtab);
7391           if (symtab->user == NULL)
7392             symtab->user = immediate_parent;
7393         }
7394     }
7395
7396   for (ix = 0;
7397        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7398        ++ix)
7399     {
7400       recursively_compute_inclusions (result, all_children,
7401                                       all_type_symtabs, iter, symtab);
7402     }
7403 }
7404
7405 /* Compute the symtab 'includes' fields for the symtab related to
7406    PER_CU.  */
7407
7408 static void
7409 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7410 {
7411   gdb_assert (! per_cu->is_debug_types);
7412
7413   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7414     {
7415       int ix, len;
7416       struct dwarf2_per_cu_data *per_cu_iter;
7417       struct symtab *symtab_iter;
7418       VEC (symtab_ptr) *result_symtabs = NULL;
7419       htab_t all_children, all_type_symtabs;
7420       struct symtab *symtab = get_symtab (per_cu);
7421
7422       /* If we don't have a symtab, we can just skip this case.  */
7423       if (symtab == NULL)
7424         return;
7425
7426       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7427                                         NULL, xcalloc, xfree);
7428       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7429                                             NULL, xcalloc, xfree);
7430
7431       for (ix = 0;
7432            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7433                         ix, per_cu_iter);
7434            ++ix)
7435         {
7436           recursively_compute_inclusions (&result_symtabs, all_children,
7437                                           all_type_symtabs, per_cu_iter,
7438                                           symtab);
7439         }
7440
7441       /* Now we have a transitive closure of all the included symtabs.  */
7442       len = VEC_length (symtab_ptr, result_symtabs);
7443       symtab->includes
7444         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7445                          (len + 1) * sizeof (struct symtab *));
7446       for (ix = 0;
7447            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7448            ++ix)
7449         symtab->includes[ix] = symtab_iter;
7450       symtab->includes[len] = NULL;
7451
7452       VEC_free (symtab_ptr, result_symtabs);
7453       htab_delete (all_children);
7454       htab_delete (all_type_symtabs);
7455     }
7456 }
7457
7458 /* Compute the 'includes' field for the symtabs of all the CUs we just
7459    read.  */
7460
7461 static void
7462 process_cu_includes (void)
7463 {
7464   int ix;
7465   struct dwarf2_per_cu_data *iter;
7466
7467   for (ix = 0;
7468        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7469                     ix, iter);
7470        ++ix)
7471     {
7472       if (! iter->is_debug_types)
7473         compute_symtab_includes (iter);
7474     }
7475
7476   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7477 }
7478
7479 /* Generate full symbol information for PER_CU, whose DIEs have
7480    already been loaded into memory.  */
7481
7482 static void
7483 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7484                         enum language pretend_language)
7485 {
7486   struct dwarf2_cu *cu = per_cu->cu;
7487   struct objfile *objfile = per_cu->objfile;
7488   CORE_ADDR lowpc, highpc;
7489   struct symtab *symtab;
7490   struct cleanup *back_to, *delayed_list_cleanup;
7491   CORE_ADDR baseaddr;
7492   struct block *static_block;
7493
7494   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7495
7496   buildsym_init ();
7497   back_to = make_cleanup (really_free_pendings, NULL);
7498   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7499
7500   cu->list_in_scope = &file_symbols;
7501
7502   cu->language = pretend_language;
7503   cu->language_defn = language_def (cu->language);
7504
7505   /* Do line number decoding in read_file_scope () */
7506   process_die (cu->dies, cu);
7507
7508   /* For now fudge the Go package.  */
7509   if (cu->language == language_go)
7510     fixup_go_packaging (cu);
7511
7512   /* Now that we have processed all the DIEs in the CU, all the types 
7513      should be complete, and it should now be safe to compute all of the
7514      physnames.  */
7515   compute_delayed_physnames (cu);
7516   do_cleanups (delayed_list_cleanup);
7517
7518   /* Some compilers don't define a DW_AT_high_pc attribute for the
7519      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7520      it, by scanning the DIE's below the compilation unit.  */
7521   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7522
7523   static_block
7524     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7525
7526   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7527      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7528      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7529      addrmap to help ensure it has an accurate map of pc values belonging to
7530      this comp unit.  */
7531   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7532
7533   symtab = end_symtab_from_static_block (static_block, objfile,
7534                                          SECT_OFF_TEXT (objfile), 0);
7535
7536   if (symtab != NULL)
7537     {
7538       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7539
7540       /* Set symtab language to language from DW_AT_language.  If the
7541          compilation is from a C file generated by language preprocessors, do
7542          not set the language if it was already deduced by start_subfile.  */
7543       if (!(cu->language == language_c && symtab->language != language_c))
7544         symtab->language = cu->language;
7545
7546       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7547          produce DW_AT_location with location lists but it can be possibly
7548          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7549          there were bugs in prologue debug info, fixed later in GCC-4.5
7550          by "unwind info for epilogues" patch (which is not directly related).
7551
7552          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7553          needed, it would be wrong due to missing DW_AT_producer there.
7554
7555          Still one can confuse GDB by using non-standard GCC compilation
7556          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7557          */ 
7558       if (cu->has_loclist && gcc_4_minor >= 5)
7559         symtab->locations_valid = 1;
7560
7561       if (gcc_4_minor >= 5)
7562         symtab->epilogue_unwind_valid = 1;
7563
7564       symtab->call_site_htab = cu->call_site_htab;
7565     }
7566
7567   if (dwarf2_per_objfile->using_index)
7568     per_cu->v.quick->symtab = symtab;
7569   else
7570     {
7571       struct partial_symtab *pst = per_cu->v.psymtab;
7572       pst->symtab = symtab;
7573       pst->readin = 1;
7574     }
7575
7576   /* Push it for inclusion processing later.  */
7577   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7578
7579   do_cleanups (back_to);
7580 }
7581
7582 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7583    already been loaded into memory.  */
7584
7585 static void
7586 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7587                         enum language pretend_language)
7588 {
7589   struct dwarf2_cu *cu = per_cu->cu;
7590   struct objfile *objfile = per_cu->objfile;
7591   struct symtab *symtab;
7592   struct cleanup *back_to, *delayed_list_cleanup;
7593   struct signatured_type *sig_type;
7594
7595   gdb_assert (per_cu->is_debug_types);
7596   sig_type = (struct signatured_type *) per_cu;
7597
7598   buildsym_init ();
7599   back_to = make_cleanup (really_free_pendings, NULL);
7600   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7601
7602   cu->list_in_scope = &file_symbols;
7603
7604   cu->language = pretend_language;
7605   cu->language_defn = language_def (cu->language);
7606
7607   /* The symbol tables are set up in read_type_unit_scope.  */
7608   process_die (cu->dies, cu);
7609
7610   /* For now fudge the Go package.  */
7611   if (cu->language == language_go)
7612     fixup_go_packaging (cu);
7613
7614   /* Now that we have processed all the DIEs in the CU, all the types 
7615      should be complete, and it should now be safe to compute all of the
7616      physnames.  */
7617   compute_delayed_physnames (cu);
7618   do_cleanups (delayed_list_cleanup);
7619
7620   /* TUs share symbol tables.
7621      If this is the first TU to use this symtab, complete the construction
7622      of it with end_expandable_symtab.  Otherwise, complete the addition of
7623      this TU's symbols to the existing symtab.  */
7624   if (sig_type->type_unit_group->primary_symtab == NULL)
7625     {
7626       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7627       sig_type->type_unit_group->primary_symtab = symtab;
7628
7629       if (symtab != NULL)
7630         {
7631           /* Set symtab language to language from DW_AT_language.  If the
7632              compilation is from a C file generated by language preprocessors,
7633              do not set the language if it was already deduced by
7634              start_subfile.  */
7635           if (!(cu->language == language_c && symtab->language != language_c))
7636             symtab->language = cu->language;
7637         }
7638     }
7639   else
7640     {
7641       augment_type_symtab (objfile,
7642                            sig_type->type_unit_group->primary_symtab);
7643       symtab = sig_type->type_unit_group->primary_symtab;
7644     }
7645
7646   if (dwarf2_per_objfile->using_index)
7647     per_cu->v.quick->symtab = symtab;
7648   else
7649     {
7650       struct partial_symtab *pst = per_cu->v.psymtab;
7651       pst->symtab = symtab;
7652       pst->readin = 1;
7653     }
7654
7655   do_cleanups (back_to);
7656 }
7657
7658 /* Process an imported unit DIE.  */
7659
7660 static void
7661 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7662 {
7663   struct attribute *attr;
7664
7665   /* For now we don't handle imported units in type units.  */
7666   if (cu->per_cu->is_debug_types)
7667     {
7668       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7669                " supported in type units [in module %s]"),
7670              cu->objfile->name);
7671     }
7672
7673   attr = dwarf2_attr (die, DW_AT_import, cu);
7674   if (attr != NULL)
7675     {
7676       struct dwarf2_per_cu_data *per_cu;
7677       struct symtab *imported_symtab;
7678       sect_offset offset;
7679       int is_dwz;
7680
7681       offset = dwarf2_get_ref_die_offset (attr);
7682       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7683       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7684
7685       /* If necessary, add it to the queue and load its DIEs.  */
7686       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7687         load_full_comp_unit (per_cu, cu->language);
7688
7689       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7690                      per_cu);
7691     }
7692 }
7693
7694 /* Process a die and its children.  */
7695
7696 static void
7697 process_die (struct die_info *die, struct dwarf2_cu *cu)
7698 {
7699   switch (die->tag)
7700     {
7701     case DW_TAG_padding:
7702       break;
7703     case DW_TAG_compile_unit:
7704     case DW_TAG_partial_unit:
7705       read_file_scope (die, cu);
7706       break;
7707     case DW_TAG_type_unit:
7708       read_type_unit_scope (die, cu);
7709       break;
7710     case DW_TAG_subprogram:
7711     case DW_TAG_inlined_subroutine:
7712       read_func_scope (die, cu);
7713       break;
7714     case DW_TAG_lexical_block:
7715     case DW_TAG_try_block:
7716     case DW_TAG_catch_block:
7717       read_lexical_block_scope (die, cu);
7718       break;
7719     case DW_TAG_GNU_call_site:
7720       read_call_site_scope (die, cu);
7721       break;
7722     case DW_TAG_class_type:
7723     case DW_TAG_interface_type:
7724     case DW_TAG_structure_type:
7725     case DW_TAG_union_type:
7726       process_structure_scope (die, cu);
7727       break;
7728     case DW_TAG_enumeration_type:
7729       process_enumeration_scope (die, cu);
7730       break;
7731
7732     /* These dies have a type, but processing them does not create
7733        a symbol or recurse to process the children.  Therefore we can
7734        read them on-demand through read_type_die.  */
7735     case DW_TAG_subroutine_type:
7736     case DW_TAG_set_type:
7737     case DW_TAG_array_type:
7738     case DW_TAG_pointer_type:
7739     case DW_TAG_ptr_to_member_type:
7740     case DW_TAG_reference_type:
7741     case DW_TAG_string_type:
7742       break;
7743
7744     case DW_TAG_base_type:
7745     case DW_TAG_subrange_type:
7746     case DW_TAG_typedef:
7747       /* Add a typedef symbol for the type definition, if it has a
7748          DW_AT_name.  */
7749       new_symbol (die, read_type_die (die, cu), cu);
7750       break;
7751     case DW_TAG_common_block:
7752       read_common_block (die, cu);
7753       break;
7754     case DW_TAG_common_inclusion:
7755       break;
7756     case DW_TAG_namespace:
7757       cu->processing_has_namespace_info = 1;
7758       read_namespace (die, cu);
7759       break;
7760     case DW_TAG_module:
7761       cu->processing_has_namespace_info = 1;
7762       read_module (die, cu);
7763       break;
7764     case DW_TAG_imported_declaration:
7765     case DW_TAG_imported_module:
7766       cu->processing_has_namespace_info = 1;
7767       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7768                                  || cu->language != language_fortran))
7769         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7770                    dwarf_tag_name (die->tag));
7771       read_import_statement (die, cu);
7772       break;
7773
7774     case DW_TAG_imported_unit:
7775       process_imported_unit_die (die, cu);
7776       break;
7777
7778     default:
7779       new_symbol (die, NULL, cu);
7780       break;
7781     }
7782 }
7783 \f
7784 /* DWARF name computation.  */
7785
7786 /* A helper function for dwarf2_compute_name which determines whether DIE
7787    needs to have the name of the scope prepended to the name listed in the
7788    die.  */
7789
7790 static int
7791 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7792 {
7793   struct attribute *attr;
7794
7795   switch (die->tag)
7796     {
7797     case DW_TAG_namespace:
7798     case DW_TAG_typedef:
7799     case DW_TAG_class_type:
7800     case DW_TAG_interface_type:
7801     case DW_TAG_structure_type:
7802     case DW_TAG_union_type:
7803     case DW_TAG_enumeration_type:
7804     case DW_TAG_enumerator:
7805     case DW_TAG_subprogram:
7806     case DW_TAG_member:
7807       return 1;
7808
7809     case DW_TAG_variable:
7810     case DW_TAG_constant:
7811       /* We only need to prefix "globally" visible variables.  These include
7812          any variable marked with DW_AT_external or any variable that
7813          lives in a namespace.  [Variables in anonymous namespaces
7814          require prefixing, but they are not DW_AT_external.]  */
7815
7816       if (dwarf2_attr (die, DW_AT_specification, cu))
7817         {
7818           struct dwarf2_cu *spec_cu = cu;
7819
7820           return die_needs_namespace (die_specification (die, &spec_cu),
7821                                       spec_cu);
7822         }
7823
7824       attr = dwarf2_attr (die, DW_AT_external, cu);
7825       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7826           && die->parent->tag != DW_TAG_module)
7827         return 0;
7828       /* A variable in a lexical block of some kind does not need a
7829          namespace, even though in C++ such variables may be external
7830          and have a mangled name.  */
7831       if (die->parent->tag ==  DW_TAG_lexical_block
7832           || die->parent->tag ==  DW_TAG_try_block
7833           || die->parent->tag ==  DW_TAG_catch_block
7834           || die->parent->tag == DW_TAG_subprogram)
7835         return 0;
7836       return 1;
7837
7838     default:
7839       return 0;
7840     }
7841 }
7842
7843 /* Retrieve the last character from a mem_file.  */
7844
7845 static void
7846 do_ui_file_peek_last (void *object, const char *buffer, long length)
7847 {
7848   char *last_char_p = (char *) object;
7849
7850   if (length > 0)
7851     *last_char_p = buffer[length - 1];
7852 }
7853
7854 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7855    compute the physname for the object, which include a method's:
7856    - formal parameters (C++/Java),
7857    - receiver type (Go),
7858    - return type (Java).
7859
7860    The term "physname" is a bit confusing.
7861    For C++, for example, it is the demangled name.
7862    For Go, for example, it's the mangled name.
7863
7864    For Ada, return the DIE's linkage name rather than the fully qualified
7865    name.  PHYSNAME is ignored..
7866
7867    The result is allocated on the objfile_obstack and canonicalized.  */
7868
7869 static const char *
7870 dwarf2_compute_name (const char *name,
7871                      struct die_info *die, struct dwarf2_cu *cu,
7872                      int physname)
7873 {
7874   struct objfile *objfile = cu->objfile;
7875
7876   if (name == NULL)
7877     name = dwarf2_name (die, cu);
7878
7879   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7880      compute it by typename_concat inside GDB.  */
7881   if (cu->language == language_ada
7882       || (cu->language == language_fortran && physname))
7883     {
7884       /* For Ada unit, we prefer the linkage name over the name, as
7885          the former contains the exported name, which the user expects
7886          to be able to reference.  Ideally, we want the user to be able
7887          to reference this entity using either natural or linkage name,
7888          but we haven't started looking at this enhancement yet.  */
7889       struct attribute *attr;
7890
7891       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7892       if (attr == NULL)
7893         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7894       if (attr && DW_STRING (attr))
7895         return DW_STRING (attr);
7896     }
7897
7898   /* These are the only languages we know how to qualify names in.  */
7899   if (name != NULL
7900       && (cu->language == language_cplus || cu->language == language_java
7901           || cu->language == language_fortran))
7902     {
7903       if (die_needs_namespace (die, cu))
7904         {
7905           long length;
7906           const char *prefix;
7907           struct ui_file *buf;
7908
7909           prefix = determine_prefix (die, cu);
7910           buf = mem_fileopen ();
7911           if (*prefix != '\0')
7912             {
7913               char *prefixed_name = typename_concat (NULL, prefix, name,
7914                                                      physname, cu);
7915
7916               fputs_unfiltered (prefixed_name, buf);
7917               xfree (prefixed_name);
7918             }
7919           else
7920             fputs_unfiltered (name, buf);
7921
7922           /* Template parameters may be specified in the DIE's DW_AT_name, or
7923              as children with DW_TAG_template_type_param or
7924              DW_TAG_value_type_param.  If the latter, add them to the name
7925              here.  If the name already has template parameters, then
7926              skip this step; some versions of GCC emit both, and
7927              it is more efficient to use the pre-computed name.
7928
7929              Something to keep in mind about this process: it is very
7930              unlikely, or in some cases downright impossible, to produce
7931              something that will match the mangled name of a function.
7932              If the definition of the function has the same debug info,
7933              we should be able to match up with it anyway.  But fallbacks
7934              using the minimal symbol, for instance to find a method
7935              implemented in a stripped copy of libstdc++, will not work.
7936              If we do not have debug info for the definition, we will have to
7937              match them up some other way.
7938
7939              When we do name matching there is a related problem with function
7940              templates; two instantiated function templates are allowed to
7941              differ only by their return types, which we do not add here.  */
7942
7943           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7944             {
7945               struct attribute *attr;
7946               struct die_info *child;
7947               int first = 1;
7948
7949               die->building_fullname = 1;
7950
7951               for (child = die->child; child != NULL; child = child->sibling)
7952                 {
7953                   struct type *type;
7954                   LONGEST value;
7955                   const gdb_byte *bytes;
7956                   struct dwarf2_locexpr_baton *baton;
7957                   struct value *v;
7958
7959                   if (child->tag != DW_TAG_template_type_param
7960                       && child->tag != DW_TAG_template_value_param)
7961                     continue;
7962
7963                   if (first)
7964                     {
7965                       fputs_unfiltered ("<", buf);
7966                       first = 0;
7967                     }
7968                   else
7969                     fputs_unfiltered (", ", buf);
7970
7971                   attr = dwarf2_attr (child, DW_AT_type, cu);
7972                   if (attr == NULL)
7973                     {
7974                       complaint (&symfile_complaints,
7975                                  _("template parameter missing DW_AT_type"));
7976                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7977                       continue;
7978                     }
7979                   type = die_type (child, cu);
7980
7981                   if (child->tag == DW_TAG_template_type_param)
7982                     {
7983                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7984                       continue;
7985                     }
7986
7987                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7988                   if (attr == NULL)
7989                     {
7990                       complaint (&symfile_complaints,
7991                                  _("template parameter missing "
7992                                    "DW_AT_const_value"));
7993                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7994                       continue;
7995                     }
7996
7997                   dwarf2_const_value_attr (attr, type, name,
7998                                            &cu->comp_unit_obstack, cu,
7999                                            &value, &bytes, &baton);
8000
8001                   if (TYPE_NOSIGN (type))
8002                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8003                        changed, this can use value_print instead.  */
8004                     c_printchar (value, type, buf);
8005                   else
8006                     {
8007                       struct value_print_options opts;
8008
8009                       if (baton != NULL)
8010                         v = dwarf2_evaluate_loc_desc (type, NULL,
8011                                                       baton->data,
8012                                                       baton->size,
8013                                                       baton->per_cu);
8014                       else if (bytes != NULL)
8015                         {
8016                           v = allocate_value (type);
8017                           memcpy (value_contents_writeable (v), bytes,
8018                                   TYPE_LENGTH (type));
8019                         }
8020                       else
8021                         v = value_from_longest (type, value);
8022
8023                       /* Specify decimal so that we do not depend on
8024                          the radix.  */
8025                       get_formatted_print_options (&opts, 'd');
8026                       opts.raw = 1;
8027                       value_print (v, buf, &opts);
8028                       release_value (v);
8029                       value_free (v);
8030                     }
8031                 }
8032
8033               die->building_fullname = 0;
8034
8035               if (!first)
8036                 {
8037                   /* Close the argument list, with a space if necessary
8038                      (nested templates).  */
8039                   char last_char = '\0';
8040                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8041                   if (last_char == '>')
8042                     fputs_unfiltered (" >", buf);
8043                   else
8044                     fputs_unfiltered (">", buf);
8045                 }
8046             }
8047
8048           /* For Java and C++ methods, append formal parameter type
8049              information, if PHYSNAME.  */
8050
8051           if (physname && die->tag == DW_TAG_subprogram
8052               && (cu->language == language_cplus
8053                   || cu->language == language_java))
8054             {
8055               struct type *type = read_type_die (die, cu);
8056
8057               c_type_print_args (type, buf, 1, cu->language,
8058                                  &type_print_raw_options);
8059
8060               if (cu->language == language_java)
8061                 {
8062                   /* For java, we must append the return type to method
8063                      names.  */
8064                   if (die->tag == DW_TAG_subprogram)
8065                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8066                                      0, 0, &type_print_raw_options);
8067                 }
8068               else if (cu->language == language_cplus)
8069                 {
8070                   /* Assume that an artificial first parameter is
8071                      "this", but do not crash if it is not.  RealView
8072                      marks unnamed (and thus unused) parameters as
8073                      artificial; there is no way to differentiate
8074                      the two cases.  */
8075                   if (TYPE_NFIELDS (type) > 0
8076                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8077                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8078                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8079                                                                         0))))
8080                     fputs_unfiltered (" const", buf);
8081                 }
8082             }
8083
8084           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8085                                        &length);
8086           ui_file_delete (buf);
8087
8088           if (cu->language == language_cplus)
8089             {
8090               const char *cname
8091                 = dwarf2_canonicalize_name (name, cu,
8092                                             &objfile->objfile_obstack);
8093
8094               if (cname != NULL)
8095                 name = cname;
8096             }
8097         }
8098     }
8099
8100   return name;
8101 }
8102
8103 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8104    If scope qualifiers are appropriate they will be added.  The result
8105    will be allocated on the objfile_obstack, or NULL if the DIE does
8106    not have a name.  NAME may either be from a previous call to
8107    dwarf2_name or NULL.
8108
8109    The output string will be canonicalized (if C++/Java).  */
8110
8111 static const char *
8112 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8113 {
8114   return dwarf2_compute_name (name, die, cu, 0);
8115 }
8116
8117 /* Construct a physname for the given DIE in CU.  NAME may either be
8118    from a previous call to dwarf2_name or NULL.  The result will be
8119    allocated on the objfile_objstack or NULL if the DIE does not have a
8120    name.
8121
8122    The output string will be canonicalized (if C++/Java).  */
8123
8124 static const char *
8125 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8126 {
8127   struct objfile *objfile = cu->objfile;
8128   struct attribute *attr;
8129   const char *retval, *mangled = NULL, *canon = NULL;
8130   struct cleanup *back_to;
8131   int need_copy = 1;
8132
8133   /* In this case dwarf2_compute_name is just a shortcut not building anything
8134      on its own.  */
8135   if (!die_needs_namespace (die, cu))
8136     return dwarf2_compute_name (name, die, cu, 1);
8137
8138   back_to = make_cleanup (null_cleanup, NULL);
8139
8140   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8141   if (!attr)
8142     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8143
8144   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8145      has computed.  */
8146   if (attr && DW_STRING (attr))
8147     {
8148       char *demangled;
8149
8150       mangled = DW_STRING (attr);
8151
8152       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8153          type.  It is easier for GDB users to search for such functions as
8154          `name(params)' than `long name(params)'.  In such case the minimal
8155          symbol names do not match the full symbol names but for template
8156          functions there is never a need to look up their definition from their
8157          declaration so the only disadvantage remains the minimal symbol
8158          variant `long name(params)' does not have the proper inferior type.
8159          */
8160
8161       if (cu->language == language_go)
8162         {
8163           /* This is a lie, but we already lie to the caller new_symbol_full.
8164              new_symbol_full assumes we return the mangled name.
8165              This just undoes that lie until things are cleaned up.  */
8166           demangled = NULL;
8167         }
8168       else
8169         {
8170           demangled = gdb_demangle (mangled,
8171                                     (DMGL_PARAMS | DMGL_ANSI
8172                                      | (cu->language == language_java
8173                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8174                                         : DMGL_RET_DROP)));
8175         }
8176       if (demangled)
8177         {
8178           make_cleanup (xfree, demangled);
8179           canon = demangled;
8180         }
8181       else
8182         {
8183           canon = mangled;
8184           need_copy = 0;
8185         }
8186     }
8187
8188   if (canon == NULL || check_physname)
8189     {
8190       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8191
8192       if (canon != NULL && strcmp (physname, canon) != 0)
8193         {
8194           /* It may not mean a bug in GDB.  The compiler could also
8195              compute DW_AT_linkage_name incorrectly.  But in such case
8196              GDB would need to be bug-to-bug compatible.  */
8197
8198           complaint (&symfile_complaints,
8199                      _("Computed physname <%s> does not match demangled <%s> "
8200                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8201                      physname, canon, mangled, die->offset.sect_off, objfile->name);
8202
8203           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8204              is available here - over computed PHYSNAME.  It is safer
8205              against both buggy GDB and buggy compilers.  */
8206
8207           retval = canon;
8208         }
8209       else
8210         {
8211           retval = physname;
8212           need_copy = 0;
8213         }
8214     }
8215   else
8216     retval = canon;
8217
8218   if (need_copy)
8219     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8220
8221   do_cleanups (back_to);
8222   return retval;
8223 }
8224
8225 /* Read the import statement specified by the given die and record it.  */
8226
8227 static void
8228 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8229 {
8230   struct objfile *objfile = cu->objfile;
8231   struct attribute *import_attr;
8232   struct die_info *imported_die, *child_die;
8233   struct dwarf2_cu *imported_cu;
8234   const char *imported_name;
8235   const char *imported_name_prefix;
8236   const char *canonical_name;
8237   const char *import_alias;
8238   const char *imported_declaration = NULL;
8239   const char *import_prefix;
8240   VEC (const_char_ptr) *excludes = NULL;
8241   struct cleanup *cleanups;
8242
8243   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8244   if (import_attr == NULL)
8245     {
8246       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8247                  dwarf_tag_name (die->tag));
8248       return;
8249     }
8250
8251   imported_cu = cu;
8252   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8253   imported_name = dwarf2_name (imported_die, imported_cu);
8254   if (imported_name == NULL)
8255     {
8256       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8257
8258         The import in the following code:
8259         namespace A
8260           {
8261             typedef int B;
8262           }
8263
8264         int main ()
8265           {
8266             using A::B;
8267             B b;
8268             return b;
8269           }
8270
8271         ...
8272          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8273             <52>   DW_AT_decl_file   : 1
8274             <53>   DW_AT_decl_line   : 6
8275             <54>   DW_AT_import      : <0x75>
8276          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8277             <59>   DW_AT_name        : B
8278             <5b>   DW_AT_decl_file   : 1
8279             <5c>   DW_AT_decl_line   : 2
8280             <5d>   DW_AT_type        : <0x6e>
8281         ...
8282          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8283             <76>   DW_AT_byte_size   : 4
8284             <77>   DW_AT_encoding    : 5        (signed)
8285
8286         imports the wrong die ( 0x75 instead of 0x58 ).
8287         This case will be ignored until the gcc bug is fixed.  */
8288       return;
8289     }
8290
8291   /* Figure out the local name after import.  */
8292   import_alias = dwarf2_name (die, cu);
8293
8294   /* Figure out where the statement is being imported to.  */
8295   import_prefix = determine_prefix (die, cu);
8296
8297   /* Figure out what the scope of the imported die is and prepend it
8298      to the name of the imported die.  */
8299   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8300
8301   if (imported_die->tag != DW_TAG_namespace
8302       && imported_die->tag != DW_TAG_module)
8303     {
8304       imported_declaration = imported_name;
8305       canonical_name = imported_name_prefix;
8306     }
8307   else if (strlen (imported_name_prefix) > 0)
8308     canonical_name = obconcat (&objfile->objfile_obstack,
8309                                imported_name_prefix, "::", imported_name,
8310                                (char *) NULL);
8311   else
8312     canonical_name = imported_name;
8313
8314   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8315
8316   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8317     for (child_die = die->child; child_die && child_die->tag;
8318          child_die = sibling_die (child_die))
8319       {
8320         /* DWARF-4: A Fortran use statement with a “rename list” may be
8321            represented by an imported module entry with an import attribute
8322            referring to the module and owned entries corresponding to those
8323            entities that are renamed as part of being imported.  */
8324
8325         if (child_die->tag != DW_TAG_imported_declaration)
8326           {
8327             complaint (&symfile_complaints,
8328                        _("child DW_TAG_imported_declaration expected "
8329                          "- DIE at 0x%x [in module %s]"),
8330                        child_die->offset.sect_off, objfile->name);
8331             continue;
8332           }
8333
8334         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8335         if (import_attr == NULL)
8336           {
8337             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8338                        dwarf_tag_name (child_die->tag));
8339             continue;
8340           }
8341
8342         imported_cu = cu;
8343         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8344                                               &imported_cu);
8345         imported_name = dwarf2_name (imported_die, imported_cu);
8346         if (imported_name == NULL)
8347           {
8348             complaint (&symfile_complaints,
8349                        _("child DW_TAG_imported_declaration has unknown "
8350                          "imported name - DIE at 0x%x [in module %s]"),
8351                        child_die->offset.sect_off, objfile->name);
8352             continue;
8353           }
8354
8355         VEC_safe_push (const_char_ptr, excludes, imported_name);
8356
8357         process_die (child_die, cu);
8358       }
8359
8360   cp_add_using_directive (import_prefix,
8361                           canonical_name,
8362                           import_alias,
8363                           imported_declaration,
8364                           excludes,
8365                           0,
8366                           &objfile->objfile_obstack);
8367
8368   do_cleanups (cleanups);
8369 }
8370
8371 /* Cleanup function for handle_DW_AT_stmt_list.  */
8372
8373 static void
8374 free_cu_line_header (void *arg)
8375 {
8376   struct dwarf2_cu *cu = arg;
8377
8378   free_line_header (cu->line_header);
8379   cu->line_header = NULL;
8380 }
8381
8382 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8383    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8384    this, it was first present in GCC release 4.3.0.  */
8385
8386 static int
8387 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8388 {
8389   if (!cu->checked_producer)
8390     check_producer (cu);
8391
8392   return cu->producer_is_gcc_lt_4_3;
8393 }
8394
8395 static void
8396 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8397                          const char **name, const char **comp_dir)
8398 {
8399   struct attribute *attr;
8400
8401   *name = NULL;
8402   *comp_dir = NULL;
8403
8404   /* Find the filename.  Do not use dwarf2_name here, since the filename
8405      is not a source language identifier.  */
8406   attr = dwarf2_attr (die, DW_AT_name, cu);
8407   if (attr)
8408     {
8409       *name = DW_STRING (attr);
8410     }
8411
8412   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8413   if (attr)
8414     *comp_dir = DW_STRING (attr);
8415   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8416            && IS_ABSOLUTE_PATH (*name))
8417     {
8418       char *d = ldirname (*name);
8419
8420       *comp_dir = d;
8421       if (d != NULL)
8422         make_cleanup (xfree, d);
8423     }
8424   if (*comp_dir != NULL)
8425     {
8426       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8427          directory, get rid of it.  */
8428       char *cp = strchr (*comp_dir, ':');
8429
8430       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8431         *comp_dir = cp + 1;
8432     }
8433
8434   if (*name == NULL)
8435     *name = "<unknown>";
8436 }
8437
8438 /* Handle DW_AT_stmt_list for a compilation unit.
8439    DIE is the DW_TAG_compile_unit die for CU.
8440    COMP_DIR is the compilation directory.
8441    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8442
8443 static void
8444 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8445                         const char *comp_dir) /* ARI: editCase function */
8446 {
8447   struct attribute *attr;
8448
8449   gdb_assert (! cu->per_cu->is_debug_types);
8450
8451   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8452   if (attr)
8453     {
8454       unsigned int line_offset = DW_UNSND (attr);
8455       struct line_header *line_header
8456         = dwarf_decode_line_header (line_offset, cu);
8457
8458       if (line_header)
8459         {
8460           cu->line_header = line_header;
8461           make_cleanup (free_cu_line_header, cu);
8462           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8463         }
8464     }
8465 }
8466
8467 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8468
8469 static void
8470 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8471 {
8472   struct objfile *objfile = dwarf2_per_objfile->objfile;
8473   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8474   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8475   CORE_ADDR highpc = ((CORE_ADDR) 0);
8476   struct attribute *attr;
8477   const char *name = NULL;
8478   const char *comp_dir = NULL;
8479   struct die_info *child_die;
8480   bfd *abfd = objfile->obfd;
8481   CORE_ADDR baseaddr;
8482
8483   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8484
8485   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8486
8487   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8488      from finish_block.  */
8489   if (lowpc == ((CORE_ADDR) -1))
8490     lowpc = highpc;
8491   lowpc += baseaddr;
8492   highpc += baseaddr;
8493
8494   find_file_and_directory (die, cu, &name, &comp_dir);
8495
8496   prepare_one_comp_unit (cu, die, cu->language);
8497
8498   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8499      standardised yet.  As a workaround for the language detection we fall
8500      back to the DW_AT_producer string.  */
8501   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8502     cu->language = language_opencl;
8503
8504   /* Similar hack for Go.  */
8505   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8506     set_cu_language (DW_LANG_Go, cu);
8507
8508   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8509
8510   /* Decode line number information if present.  We do this before
8511      processing child DIEs, so that the line header table is available
8512      for DW_AT_decl_file.  */
8513   handle_DW_AT_stmt_list (die, cu, comp_dir);
8514
8515   /* Process all dies in compilation unit.  */
8516   if (die->child != NULL)
8517     {
8518       child_die = die->child;
8519       while (child_die && child_die->tag)
8520         {
8521           process_die (child_die, cu);
8522           child_die = sibling_die (child_die);
8523         }
8524     }
8525
8526   /* Decode macro information, if present.  Dwarf 2 macro information
8527      refers to information in the line number info statement program
8528      header, so we can only read it if we've read the header
8529      successfully.  */
8530   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8531   if (attr && cu->line_header)
8532     {
8533       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8534         complaint (&symfile_complaints,
8535                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8536
8537       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8538     }
8539   else
8540     {
8541       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8542       if (attr && cu->line_header)
8543         {
8544           unsigned int macro_offset = DW_UNSND (attr);
8545
8546           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8547         }
8548     }
8549
8550   do_cleanups (back_to);
8551 }
8552
8553 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8554    Create the set of symtabs used by this TU, or if this TU is sharing
8555    symtabs with another TU and the symtabs have already been created
8556    then restore those symtabs in the line header.
8557    We don't need the pc/line-number mapping for type units.  */
8558
8559 static void
8560 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8561 {
8562   struct objfile *objfile = dwarf2_per_objfile->objfile;
8563   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8564   struct type_unit_group *tu_group;
8565   int first_time;
8566   struct line_header *lh;
8567   struct attribute *attr;
8568   unsigned int i, line_offset;
8569   struct signatured_type *sig_type;
8570
8571   gdb_assert (per_cu->is_debug_types);
8572   sig_type = (struct signatured_type *) per_cu;
8573
8574   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8575
8576   /* If we're using .gdb_index (includes -readnow) then
8577      per_cu->type_unit_group may not have been set up yet.  */
8578   if (sig_type->type_unit_group == NULL)
8579     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8580   tu_group = sig_type->type_unit_group;
8581
8582   /* If we've already processed this stmt_list there's no real need to
8583      do it again, we could fake it and just recreate the part we need
8584      (file name,index -> symtab mapping).  If data shows this optimization
8585      is useful we can do it then.  */
8586   first_time = tu_group->primary_symtab == NULL;
8587
8588   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8589      debug info.  */
8590   lh = NULL;
8591   if (attr != NULL)
8592     {
8593       line_offset = DW_UNSND (attr);
8594       lh = dwarf_decode_line_header (line_offset, cu);
8595     }
8596   if (lh == NULL)
8597     {
8598       if (first_time)
8599         dwarf2_start_symtab (cu, "", NULL, 0);
8600       else
8601         {
8602           gdb_assert (tu_group->symtabs == NULL);
8603           restart_symtab (0);
8604         }
8605       /* Note: The primary symtab will get allocated at the end.  */
8606       return;
8607     }
8608
8609   cu->line_header = lh;
8610   make_cleanup (free_cu_line_header, cu);
8611
8612   if (first_time)
8613     {
8614       dwarf2_start_symtab (cu, "", NULL, 0);
8615
8616       tu_group->num_symtabs = lh->num_file_names;
8617       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8618
8619       for (i = 0; i < lh->num_file_names; ++i)
8620         {
8621           const char *dir = NULL;
8622           struct file_entry *fe = &lh->file_names[i];
8623
8624           if (fe->dir_index)
8625             dir = lh->include_dirs[fe->dir_index - 1];
8626           dwarf2_start_subfile (fe->name, dir, NULL);
8627
8628           /* Note: We don't have to watch for the main subfile here, type units
8629              don't have DW_AT_name.  */
8630
8631           if (current_subfile->symtab == NULL)
8632             {
8633               /* NOTE: start_subfile will recognize when it's been passed
8634                  a file it has already seen.  So we can't assume there's a
8635                  simple mapping from lh->file_names to subfiles,
8636                  lh->file_names may contain dups.  */
8637               current_subfile->symtab = allocate_symtab (current_subfile->name,
8638                                                          objfile);
8639             }
8640
8641           fe->symtab = current_subfile->symtab;
8642           tu_group->symtabs[i] = fe->symtab;
8643         }
8644     }
8645   else
8646     {
8647       restart_symtab (0);
8648
8649       for (i = 0; i < lh->num_file_names; ++i)
8650         {
8651           struct file_entry *fe = &lh->file_names[i];
8652
8653           fe->symtab = tu_group->symtabs[i];
8654         }
8655     }
8656
8657   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8658      so they don't have a "real" (so to speak) symtab anyway.
8659      There is later code that will assign the main symtab to all symbols
8660      that don't have one.  We need to handle the case of a symbol with a
8661      missing symtab (DW_AT_decl_file) anyway.  */
8662 }
8663
8664 /* Process DW_TAG_type_unit.
8665    For TUs we want to skip the first top level sibling if it's not the
8666    actual type being defined by this TU.  In this case the first top
8667    level sibling is there to provide context only.  */
8668
8669 static void
8670 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8671 {
8672   struct die_info *child_die;
8673
8674   prepare_one_comp_unit (cu, die, language_minimal);
8675
8676   /* Initialize (or reinitialize) the machinery for building symtabs.
8677      We do this before processing child DIEs, so that the line header table
8678      is available for DW_AT_decl_file.  */
8679   setup_type_unit_groups (die, cu);
8680
8681   if (die->child != NULL)
8682     {
8683       child_die = die->child;
8684       while (child_die && child_die->tag)
8685         {
8686           process_die (child_die, cu);
8687           child_die = sibling_die (child_die);
8688         }
8689     }
8690 }
8691 \f
8692 /* DWO/DWP files.
8693
8694    http://gcc.gnu.org/wiki/DebugFission
8695    http://gcc.gnu.org/wiki/DebugFissionDWP
8696
8697    To simplify handling of both DWO files ("object" files with the DWARF info)
8698    and DWP files (a file with the DWOs packaged up into one file), we treat
8699    DWP files as having a collection of virtual DWO files.  */
8700
8701 static hashval_t
8702 hash_dwo_file (const void *item)
8703 {
8704   const struct dwo_file *dwo_file = item;
8705   hashval_t hash;
8706
8707   hash = htab_hash_string (dwo_file->dwo_name);
8708   if (dwo_file->comp_dir != NULL)
8709     hash += htab_hash_string (dwo_file->comp_dir);
8710   return hash;
8711 }
8712
8713 static int
8714 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8715 {
8716   const struct dwo_file *lhs = item_lhs;
8717   const struct dwo_file *rhs = item_rhs;
8718
8719   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8720     return 0;
8721   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8722     return lhs->comp_dir == rhs->comp_dir;
8723   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8724 }
8725
8726 /* Allocate a hash table for DWO files.  */
8727
8728 static htab_t
8729 allocate_dwo_file_hash_table (void)
8730 {
8731   struct objfile *objfile = dwarf2_per_objfile->objfile;
8732
8733   return htab_create_alloc_ex (41,
8734                                hash_dwo_file,
8735                                eq_dwo_file,
8736                                NULL,
8737                                &objfile->objfile_obstack,
8738                                hashtab_obstack_allocate,
8739                                dummy_obstack_deallocate);
8740 }
8741
8742 /* Lookup DWO file DWO_NAME.  */
8743
8744 static void **
8745 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8746 {
8747   struct dwo_file find_entry;
8748   void **slot;
8749
8750   if (dwarf2_per_objfile->dwo_files == NULL)
8751     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8752
8753   memset (&find_entry, 0, sizeof (find_entry));
8754   find_entry.dwo_name = dwo_name;
8755   find_entry.comp_dir = comp_dir;
8756   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8757
8758   return slot;
8759 }
8760
8761 static hashval_t
8762 hash_dwo_unit (const void *item)
8763 {
8764   const struct dwo_unit *dwo_unit = item;
8765
8766   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8767   return dwo_unit->signature;
8768 }
8769
8770 static int
8771 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8772 {
8773   const struct dwo_unit *lhs = item_lhs;
8774   const struct dwo_unit *rhs = item_rhs;
8775
8776   /* The signature is assumed to be unique within the DWO file.
8777      So while object file CU dwo_id's always have the value zero,
8778      that's OK, assuming each object file DWO file has only one CU,
8779      and that's the rule for now.  */
8780   return lhs->signature == rhs->signature;
8781 }
8782
8783 /* Allocate a hash table for DWO CUs,TUs.
8784    There is one of these tables for each of CUs,TUs for each DWO file.  */
8785
8786 static htab_t
8787 allocate_dwo_unit_table (struct objfile *objfile)
8788 {
8789   /* Start out with a pretty small number.
8790      Generally DWO files contain only one CU and maybe some TUs.  */
8791   return htab_create_alloc_ex (3,
8792                                hash_dwo_unit,
8793                                eq_dwo_unit,
8794                                NULL,
8795                                &objfile->objfile_obstack,
8796                                hashtab_obstack_allocate,
8797                                dummy_obstack_deallocate);
8798 }
8799
8800 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8801
8802 struct create_dwo_cu_data
8803 {
8804   struct dwo_file *dwo_file;
8805   struct dwo_unit dwo_unit;
8806 };
8807
8808 /* die_reader_func for create_dwo_cu.  */
8809
8810 static void
8811 create_dwo_cu_reader (const struct die_reader_specs *reader,
8812                       const gdb_byte *info_ptr,
8813                       struct die_info *comp_unit_die,
8814                       int has_children,
8815                       void *datap)
8816 {
8817   struct dwarf2_cu *cu = reader->cu;
8818   struct objfile *objfile = dwarf2_per_objfile->objfile;
8819   sect_offset offset = cu->per_cu->offset;
8820   struct dwarf2_section_info *section = cu->per_cu->section;
8821   struct create_dwo_cu_data *data = datap;
8822   struct dwo_file *dwo_file = data->dwo_file;
8823   struct dwo_unit *dwo_unit = &data->dwo_unit;
8824   struct attribute *attr;
8825
8826   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8827   if (attr == NULL)
8828     {
8829       complaint (&symfile_complaints,
8830                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8831                    " its dwo_id [in module %s]"),
8832                  offset.sect_off, dwo_file->dwo_name);
8833       return;
8834     }
8835
8836   dwo_unit->dwo_file = dwo_file;
8837   dwo_unit->signature = DW_UNSND (attr);
8838   dwo_unit->section = section;
8839   dwo_unit->offset = offset;
8840   dwo_unit->length = cu->per_cu->length;
8841
8842   if (dwarf2_read_debug)
8843     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8844                         offset.sect_off, hex_string (dwo_unit->signature));
8845 }
8846
8847 /* Create the dwo_unit for the lone CU in DWO_FILE.
8848    Note: This function processes DWO files only, not DWP files.  */
8849
8850 static struct dwo_unit *
8851 create_dwo_cu (struct dwo_file *dwo_file)
8852 {
8853   struct objfile *objfile = dwarf2_per_objfile->objfile;
8854   struct dwarf2_section_info *section = &dwo_file->sections.info;
8855   bfd *abfd;
8856   htab_t cu_htab;
8857   const gdb_byte *info_ptr, *end_ptr;
8858   struct create_dwo_cu_data create_dwo_cu_data;
8859   struct dwo_unit *dwo_unit;
8860
8861   dwarf2_read_section (objfile, section);
8862   info_ptr = section->buffer;
8863
8864   if (info_ptr == NULL)
8865     return NULL;
8866
8867   /* We can't set abfd until now because the section may be empty or
8868      not present, in which case section->asection will be NULL.  */
8869   abfd = section->asection->owner;
8870
8871   if (dwarf2_read_debug)
8872     {
8873       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8874                           bfd_section_name (abfd, section->asection),
8875                           bfd_get_filename (abfd));
8876     }
8877
8878   create_dwo_cu_data.dwo_file = dwo_file;
8879   dwo_unit = NULL;
8880
8881   end_ptr = info_ptr + section->size;
8882   while (info_ptr < end_ptr)
8883     {
8884       struct dwarf2_per_cu_data per_cu;
8885
8886       memset (&create_dwo_cu_data.dwo_unit, 0,
8887               sizeof (create_dwo_cu_data.dwo_unit));
8888       memset (&per_cu, 0, sizeof (per_cu));
8889       per_cu.objfile = objfile;
8890       per_cu.is_debug_types = 0;
8891       per_cu.offset.sect_off = info_ptr - section->buffer;
8892       per_cu.section = section;
8893
8894       init_cutu_and_read_dies_no_follow (&per_cu,
8895                                          &dwo_file->sections.abbrev,
8896                                          dwo_file,
8897                                          create_dwo_cu_reader,
8898                                          &create_dwo_cu_data);
8899
8900       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8901         {
8902           /* If we've already found one, complain.  We only support one
8903              because having more than one requires hacking the dwo_name of
8904              each to match, which is highly unlikely to happen.  */
8905           if (dwo_unit != NULL)
8906             {
8907               complaint (&symfile_complaints,
8908                          _("Multiple CUs in DWO file %s [in module %s]"),
8909                          dwo_file->dwo_name, objfile->name);
8910               break;
8911             }
8912
8913           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8914           *dwo_unit = create_dwo_cu_data.dwo_unit;
8915         }
8916
8917       info_ptr += per_cu.length;
8918     }
8919
8920   return dwo_unit;
8921 }
8922
8923 /* DWP file .debug_{cu,tu}_index section format:
8924    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8925
8926    DWP Version 1:
8927
8928    Both index sections have the same format, and serve to map a 64-bit
8929    signature to a set of section numbers.  Each section begins with a header,
8930    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8931    indexes, and a pool of 32-bit section numbers.  The index sections will be
8932    aligned at 8-byte boundaries in the file.
8933
8934    The index section header consists of:
8935
8936     V, 32 bit version number
8937     -, 32 bits unused
8938     N, 32 bit number of compilation units or type units in the index
8939     M, 32 bit number of slots in the hash table
8940
8941    Numbers are recorded using the byte order of the application binary.
8942
8943    We assume that N and M will not exceed 2^32 - 1.
8944
8945    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8946
8947    The hash table begins at offset 16 in the section, and consists of an array
8948    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8949    order of the application binary).  Unused slots in the hash table are 0.
8950    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8951
8952    The parallel table begins immediately after the hash table
8953    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8954    array of 32-bit indexes (using the byte order of the application binary),
8955    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8956    table contains a 32-bit index into the pool of section numbers.  For unused
8957    hash table slots, the corresponding entry in the parallel table will be 0.
8958
8959    Given a 64-bit compilation unit signature or a type signature S, an entry
8960    in the hash table is located as follows:
8961
8962    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8963       the low-order k bits all set to 1.
8964
8965    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8966
8967    3) If the hash table entry at index H matches the signature, use that
8968       entry.  If the hash table entry at index H is unused (all zeroes),
8969       terminate the search: the signature is not present in the table.
8970
8971    4) Let H = (H + H') modulo M. Repeat at Step 3.
8972
8973    Because M > N and H' and M are relatively prime, the search is guaranteed
8974    to stop at an unused slot or find the match.
8975
8976    The pool of section numbers begins immediately following the hash table
8977    (at offset 16 + 12 * M from the beginning of the section).  The pool of
8978    section numbers consists of an array of 32-bit words (using the byte order
8979    of the application binary).  Each item in the array is indexed starting
8980    from 0.  The hash table entry provides the index of the first section
8981    number in the set.  Additional section numbers in the set follow, and the
8982    set is terminated by a 0 entry (section number 0 is not used in ELF).
8983
8984    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8985    section must be the first entry in the set, and the .debug_abbrev.dwo must
8986    be the second entry. Other members of the set may follow in any order.  */
8987
8988 /* Create a hash table to map DWO IDs to their CU/TU entry in
8989    .debug_{info,types}.dwo in DWP_FILE.
8990    Returns NULL if there isn't one.
8991    Note: This function processes DWP files only, not DWO files.  */
8992
8993 static struct dwp_hash_table *
8994 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8995 {
8996   struct objfile *objfile = dwarf2_per_objfile->objfile;
8997   bfd *dbfd = dwp_file->dbfd;
8998   const gdb_byte *index_ptr, *index_end;
8999   struct dwarf2_section_info *index;
9000   uint32_t version, nr_units, nr_slots;
9001   struct dwp_hash_table *htab;
9002
9003   if (is_debug_types)
9004     index = &dwp_file->sections.tu_index;
9005   else
9006     index = &dwp_file->sections.cu_index;
9007
9008   if (dwarf2_section_empty_p (index))
9009     return NULL;
9010   dwarf2_read_section (objfile, index);
9011
9012   index_ptr = index->buffer;
9013   index_end = index_ptr + index->size;
9014
9015   version = read_4_bytes (dbfd, index_ptr);
9016   index_ptr += 8; /* Skip the unused word.  */
9017   nr_units = read_4_bytes (dbfd, index_ptr);
9018   index_ptr += 4;
9019   nr_slots = read_4_bytes (dbfd, index_ptr);
9020   index_ptr += 4;
9021
9022   if (version != 1)
9023     {
9024       error (_("Dwarf Error: unsupported DWP file version (%s)"
9025                " [in module %s]"),
9026              pulongest (version), dwp_file->name);
9027     }
9028   if (nr_slots != (nr_slots & -nr_slots))
9029     {
9030       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9031                " is not power of 2 [in module %s]"),
9032              pulongest (nr_slots), dwp_file->name);
9033     }
9034
9035   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9036   htab->nr_units = nr_units;
9037   htab->nr_slots = nr_slots;
9038   htab->hash_table = index_ptr;
9039   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9040   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9041
9042   return htab;
9043 }
9044
9045 /* Update SECTIONS with the data from SECTP.
9046
9047    This function is like the other "locate" section routines that are
9048    passed to bfd_map_over_sections, but in this context the sections to
9049    read comes from the DWP hash table, not the full ELF section table.
9050
9051    The result is non-zero for success, or zero if an error was found.  */
9052
9053 static int
9054 locate_virtual_dwo_sections (asection *sectp,
9055                              struct virtual_dwo_sections *sections)
9056 {
9057   const struct dwop_section_names *names = &dwop_section_names;
9058
9059   if (section_is_p (sectp->name, &names->abbrev_dwo))
9060     {
9061       /* There can be only one.  */
9062       if (sections->abbrev.asection != NULL)
9063         return 0;
9064       sections->abbrev.asection = sectp;
9065       sections->abbrev.size = bfd_get_section_size (sectp);
9066     }
9067   else if (section_is_p (sectp->name, &names->info_dwo)
9068            || section_is_p (sectp->name, &names->types_dwo))
9069     {
9070       /* There can be only one.  */
9071       if (sections->info_or_types.asection != NULL)
9072         return 0;
9073       sections->info_or_types.asection = sectp;
9074       sections->info_or_types.size = bfd_get_section_size (sectp);
9075     }
9076   else if (section_is_p (sectp->name, &names->line_dwo))
9077     {
9078       /* There can be only one.  */
9079       if (sections->line.asection != NULL)
9080         return 0;
9081       sections->line.asection = sectp;
9082       sections->line.size = bfd_get_section_size (sectp);
9083     }
9084   else if (section_is_p (sectp->name, &names->loc_dwo))
9085     {
9086       /* There can be only one.  */
9087       if (sections->loc.asection != NULL)
9088         return 0;
9089       sections->loc.asection = sectp;
9090       sections->loc.size = bfd_get_section_size (sectp);
9091     }
9092   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9093     {
9094       /* There can be only one.  */
9095       if (sections->macinfo.asection != NULL)
9096         return 0;
9097       sections->macinfo.asection = sectp;
9098       sections->macinfo.size = bfd_get_section_size (sectp);
9099     }
9100   else if (section_is_p (sectp->name, &names->macro_dwo))
9101     {
9102       /* There can be only one.  */
9103       if (sections->macro.asection != NULL)
9104         return 0;
9105       sections->macro.asection = sectp;
9106       sections->macro.size = bfd_get_section_size (sectp);
9107     }
9108   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9109     {
9110       /* There can be only one.  */
9111       if (sections->str_offsets.asection != NULL)
9112         return 0;
9113       sections->str_offsets.asection = sectp;
9114       sections->str_offsets.size = bfd_get_section_size (sectp);
9115     }
9116   else
9117     {
9118       /* No other kind of section is valid.  */
9119       return 0;
9120     }
9121
9122   return 1;
9123 }
9124
9125 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9126    HTAB is the hash table from the DWP file.
9127    SECTION_INDEX is the index of the DWO in HTAB.
9128    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9129
9130 static struct dwo_unit *
9131 create_dwo_in_dwp (struct dwp_file *dwp_file,
9132                    const struct dwp_hash_table *htab,
9133                    uint32_t section_index,
9134                    const char *comp_dir,
9135                    ULONGEST signature, int is_debug_types)
9136 {
9137   struct objfile *objfile = dwarf2_per_objfile->objfile;
9138   bfd *dbfd = dwp_file->dbfd;
9139   const char *kind = is_debug_types ? "TU" : "CU";
9140   struct dwo_file *dwo_file;
9141   struct dwo_unit *dwo_unit;
9142   struct virtual_dwo_sections sections;
9143   void **dwo_file_slot;
9144   char *virtual_dwo_name;
9145   struct dwarf2_section_info *cutu;
9146   struct cleanup *cleanups;
9147   int i;
9148
9149   if (dwarf2_read_debug)
9150     {
9151       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9152                           kind,
9153                           pulongest (section_index), hex_string (signature),
9154                           dwp_file->name);
9155     }
9156
9157   /* Fetch the sections of this DWO.
9158      Put a limit on the number of sections we look for so that bad data
9159      doesn't cause us to loop forever.  */
9160
9161 #define MAX_NR_DWO_SECTIONS \
9162   (1 /* .debug_info or .debug_types */ \
9163    + 1 /* .debug_abbrev */ \
9164    + 1 /* .debug_line */ \
9165    + 1 /* .debug_loc */ \
9166    + 1 /* .debug_str_offsets */ \
9167    + 1 /* .debug_macro */ \
9168    + 1 /* .debug_macinfo */ \
9169    + 1 /* trailing zero */)
9170
9171   memset (&sections, 0, sizeof (sections));
9172   cleanups = make_cleanup (null_cleanup, 0);
9173
9174   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9175     {
9176       asection *sectp;
9177       uint32_t section_nr =
9178         read_4_bytes (dbfd,
9179                       htab->section_pool
9180                       + (section_index + i) * sizeof (uint32_t));
9181
9182       if (section_nr == 0)
9183         break;
9184       if (section_nr >= dwp_file->num_sections)
9185         {
9186           error (_("Dwarf Error: bad DWP hash table, section number too large"
9187                    " [in module %s]"),
9188                  dwp_file->name);
9189         }
9190
9191       sectp = dwp_file->elf_sections[section_nr];
9192       if (! locate_virtual_dwo_sections (sectp, &sections))
9193         {
9194           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9195                    " [in module %s]"),
9196                  dwp_file->name);
9197         }
9198     }
9199
9200   if (i < 2
9201       || sections.info_or_types.asection == NULL
9202       || sections.abbrev.asection == NULL)
9203     {
9204       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9205                " [in module %s]"),
9206              dwp_file->name);
9207     }
9208   if (i == MAX_NR_DWO_SECTIONS)
9209     {
9210       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9211                " [in module %s]"),
9212              dwp_file->name);
9213     }
9214
9215   /* It's easier for the rest of the code if we fake a struct dwo_file and
9216      have dwo_unit "live" in that.  At least for now.
9217
9218      The DWP file can be made up of a random collection of CUs and TUs.
9219      However, for each CU + set of TUs that came from the same original DWO
9220      file, we want to combine them back into a virtual DWO file to save space
9221      (fewer struct dwo_file objects to allocated).  Remember that for really
9222      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9223
9224   virtual_dwo_name =
9225     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9226                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9227                 sections.line.asection ? sections.line.asection->id : 0,
9228                 sections.loc.asection ? sections.loc.asection->id : 0,
9229                 (sections.str_offsets.asection
9230                 ? sections.str_offsets.asection->id
9231                 : 0));
9232   make_cleanup (xfree, virtual_dwo_name);
9233   /* Can we use an existing virtual DWO file?  */
9234   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9235   /* Create one if necessary.  */
9236   if (*dwo_file_slot == NULL)
9237     {
9238       if (dwarf2_read_debug)
9239         {
9240           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9241                               virtual_dwo_name);
9242         }
9243       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9244       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9245                                           virtual_dwo_name,
9246                                           strlen (virtual_dwo_name));
9247       dwo_file->comp_dir = comp_dir;
9248       dwo_file->sections.abbrev = sections.abbrev;
9249       dwo_file->sections.line = sections.line;
9250       dwo_file->sections.loc = sections.loc;
9251       dwo_file->sections.macinfo = sections.macinfo;
9252       dwo_file->sections.macro = sections.macro;
9253       dwo_file->sections.str_offsets = sections.str_offsets;
9254       /* The "str" section is global to the entire DWP file.  */
9255       dwo_file->sections.str = dwp_file->sections.str;
9256       /* The info or types section is assigned later to dwo_unit,
9257          there's no need to record it in dwo_file.
9258          Also, we can't simply record type sections in dwo_file because
9259          we record a pointer into the vector in dwo_unit.  As we collect more
9260          types we'll grow the vector and eventually have to reallocate space
9261          for it, invalidating all the pointers into the current copy.  */
9262       *dwo_file_slot = dwo_file;
9263     }
9264   else
9265     {
9266       if (dwarf2_read_debug)
9267         {
9268           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9269                               virtual_dwo_name);
9270         }
9271       dwo_file = *dwo_file_slot;
9272     }
9273   do_cleanups (cleanups);
9274
9275   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9276   dwo_unit->dwo_file = dwo_file;
9277   dwo_unit->signature = signature;
9278   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9279                                      sizeof (struct dwarf2_section_info));
9280   *dwo_unit->section = sections.info_or_types;
9281   /* offset, length, type_offset_in_tu are set later.  */
9282
9283   return dwo_unit;
9284 }
9285
9286 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9287
9288 static struct dwo_unit *
9289 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9290                    const struct dwp_hash_table *htab,
9291                    const char *comp_dir,
9292                    ULONGEST signature, int is_debug_types)
9293 {
9294   bfd *dbfd = dwp_file->dbfd;
9295   uint32_t mask = htab->nr_slots - 1;
9296   uint32_t hash = signature & mask;
9297   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9298   unsigned int i;
9299   void **slot;
9300   struct dwo_unit find_dwo_cu, *dwo_cu;
9301
9302   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9303   find_dwo_cu.signature = signature;
9304   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9305
9306   if (*slot != NULL)
9307     return *slot;
9308
9309   /* Use a for loop so that we don't loop forever on bad debug info.  */
9310   for (i = 0; i < htab->nr_slots; ++i)
9311     {
9312       ULONGEST signature_in_table;
9313
9314       signature_in_table =
9315         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9316       if (signature_in_table == signature)
9317         {
9318           uint32_t section_index =
9319             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9320
9321           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9322                                      comp_dir, signature, is_debug_types);
9323           return *slot;
9324         }
9325       if (signature_in_table == 0)
9326         return NULL;
9327       hash = (hash + hash2) & mask;
9328     }
9329
9330   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9331            " [in module %s]"),
9332          dwp_file->name);
9333 }
9334
9335 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9336    Open the file specified by FILE_NAME and hand it off to BFD for
9337    preliminary analysis.  Return a newly initialized bfd *, which
9338    includes a canonicalized copy of FILE_NAME.
9339    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9340    SEARCH_CWD is true if the current directory is to be searched.
9341    It will be searched before debug-file-directory.
9342    If unable to find/open the file, return NULL.
9343    NOTE: This function is derived from symfile_bfd_open.  */
9344
9345 static bfd *
9346 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9347 {
9348   bfd *sym_bfd;
9349   int desc, flags;
9350   char *absolute_name;
9351   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9352      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9353      to debug_file_directory.  */
9354   char *search_path;
9355   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9356
9357   if (search_cwd)
9358     {
9359       if (*debug_file_directory != '\0')
9360         search_path = concat (".", dirname_separator_string,
9361                               debug_file_directory, NULL);
9362       else
9363         search_path = xstrdup (".");
9364     }
9365   else
9366     search_path = xstrdup (debug_file_directory);
9367
9368   flags = OPF_RETURN_REALPATH;
9369   if (is_dwp)
9370     flags |= OPF_SEARCH_IN_PATH;
9371   desc = openp (search_path, flags, file_name,
9372                 O_RDONLY | O_BINARY, &absolute_name);
9373   xfree (search_path);
9374   if (desc < 0)
9375     return NULL;
9376
9377   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9378   xfree (absolute_name);
9379   if (sym_bfd == NULL)
9380     return NULL;
9381   bfd_set_cacheable (sym_bfd, 1);
9382
9383   if (!bfd_check_format (sym_bfd, bfd_object))
9384     {
9385       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9386       return NULL;
9387     }
9388
9389   return sym_bfd;
9390 }
9391
9392 /* Try to open DWO file FILE_NAME.
9393    COMP_DIR is the DW_AT_comp_dir attribute.
9394    The result is the bfd handle of the file.
9395    If there is a problem finding or opening the file, return NULL.
9396    Upon success, the canonicalized path of the file is stored in the bfd,
9397    same as symfile_bfd_open.  */
9398
9399 static bfd *
9400 open_dwo_file (const char *file_name, const char *comp_dir)
9401 {
9402   bfd *abfd;
9403
9404   if (IS_ABSOLUTE_PATH (file_name))
9405     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
9406
9407   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9408
9409   if (comp_dir != NULL)
9410     {
9411       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9412
9413       /* NOTE: If comp_dir is a relative path, this will also try the
9414          search path, which seems useful.  */
9415       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
9416       xfree (path_to_try);
9417       if (abfd != NULL)
9418         return abfd;
9419     }
9420
9421   /* That didn't work, try debug-file-directory, which, despite its name,
9422      is a list of paths.  */
9423
9424   if (*debug_file_directory == '\0')
9425     return NULL;
9426
9427   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
9428 }
9429
9430 /* This function is mapped across the sections and remembers the offset and
9431    size of each of the DWO debugging sections we are interested in.  */
9432
9433 static void
9434 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9435 {
9436   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9437   const struct dwop_section_names *names = &dwop_section_names;
9438
9439   if (section_is_p (sectp->name, &names->abbrev_dwo))
9440     {
9441       dwo_sections->abbrev.asection = sectp;
9442       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9443     }
9444   else if (section_is_p (sectp->name, &names->info_dwo))
9445     {
9446       dwo_sections->info.asection = sectp;
9447       dwo_sections->info.size = bfd_get_section_size (sectp);
9448     }
9449   else if (section_is_p (sectp->name, &names->line_dwo))
9450     {
9451       dwo_sections->line.asection = sectp;
9452       dwo_sections->line.size = bfd_get_section_size (sectp);
9453     }
9454   else if (section_is_p (sectp->name, &names->loc_dwo))
9455     {
9456       dwo_sections->loc.asection = sectp;
9457       dwo_sections->loc.size = bfd_get_section_size (sectp);
9458     }
9459   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9460     {
9461       dwo_sections->macinfo.asection = sectp;
9462       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9463     }
9464   else if (section_is_p (sectp->name, &names->macro_dwo))
9465     {
9466       dwo_sections->macro.asection = sectp;
9467       dwo_sections->macro.size = bfd_get_section_size (sectp);
9468     }
9469   else if (section_is_p (sectp->name, &names->str_dwo))
9470     {
9471       dwo_sections->str.asection = sectp;
9472       dwo_sections->str.size = bfd_get_section_size (sectp);
9473     }
9474   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9475     {
9476       dwo_sections->str_offsets.asection = sectp;
9477       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9478     }
9479   else if (section_is_p (sectp->name, &names->types_dwo))
9480     {
9481       struct dwarf2_section_info type_section;
9482
9483       memset (&type_section, 0, sizeof (type_section));
9484       type_section.asection = sectp;
9485       type_section.size = bfd_get_section_size (sectp);
9486       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9487                      &type_section);
9488     }
9489 }
9490
9491 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9492    by PER_CU.  This is for the non-DWP case.
9493    The result is NULL if DWO_NAME can't be found.  */
9494
9495 static struct dwo_file *
9496 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9497                         const char *dwo_name, const char *comp_dir)
9498 {
9499   struct objfile *objfile = dwarf2_per_objfile->objfile;
9500   struct dwo_file *dwo_file;
9501   bfd *dbfd;
9502   struct cleanup *cleanups;
9503
9504   dbfd = open_dwo_file (dwo_name, comp_dir);
9505   if (dbfd == NULL)
9506     {
9507       if (dwarf2_read_debug)
9508         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9509       return NULL;
9510     }
9511   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9512   dwo_file->dwo_name = dwo_name;
9513   dwo_file->comp_dir = comp_dir;
9514   dwo_file->dbfd = dbfd;
9515
9516   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9517
9518   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9519
9520   dwo_file->cu = create_dwo_cu (dwo_file);
9521
9522   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9523                                                  dwo_file->sections.types);
9524
9525   discard_cleanups (cleanups);
9526
9527   if (dwarf2_read_debug)
9528     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9529
9530   return dwo_file;
9531 }
9532
9533 /* This function is mapped across the sections and remembers the offset and
9534    size of each of the DWP debugging sections we are interested in.  */
9535
9536 static void
9537 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9538 {
9539   struct dwp_file *dwp_file = dwp_file_ptr;
9540   const struct dwop_section_names *names = &dwop_section_names;
9541   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9542
9543   /* Record the ELF section number for later lookup: this is what the
9544      .debug_cu_index,.debug_tu_index tables use.  */
9545   gdb_assert (elf_section_nr < dwp_file->num_sections);
9546   dwp_file->elf_sections[elf_section_nr] = sectp;
9547
9548   /* Look for specific sections that we need.  */
9549   if (section_is_p (sectp->name, &names->str_dwo))
9550     {
9551       dwp_file->sections.str.asection = sectp;
9552       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9553     }
9554   else if (section_is_p (sectp->name, &names->cu_index))
9555     {
9556       dwp_file->sections.cu_index.asection = sectp;
9557       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9558     }
9559   else if (section_is_p (sectp->name, &names->tu_index))
9560     {
9561       dwp_file->sections.tu_index.asection = sectp;
9562       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9563     }
9564 }
9565
9566 /* Hash function for dwp_file loaded CUs/TUs.  */
9567
9568 static hashval_t
9569 hash_dwp_loaded_cutus (const void *item)
9570 {
9571   const struct dwo_unit *dwo_unit = item;
9572
9573   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9574   return dwo_unit->signature;
9575 }
9576
9577 /* Equality function for dwp_file loaded CUs/TUs.  */
9578
9579 static int
9580 eq_dwp_loaded_cutus (const void *a, const void *b)
9581 {
9582   const struct dwo_unit *dua = a;
9583   const struct dwo_unit *dub = b;
9584
9585   return dua->signature == dub->signature;
9586 }
9587
9588 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9589
9590 static htab_t
9591 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9592 {
9593   return htab_create_alloc_ex (3,
9594                                hash_dwp_loaded_cutus,
9595                                eq_dwp_loaded_cutus,
9596                                NULL,
9597                                &objfile->objfile_obstack,
9598                                hashtab_obstack_allocate,
9599                                dummy_obstack_deallocate);
9600 }
9601
9602 /* Try to open DWP file FILE_NAME.
9603    The result is the bfd handle of the file.
9604    If there is a problem finding or opening the file, return NULL.
9605    Upon success, the canonicalized path of the file is stored in the bfd,
9606    same as symfile_bfd_open.  */
9607
9608 static bfd *
9609 open_dwp_file (const char *file_name)
9610 {
9611   bfd *abfd;
9612
9613   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
9614   if (abfd != NULL)
9615     return abfd;
9616
9617   /* Work around upstream bug 15652.
9618      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
9619      [Whether that's a "bug" is debatable, but it is getting in our way.]
9620      We have no real idea where the dwp file is, because gdb's realpath-ing
9621      of the executable's path may have discarded the needed info.
9622      [IWBN if the dwp file name was recorded in the executable, akin to
9623      .gnu_debuglink, but that doesn't exist yet.]
9624      Strip the directory from FILE_NAME and search again.  */
9625   if (*debug_file_directory != '\0')
9626     {
9627       /* Don't implicitly search the current directory here.
9628          If the user wants to search "." to handle this case,
9629          it must be added to debug-file-directory.  */
9630       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
9631                                  0 /*search_cwd*/);
9632     }
9633
9634   return NULL;
9635 }
9636
9637 /* Initialize the use of the DWP file for the current objfile.
9638    By convention the name of the DWP file is ${objfile}.dwp.
9639    The result is NULL if it can't be found.  */
9640
9641 static struct dwp_file *
9642 open_and_init_dwp_file (void)
9643 {
9644   struct objfile *objfile = dwarf2_per_objfile->objfile;
9645   struct dwp_file *dwp_file;
9646   char *dwp_name;
9647   bfd *dbfd;
9648   struct cleanup *cleanups;
9649
9650   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9651   cleanups = make_cleanup (xfree, dwp_name);
9652
9653   dbfd = open_dwp_file (dwp_name);
9654   if (dbfd == NULL)
9655     {
9656       if (dwarf2_read_debug)
9657         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9658       do_cleanups (cleanups);
9659       return NULL;
9660     }
9661   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9662   dwp_file->name = bfd_get_filename (dbfd);
9663   dwp_file->dbfd = dbfd;
9664   do_cleanups (cleanups);
9665
9666   /* +1: section 0 is unused */
9667   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9668   dwp_file->elf_sections =
9669     OBSTACK_CALLOC (&objfile->objfile_obstack,
9670                     dwp_file->num_sections, asection *);
9671
9672   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9673
9674   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9675
9676   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9677
9678   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9679
9680   if (dwarf2_read_debug)
9681     {
9682       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9683       fprintf_unfiltered (gdb_stdlog,
9684                           "    %s CUs, %s TUs\n",
9685                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9686                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9687     }
9688
9689   return dwp_file;
9690 }
9691
9692 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9693
9694 static struct dwp_file *
9695 get_dwp_file (void)
9696 {
9697   if (! dwarf2_per_objfile->dwp_checked)
9698     {
9699       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9700       dwarf2_per_objfile->dwp_checked = 1;
9701     }
9702   return dwarf2_per_objfile->dwp_file;
9703 }
9704
9705 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9706    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9707    or in the DWP file for the objfile, referenced by THIS_UNIT.
9708    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9709    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9710
9711    This is called, for example, when wanting to read a variable with a
9712    complex location.  Therefore we don't want to do file i/o for every call.
9713    Therefore we don't want to look for a DWO file on every call.
9714    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9715    then we check if we've already seen DWO_NAME, and only THEN do we check
9716    for a DWO file.
9717
9718    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9719    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9720
9721 static struct dwo_unit *
9722 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9723                  const char *dwo_name, const char *comp_dir,
9724                  ULONGEST signature, int is_debug_types)
9725 {
9726   struct objfile *objfile = dwarf2_per_objfile->objfile;
9727   const char *kind = is_debug_types ? "TU" : "CU";
9728   void **dwo_file_slot;
9729   struct dwo_file *dwo_file;
9730   struct dwp_file *dwp_file;
9731
9732   /* First see if there's a DWP file.
9733      If we have a DWP file but didn't find the DWO inside it, don't
9734      look for the original DWO file.  It makes gdb behave differently
9735      depending on whether one is debugging in the build tree.  */
9736
9737   dwp_file = get_dwp_file ();
9738   if (dwp_file != NULL)
9739     {
9740       const struct dwp_hash_table *dwp_htab =
9741         is_debug_types ? dwp_file->tus : dwp_file->cus;
9742
9743       if (dwp_htab != NULL)
9744         {
9745           struct dwo_unit *dwo_cutu =
9746             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9747                                signature, is_debug_types);
9748
9749           if (dwo_cutu != NULL)
9750             {
9751               if (dwarf2_read_debug)
9752                 {
9753                   fprintf_unfiltered (gdb_stdlog,
9754                                       "Virtual DWO %s %s found: @%s\n",
9755                                       kind, hex_string (signature),
9756                                       host_address_to_string (dwo_cutu));
9757                 }
9758               return dwo_cutu;
9759             }
9760         }
9761     }
9762   else
9763     {
9764       /* No DWP file, look for the DWO file.  */
9765
9766       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9767       if (*dwo_file_slot == NULL)
9768         {
9769           /* Read in the file and build a table of the CUs/TUs it contains.  */
9770           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9771         }
9772       /* NOTE: This will be NULL if unable to open the file.  */
9773       dwo_file = *dwo_file_slot;
9774
9775       if (dwo_file != NULL)
9776         {
9777           struct dwo_unit *dwo_cutu = NULL;
9778
9779           if (is_debug_types && dwo_file->tus)
9780             {
9781               struct dwo_unit find_dwo_cutu;
9782
9783               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9784               find_dwo_cutu.signature = signature;
9785               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9786             }
9787           else if (!is_debug_types && dwo_file->cu)
9788             {
9789               if (signature == dwo_file->cu->signature)
9790                 dwo_cutu = dwo_file->cu;
9791             }
9792
9793           if (dwo_cutu != NULL)
9794             {
9795               if (dwarf2_read_debug)
9796                 {
9797                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9798                                       kind, dwo_name, hex_string (signature),
9799                                       host_address_to_string (dwo_cutu));
9800                 }
9801               return dwo_cutu;
9802             }
9803         }
9804     }
9805
9806   /* We didn't find it.  This could mean a dwo_id mismatch, or
9807      someone deleted the DWO/DWP file, or the search path isn't set up
9808      correctly to find the file.  */
9809
9810   if (dwarf2_read_debug)
9811     {
9812       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9813                           kind, dwo_name, hex_string (signature));
9814     }
9815
9816   /* This is a warning and not a complaint because it can be caused by
9817      pilot error (e.g., user accidentally deleting the DWO).  */
9818   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9819              " [in module %s]"),
9820            kind, dwo_name, hex_string (signature),
9821            this_unit->is_debug_types ? "TU" : "CU",
9822            this_unit->offset.sect_off, objfile->name);
9823   return NULL;
9824 }
9825
9826 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9827    See lookup_dwo_cutu_unit for details.  */
9828
9829 static struct dwo_unit *
9830 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9831                       const char *dwo_name, const char *comp_dir,
9832                       ULONGEST signature)
9833 {
9834   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9835 }
9836
9837 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9838    See lookup_dwo_cutu_unit for details.  */
9839
9840 static struct dwo_unit *
9841 lookup_dwo_type_unit (struct signatured_type *this_tu,
9842                       const char *dwo_name, const char *comp_dir)
9843 {
9844   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9845 }
9846
9847 /* Traversal function for queue_and_load_all_dwo_tus.  */
9848
9849 static int
9850 queue_and_load_dwo_tu (void **slot, void *info)
9851 {
9852   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
9853   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
9854   ULONGEST signature = dwo_unit->signature;
9855   struct signatured_type *sig_type =
9856     lookup_dwo_signatured_type (per_cu->cu, signature);
9857
9858   if (sig_type != NULL)
9859     {
9860       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
9861
9862       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
9863          a real dependency of PER_CU on SIG_TYPE.  That is detected later
9864          while processing PER_CU.  */
9865       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
9866         load_full_type_unit (sig_cu);
9867       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
9868     }
9869
9870   return 1;
9871 }
9872
9873 /* Queue all TUs contained in the DWO of PER_CU to be read in.
9874    The DWO may have the only definition of the type, though it may not be
9875    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
9876    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
9877
9878 static void
9879 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
9880 {
9881   struct dwo_unit *dwo_unit;
9882   struct dwo_file *dwo_file;
9883
9884   gdb_assert (!per_cu->is_debug_types);
9885   gdb_assert (get_dwp_file () == NULL);
9886   gdb_assert (per_cu->cu != NULL);
9887
9888   dwo_unit = per_cu->cu->dwo_unit;
9889   gdb_assert (dwo_unit != NULL);
9890
9891   dwo_file = dwo_unit->dwo_file;
9892   if (dwo_file->tus != NULL)
9893     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
9894 }
9895
9896 /* Free all resources associated with DWO_FILE.
9897    Close the DWO file and munmap the sections.
9898    All memory should be on the objfile obstack.  */
9899
9900 static void
9901 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9902 {
9903   int ix;
9904   struct dwarf2_section_info *section;
9905
9906   /* Note: dbfd is NULL for virtual DWO files.  */
9907   gdb_bfd_unref (dwo_file->dbfd);
9908
9909   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9910 }
9911
9912 /* Wrapper for free_dwo_file for use in cleanups.  */
9913
9914 static void
9915 free_dwo_file_cleanup (void *arg)
9916 {
9917   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9918   struct objfile *objfile = dwarf2_per_objfile->objfile;
9919
9920   free_dwo_file (dwo_file, objfile);
9921 }
9922
9923 /* Traversal function for free_dwo_files.  */
9924
9925 static int
9926 free_dwo_file_from_slot (void **slot, void *info)
9927 {
9928   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9929   struct objfile *objfile = (struct objfile *) info;
9930
9931   free_dwo_file (dwo_file, objfile);
9932
9933   return 1;
9934 }
9935
9936 /* Free all resources associated with DWO_FILES.  */
9937
9938 static void
9939 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9940 {
9941   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9942 }
9943 \f
9944 /* Read in various DIEs.  */
9945
9946 /* qsort helper for inherit_abstract_dies.  */
9947
9948 static int
9949 unsigned_int_compar (const void *ap, const void *bp)
9950 {
9951   unsigned int a = *(unsigned int *) ap;
9952   unsigned int b = *(unsigned int *) bp;
9953
9954   return (a > b) - (b > a);
9955 }
9956
9957 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9958    Inherit only the children of the DW_AT_abstract_origin DIE not being
9959    already referenced by DW_AT_abstract_origin from the children of the
9960    current DIE.  */
9961
9962 static void
9963 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9964 {
9965   struct die_info *child_die;
9966   unsigned die_children_count;
9967   /* CU offsets which were referenced by children of the current DIE.  */
9968   sect_offset *offsets;
9969   sect_offset *offsets_end, *offsetp;
9970   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9971   struct die_info *origin_die;
9972   /* Iterator of the ORIGIN_DIE children.  */
9973   struct die_info *origin_child_die;
9974   struct cleanup *cleanups;
9975   struct attribute *attr;
9976   struct dwarf2_cu *origin_cu;
9977   struct pending **origin_previous_list_in_scope;
9978
9979   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9980   if (!attr)
9981     return;
9982
9983   /* Note that following die references may follow to a die in a
9984      different cu.  */
9985
9986   origin_cu = cu;
9987   origin_die = follow_die_ref (die, attr, &origin_cu);
9988
9989   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9990      symbols in.  */
9991   origin_previous_list_in_scope = origin_cu->list_in_scope;
9992   origin_cu->list_in_scope = cu->list_in_scope;
9993
9994   if (die->tag != origin_die->tag
9995       && !(die->tag == DW_TAG_inlined_subroutine
9996            && origin_die->tag == DW_TAG_subprogram))
9997     complaint (&symfile_complaints,
9998                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9999                die->offset.sect_off, origin_die->offset.sect_off);
10000
10001   child_die = die->child;
10002   die_children_count = 0;
10003   while (child_die && child_die->tag)
10004     {
10005       child_die = sibling_die (child_die);
10006       die_children_count++;
10007     }
10008   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10009   cleanups = make_cleanup (xfree, offsets);
10010
10011   offsets_end = offsets;
10012   child_die = die->child;
10013   while (child_die && child_die->tag)
10014     {
10015       /* For each CHILD_DIE, find the corresponding child of
10016          ORIGIN_DIE.  If there is more than one layer of
10017          DW_AT_abstract_origin, follow them all; there shouldn't be,
10018          but GCC versions at least through 4.4 generate this (GCC PR
10019          40573).  */
10020       struct die_info *child_origin_die = child_die;
10021       struct dwarf2_cu *child_origin_cu = cu;
10022
10023       while (1)
10024         {
10025           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10026                               child_origin_cu);
10027           if (attr == NULL)
10028             break;
10029           child_origin_die = follow_die_ref (child_origin_die, attr,
10030                                              &child_origin_cu);
10031         }
10032
10033       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10034          counterpart may exist.  */
10035       if (child_origin_die != child_die)
10036         {
10037           if (child_die->tag != child_origin_die->tag
10038               && !(child_die->tag == DW_TAG_inlined_subroutine
10039                    && child_origin_die->tag == DW_TAG_subprogram))
10040             complaint (&symfile_complaints,
10041                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10042                          "different tags"), child_die->offset.sect_off,
10043                        child_origin_die->offset.sect_off);
10044           if (child_origin_die->parent != origin_die)
10045             complaint (&symfile_complaints,
10046                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10047                          "different parents"), child_die->offset.sect_off,
10048                        child_origin_die->offset.sect_off);
10049           else
10050             *offsets_end++ = child_origin_die->offset;
10051         }
10052       child_die = sibling_die (child_die);
10053     }
10054   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10055          unsigned_int_compar);
10056   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10057     if (offsetp[-1].sect_off == offsetp->sect_off)
10058       complaint (&symfile_complaints,
10059                  _("Multiple children of DIE 0x%x refer "
10060                    "to DIE 0x%x as their abstract origin"),
10061                  die->offset.sect_off, offsetp->sect_off);
10062
10063   offsetp = offsets;
10064   origin_child_die = origin_die->child;
10065   while (origin_child_die && origin_child_die->tag)
10066     {
10067       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10068       while (offsetp < offsets_end
10069              && offsetp->sect_off < origin_child_die->offset.sect_off)
10070         offsetp++;
10071       if (offsetp >= offsets_end
10072           || offsetp->sect_off > origin_child_die->offset.sect_off)
10073         {
10074           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10075           process_die (origin_child_die, origin_cu);
10076         }
10077       origin_child_die = sibling_die (origin_child_die);
10078     }
10079   origin_cu->list_in_scope = origin_previous_list_in_scope;
10080
10081   do_cleanups (cleanups);
10082 }
10083
10084 static void
10085 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10086 {
10087   struct objfile *objfile = cu->objfile;
10088   struct context_stack *new;
10089   CORE_ADDR lowpc;
10090   CORE_ADDR highpc;
10091   struct die_info *child_die;
10092   struct attribute *attr, *call_line, *call_file;
10093   const char *name;
10094   CORE_ADDR baseaddr;
10095   struct block *block;
10096   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10097   VEC (symbolp) *template_args = NULL;
10098   struct template_symbol *templ_func = NULL;
10099
10100   if (inlined_func)
10101     {
10102       /* If we do not have call site information, we can't show the
10103          caller of this inlined function.  That's too confusing, so
10104          only use the scope for local variables.  */
10105       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10106       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10107       if (call_line == NULL || call_file == NULL)
10108         {
10109           read_lexical_block_scope (die, cu);
10110           return;
10111         }
10112     }
10113
10114   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10115
10116   name = dwarf2_name (die, cu);
10117
10118   /* Ignore functions with missing or empty names.  These are actually
10119      illegal according to the DWARF standard.  */
10120   if (name == NULL)
10121     {
10122       complaint (&symfile_complaints,
10123                  _("missing name for subprogram DIE at %d"),
10124                  die->offset.sect_off);
10125       return;
10126     }
10127
10128   /* Ignore functions with missing or invalid low and high pc attributes.  */
10129   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10130     {
10131       attr = dwarf2_attr (die, DW_AT_external, cu);
10132       if (!attr || !DW_UNSND (attr))
10133         complaint (&symfile_complaints,
10134                    _("cannot get low and high bounds "
10135                      "for subprogram DIE at %d"),
10136                    die->offset.sect_off);
10137       return;
10138     }
10139
10140   lowpc += baseaddr;
10141   highpc += baseaddr;
10142
10143   /* If we have any template arguments, then we must allocate a
10144      different sort of symbol.  */
10145   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10146     {
10147       if (child_die->tag == DW_TAG_template_type_param
10148           || child_die->tag == DW_TAG_template_value_param)
10149         {
10150           templ_func = allocate_template_symbol (objfile);
10151           templ_func->base.is_cplus_template_function = 1;
10152           break;
10153         }
10154     }
10155
10156   new = push_context (0, lowpc);
10157   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10158                                (struct symbol *) templ_func);
10159
10160   /* If there is a location expression for DW_AT_frame_base, record
10161      it.  */
10162   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10163   if (attr)
10164     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10165
10166   cu->list_in_scope = &local_symbols;
10167
10168   if (die->child != NULL)
10169     {
10170       child_die = die->child;
10171       while (child_die && child_die->tag)
10172         {
10173           if (child_die->tag == DW_TAG_template_type_param
10174               || child_die->tag == DW_TAG_template_value_param)
10175             {
10176               struct symbol *arg = new_symbol (child_die, NULL, cu);
10177
10178               if (arg != NULL)
10179                 VEC_safe_push (symbolp, template_args, arg);
10180             }
10181           else
10182             process_die (child_die, cu);
10183           child_die = sibling_die (child_die);
10184         }
10185     }
10186
10187   inherit_abstract_dies (die, cu);
10188
10189   /* If we have a DW_AT_specification, we might need to import using
10190      directives from the context of the specification DIE.  See the
10191      comment in determine_prefix.  */
10192   if (cu->language == language_cplus
10193       && dwarf2_attr (die, DW_AT_specification, cu))
10194     {
10195       struct dwarf2_cu *spec_cu = cu;
10196       struct die_info *spec_die = die_specification (die, &spec_cu);
10197
10198       while (spec_die)
10199         {
10200           child_die = spec_die->child;
10201           while (child_die && child_die->tag)
10202             {
10203               if (child_die->tag == DW_TAG_imported_module)
10204                 process_die (child_die, spec_cu);
10205               child_die = sibling_die (child_die);
10206             }
10207
10208           /* In some cases, GCC generates specification DIEs that
10209              themselves contain DW_AT_specification attributes.  */
10210           spec_die = die_specification (spec_die, &spec_cu);
10211         }
10212     }
10213
10214   new = pop_context ();
10215   /* Make a block for the local symbols within.  */
10216   block = finish_block (new->name, &local_symbols, new->old_blocks,
10217                         lowpc, highpc, objfile);
10218
10219   /* For C++, set the block's scope.  */
10220   if ((cu->language == language_cplus || cu->language == language_fortran)
10221       && cu->processing_has_namespace_info)
10222     block_set_scope (block, determine_prefix (die, cu),
10223                      &objfile->objfile_obstack);
10224
10225   /* If we have address ranges, record them.  */
10226   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10227
10228   /* Attach template arguments to function.  */
10229   if (! VEC_empty (symbolp, template_args))
10230     {
10231       gdb_assert (templ_func != NULL);
10232
10233       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10234       templ_func->template_arguments
10235         = obstack_alloc (&objfile->objfile_obstack,
10236                          (templ_func->n_template_arguments
10237                           * sizeof (struct symbol *)));
10238       memcpy (templ_func->template_arguments,
10239               VEC_address (symbolp, template_args),
10240               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10241       VEC_free (symbolp, template_args);
10242     }
10243
10244   /* In C++, we can have functions nested inside functions (e.g., when
10245      a function declares a class that has methods).  This means that
10246      when we finish processing a function scope, we may need to go
10247      back to building a containing block's symbol lists.  */
10248   local_symbols = new->locals;
10249   using_directives = new->using_directives;
10250
10251   /* If we've finished processing a top-level function, subsequent
10252      symbols go in the file symbol list.  */
10253   if (outermost_context_p ())
10254     cu->list_in_scope = &file_symbols;
10255 }
10256
10257 /* Process all the DIES contained within a lexical block scope.  Start
10258    a new scope, process the dies, and then close the scope.  */
10259
10260 static void
10261 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10262 {
10263   struct objfile *objfile = cu->objfile;
10264   struct context_stack *new;
10265   CORE_ADDR lowpc, highpc;
10266   struct die_info *child_die;
10267   CORE_ADDR baseaddr;
10268
10269   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10270
10271   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10272   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10273      as multiple lexical blocks?  Handling children in a sane way would
10274      be nasty.  Might be easier to properly extend generic blocks to
10275      describe ranges.  */
10276   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10277     return;
10278   lowpc += baseaddr;
10279   highpc += baseaddr;
10280
10281   push_context (0, lowpc);
10282   if (die->child != NULL)
10283     {
10284       child_die = die->child;
10285       while (child_die && child_die->tag)
10286         {
10287           process_die (child_die, cu);
10288           child_die = sibling_die (child_die);
10289         }
10290     }
10291   new = pop_context ();
10292
10293   if (local_symbols != NULL || using_directives != NULL)
10294     {
10295       struct block *block
10296         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10297                         highpc, objfile);
10298
10299       /* Note that recording ranges after traversing children, as we
10300          do here, means that recording a parent's ranges entails
10301          walking across all its children's ranges as they appear in
10302          the address map, which is quadratic behavior.
10303
10304          It would be nicer to record the parent's ranges before
10305          traversing its children, simply overriding whatever you find
10306          there.  But since we don't even decide whether to create a
10307          block until after we've traversed its children, that's hard
10308          to do.  */
10309       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10310     }
10311   local_symbols = new->locals;
10312   using_directives = new->using_directives;
10313 }
10314
10315 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10316
10317 static void
10318 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10319 {
10320   struct objfile *objfile = cu->objfile;
10321   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10322   CORE_ADDR pc, baseaddr;
10323   struct attribute *attr;
10324   struct call_site *call_site, call_site_local;
10325   void **slot;
10326   int nparams;
10327   struct die_info *child_die;
10328
10329   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10330
10331   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10332   if (!attr)
10333     {
10334       complaint (&symfile_complaints,
10335                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10336                    "DIE 0x%x [in module %s]"),
10337                  die->offset.sect_off, objfile->name);
10338       return;
10339     }
10340   pc = DW_ADDR (attr) + baseaddr;
10341
10342   if (cu->call_site_htab == NULL)
10343     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10344                                                NULL, &objfile->objfile_obstack,
10345                                                hashtab_obstack_allocate, NULL);
10346   call_site_local.pc = pc;
10347   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10348   if (*slot != NULL)
10349     {
10350       complaint (&symfile_complaints,
10351                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10352                    "DIE 0x%x [in module %s]"),
10353                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
10354       return;
10355     }
10356
10357   /* Count parameters at the caller.  */
10358
10359   nparams = 0;
10360   for (child_die = die->child; child_die && child_die->tag;
10361        child_die = sibling_die (child_die))
10362     {
10363       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10364         {
10365           complaint (&symfile_complaints,
10366                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10367                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10368                      child_die->tag, child_die->offset.sect_off, objfile->name);
10369           continue;
10370         }
10371
10372       nparams++;
10373     }
10374
10375   call_site = obstack_alloc (&objfile->objfile_obstack,
10376                              (sizeof (*call_site)
10377                               + (sizeof (*call_site->parameter)
10378                                  * (nparams - 1))));
10379   *slot = call_site;
10380   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10381   call_site->pc = pc;
10382
10383   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10384     {
10385       struct die_info *func_die;
10386
10387       /* Skip also over DW_TAG_inlined_subroutine.  */
10388       for (func_die = die->parent;
10389            func_die && func_die->tag != DW_TAG_subprogram
10390            && func_die->tag != DW_TAG_subroutine_type;
10391            func_die = func_die->parent);
10392
10393       /* DW_AT_GNU_all_call_sites is a superset
10394          of DW_AT_GNU_all_tail_call_sites.  */
10395       if (func_die
10396           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10397           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10398         {
10399           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10400              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10401              both the initial caller containing the real return address PC and
10402              the final callee containing the current PC of a chain of tail
10403              calls do not need to have the tail call list complete.  But any
10404              function candidate for a virtual tail call frame searched via
10405              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10406              determined unambiguously.  */
10407         }
10408       else
10409         {
10410           struct type *func_type = NULL;
10411
10412           if (func_die)
10413             func_type = get_die_type (func_die, cu);
10414           if (func_type != NULL)
10415             {
10416               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10417
10418               /* Enlist this call site to the function.  */
10419               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10420               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10421             }
10422           else
10423             complaint (&symfile_complaints,
10424                        _("Cannot find function owning DW_TAG_GNU_call_site "
10425                          "DIE 0x%x [in module %s]"),
10426                        die->offset.sect_off, objfile->name);
10427         }
10428     }
10429
10430   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10431   if (attr == NULL)
10432     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10433   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10434   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10435     /* Keep NULL DWARF_BLOCK.  */;
10436   else if (attr_form_is_block (attr))
10437     {
10438       struct dwarf2_locexpr_baton *dlbaton;
10439
10440       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10441       dlbaton->data = DW_BLOCK (attr)->data;
10442       dlbaton->size = DW_BLOCK (attr)->size;
10443       dlbaton->per_cu = cu->per_cu;
10444
10445       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10446     }
10447   else if (attr_form_is_ref (attr))
10448     {
10449       struct dwarf2_cu *target_cu = cu;
10450       struct die_info *target_die;
10451
10452       target_die = follow_die_ref (die, attr, &target_cu);
10453       gdb_assert (target_cu->objfile == objfile);
10454       if (die_is_declaration (target_die, target_cu))
10455         {
10456           const char *target_physname = NULL;
10457           struct attribute *target_attr;
10458
10459           /* Prefer the mangled name; otherwise compute the demangled one.  */
10460           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10461           if (target_attr == NULL)
10462             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10463                                        target_cu);
10464           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10465             target_physname = DW_STRING (target_attr);
10466           else
10467             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10468           if (target_physname == NULL)
10469             complaint (&symfile_complaints,
10470                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10471                          "physname, for referencing DIE 0x%x [in module %s]"),
10472                        die->offset.sect_off, objfile->name);
10473           else
10474             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10475         }
10476       else
10477         {
10478           CORE_ADDR lowpc;
10479
10480           /* DW_AT_entry_pc should be preferred.  */
10481           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10482             complaint (&symfile_complaints,
10483                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10484                          "low pc, for referencing DIE 0x%x [in module %s]"),
10485                        die->offset.sect_off, objfile->name);
10486           else
10487             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10488         }
10489     }
10490   else
10491     complaint (&symfile_complaints,
10492                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10493                  "block nor reference, for DIE 0x%x [in module %s]"),
10494                die->offset.sect_off, objfile->name);
10495
10496   call_site->per_cu = cu->per_cu;
10497
10498   for (child_die = die->child;
10499        child_die && child_die->tag;
10500        child_die = sibling_die (child_die))
10501     {
10502       struct call_site_parameter *parameter;
10503       struct attribute *loc, *origin;
10504
10505       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10506         {
10507           /* Already printed the complaint above.  */
10508           continue;
10509         }
10510
10511       gdb_assert (call_site->parameter_count < nparams);
10512       parameter = &call_site->parameter[call_site->parameter_count];
10513
10514       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10515          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10516          register is contained in DW_AT_GNU_call_site_value.  */
10517
10518       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10519       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10520       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
10521         {
10522           sect_offset offset;
10523
10524           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10525           offset = dwarf2_get_ref_die_offset (origin);
10526           if (!offset_in_cu_p (&cu->header, offset))
10527             {
10528               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10529                  binding can be done only inside one CU.  Such referenced DIE
10530                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10531               complaint (&symfile_complaints,
10532                          _("DW_AT_abstract_origin offset is not in CU for "
10533                            "DW_TAG_GNU_call_site child DIE 0x%x "
10534                            "[in module %s]"),
10535                          child_die->offset.sect_off, objfile->name);
10536               continue;
10537             }
10538           parameter->u.param_offset.cu_off = (offset.sect_off
10539                                               - cu->header.offset.sect_off);
10540         }
10541       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10542         {
10543           complaint (&symfile_complaints,
10544                      _("No DW_FORM_block* DW_AT_location for "
10545                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10546                      child_die->offset.sect_off, objfile->name);
10547           continue;
10548         }
10549       else
10550         {
10551           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10552             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10553           if (parameter->u.dwarf_reg != -1)
10554             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10555           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10556                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10557                                              &parameter->u.fb_offset))
10558             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10559           else
10560             {
10561               complaint (&symfile_complaints,
10562                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10563                            "for DW_FORM_block* DW_AT_location is supported for "
10564                            "DW_TAG_GNU_call_site child DIE 0x%x "
10565                            "[in module %s]"),
10566                          child_die->offset.sect_off, objfile->name);
10567               continue;
10568             }
10569         }
10570
10571       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10572       if (!attr_form_is_block (attr))
10573         {
10574           complaint (&symfile_complaints,
10575                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10576                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10577                      child_die->offset.sect_off, objfile->name);
10578           continue;
10579         }
10580       parameter->value = DW_BLOCK (attr)->data;
10581       parameter->value_size = DW_BLOCK (attr)->size;
10582
10583       /* Parameters are not pre-cleared by memset above.  */
10584       parameter->data_value = NULL;
10585       parameter->data_value_size = 0;
10586       call_site->parameter_count++;
10587
10588       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10589       if (attr)
10590         {
10591           if (!attr_form_is_block (attr))
10592             complaint (&symfile_complaints,
10593                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10594                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10595                        child_die->offset.sect_off, objfile->name);
10596           else
10597             {
10598               parameter->data_value = DW_BLOCK (attr)->data;
10599               parameter->data_value_size = DW_BLOCK (attr)->size;
10600             }
10601         }
10602     }
10603 }
10604
10605 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10606    Return 1 if the attributes are present and valid, otherwise, return 0.
10607    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10608
10609 static int
10610 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10611                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10612                     struct partial_symtab *ranges_pst)
10613 {
10614   struct objfile *objfile = cu->objfile;
10615   struct comp_unit_head *cu_header = &cu->header;
10616   bfd *obfd = objfile->obfd;
10617   unsigned int addr_size = cu_header->addr_size;
10618   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10619   /* Base address selection entry.  */
10620   CORE_ADDR base;
10621   int found_base;
10622   unsigned int dummy;
10623   const gdb_byte *buffer;
10624   CORE_ADDR marker;
10625   int low_set;
10626   CORE_ADDR low = 0;
10627   CORE_ADDR high = 0;
10628   CORE_ADDR baseaddr;
10629
10630   found_base = cu->base_known;
10631   base = cu->base_address;
10632
10633   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10634   if (offset >= dwarf2_per_objfile->ranges.size)
10635     {
10636       complaint (&symfile_complaints,
10637                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10638                  offset);
10639       return 0;
10640     }
10641   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10642
10643   /* Read in the largest possible address.  */
10644   marker = read_address (obfd, buffer, cu, &dummy);
10645   if ((marker & mask) == mask)
10646     {
10647       /* If we found the largest possible address, then
10648          read the base address.  */
10649       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10650       buffer += 2 * addr_size;
10651       offset += 2 * addr_size;
10652       found_base = 1;
10653     }
10654
10655   low_set = 0;
10656
10657   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10658
10659   while (1)
10660     {
10661       CORE_ADDR range_beginning, range_end;
10662
10663       range_beginning = read_address (obfd, buffer, cu, &dummy);
10664       buffer += addr_size;
10665       range_end = read_address (obfd, buffer, cu, &dummy);
10666       buffer += addr_size;
10667       offset += 2 * addr_size;
10668
10669       /* An end of list marker is a pair of zero addresses.  */
10670       if (range_beginning == 0 && range_end == 0)
10671         /* Found the end of list entry.  */
10672         break;
10673
10674       /* Each base address selection entry is a pair of 2 values.
10675          The first is the largest possible address, the second is
10676          the base address.  Check for a base address here.  */
10677       if ((range_beginning & mask) == mask)
10678         {
10679           /* If we found the largest possible address, then
10680              read the base address.  */
10681           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10682           found_base = 1;
10683           continue;
10684         }
10685
10686       if (!found_base)
10687         {
10688           /* We have no valid base address for the ranges
10689              data.  */
10690           complaint (&symfile_complaints,
10691                      _("Invalid .debug_ranges data (no base address)"));
10692           return 0;
10693         }
10694
10695       if (range_beginning > range_end)
10696         {
10697           /* Inverted range entries are invalid.  */
10698           complaint (&symfile_complaints,
10699                      _("Invalid .debug_ranges data (inverted range)"));
10700           return 0;
10701         }
10702
10703       /* Empty range entries have no effect.  */
10704       if (range_beginning == range_end)
10705         continue;
10706
10707       range_beginning += base;
10708       range_end += base;
10709
10710       /* A not-uncommon case of bad debug info.
10711          Don't pollute the addrmap with bad data.  */
10712       if (range_beginning + baseaddr == 0
10713           && !dwarf2_per_objfile->has_section_at_zero)
10714         {
10715           complaint (&symfile_complaints,
10716                      _(".debug_ranges entry has start address of zero"
10717                        " [in module %s]"), objfile->name);
10718           continue;
10719         }
10720
10721       if (ranges_pst != NULL)
10722         addrmap_set_empty (objfile->psymtabs_addrmap,
10723                            range_beginning + baseaddr,
10724                            range_end - 1 + baseaddr,
10725                            ranges_pst);
10726
10727       /* FIXME: This is recording everything as a low-high
10728          segment of consecutive addresses.  We should have a
10729          data structure for discontiguous block ranges
10730          instead.  */
10731       if (! low_set)
10732         {
10733           low = range_beginning;
10734           high = range_end;
10735           low_set = 1;
10736         }
10737       else
10738         {
10739           if (range_beginning < low)
10740             low = range_beginning;
10741           if (range_end > high)
10742             high = range_end;
10743         }
10744     }
10745
10746   if (! low_set)
10747     /* If the first entry is an end-of-list marker, the range
10748        describes an empty scope, i.e. no instructions.  */
10749     return 0;
10750
10751   if (low_return)
10752     *low_return = low;
10753   if (high_return)
10754     *high_return = high;
10755   return 1;
10756 }
10757
10758 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10759    are present and valid, otherwise, return 0.  Return -1 if the range is
10760    discontinuous, i.e. derived from DW_AT_ranges information.  */
10761
10762 static int
10763 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10764                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10765                       struct partial_symtab *pst)
10766 {
10767   struct attribute *attr;
10768   struct attribute *attr_high;
10769   CORE_ADDR low = 0;
10770   CORE_ADDR high = 0;
10771   int ret = 0;
10772
10773   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10774   if (attr_high)
10775     {
10776       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10777       if (attr)
10778         {
10779           low = DW_ADDR (attr);
10780           if (attr_high->form == DW_FORM_addr
10781               || attr_high->form == DW_FORM_GNU_addr_index)
10782             high = DW_ADDR (attr_high);
10783           else
10784             high = low + DW_UNSND (attr_high);
10785         }
10786       else
10787         /* Found high w/o low attribute.  */
10788         return 0;
10789
10790       /* Found consecutive range of addresses.  */
10791       ret = 1;
10792     }
10793   else
10794     {
10795       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10796       if (attr != NULL)
10797         {
10798           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10799              We take advantage of the fact that DW_AT_ranges does not appear
10800              in DW_TAG_compile_unit of DWO files.  */
10801           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10802           unsigned int ranges_offset = (DW_UNSND (attr)
10803                                         + (need_ranges_base
10804                                            ? cu->ranges_base
10805                                            : 0));
10806
10807           /* Value of the DW_AT_ranges attribute is the offset in the
10808              .debug_ranges section.  */
10809           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10810             return 0;
10811           /* Found discontinuous range of addresses.  */
10812           ret = -1;
10813         }
10814     }
10815
10816   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10817   if (high <= low)
10818     return 0;
10819
10820   /* When using the GNU linker, .gnu.linkonce. sections are used to
10821      eliminate duplicate copies of functions and vtables and such.
10822      The linker will arbitrarily choose one and discard the others.
10823      The AT_*_pc values for such functions refer to local labels in
10824      these sections.  If the section from that file was discarded, the
10825      labels are not in the output, so the relocs get a value of 0.
10826      If this is a discarded function, mark the pc bounds as invalid,
10827      so that GDB will ignore it.  */
10828   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10829     return 0;
10830
10831   *lowpc = low;
10832   if (highpc)
10833     *highpc = high;
10834   return ret;
10835 }
10836
10837 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10838    its low and high PC addresses.  Do nothing if these addresses could not
10839    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10840    and HIGHPC to the high address if greater than HIGHPC.  */
10841
10842 static void
10843 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10844                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10845                                  struct dwarf2_cu *cu)
10846 {
10847   CORE_ADDR low, high;
10848   struct die_info *child = die->child;
10849
10850   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10851     {
10852       *lowpc = min (*lowpc, low);
10853       *highpc = max (*highpc, high);
10854     }
10855
10856   /* If the language does not allow nested subprograms (either inside
10857      subprograms or lexical blocks), we're done.  */
10858   if (cu->language != language_ada)
10859     return;
10860
10861   /* Check all the children of the given DIE.  If it contains nested
10862      subprograms, then check their pc bounds.  Likewise, we need to
10863      check lexical blocks as well, as they may also contain subprogram
10864      definitions.  */
10865   while (child && child->tag)
10866     {
10867       if (child->tag == DW_TAG_subprogram
10868           || child->tag == DW_TAG_lexical_block)
10869         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10870       child = sibling_die (child);
10871     }
10872 }
10873
10874 /* Get the low and high pc's represented by the scope DIE, and store
10875    them in *LOWPC and *HIGHPC.  If the correct values can't be
10876    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10877
10878 static void
10879 get_scope_pc_bounds (struct die_info *die,
10880                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10881                      struct dwarf2_cu *cu)
10882 {
10883   CORE_ADDR best_low = (CORE_ADDR) -1;
10884   CORE_ADDR best_high = (CORE_ADDR) 0;
10885   CORE_ADDR current_low, current_high;
10886
10887   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10888     {
10889       best_low = current_low;
10890       best_high = current_high;
10891     }
10892   else
10893     {
10894       struct die_info *child = die->child;
10895
10896       while (child && child->tag)
10897         {
10898           switch (child->tag) {
10899           case DW_TAG_subprogram:
10900             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10901             break;
10902           case DW_TAG_namespace:
10903           case DW_TAG_module:
10904             /* FIXME: carlton/2004-01-16: Should we do this for
10905                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10906                that current GCC's always emit the DIEs corresponding
10907                to definitions of methods of classes as children of a
10908                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10909                the DIEs giving the declarations, which could be
10910                anywhere).  But I don't see any reason why the
10911                standards says that they have to be there.  */
10912             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10913
10914             if (current_low != ((CORE_ADDR) -1))
10915               {
10916                 best_low = min (best_low, current_low);
10917                 best_high = max (best_high, current_high);
10918               }
10919             break;
10920           default:
10921             /* Ignore.  */
10922             break;
10923           }
10924
10925           child = sibling_die (child);
10926         }
10927     }
10928
10929   *lowpc = best_low;
10930   *highpc = best_high;
10931 }
10932
10933 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10934    in DIE.  */
10935
10936 static void
10937 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10938                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10939 {
10940   struct objfile *objfile = cu->objfile;
10941   struct attribute *attr;
10942   struct attribute *attr_high;
10943
10944   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10945   if (attr_high)
10946     {
10947       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10948       if (attr)
10949         {
10950           CORE_ADDR low = DW_ADDR (attr);
10951           CORE_ADDR high;
10952           if (attr_high->form == DW_FORM_addr
10953               || attr_high->form == DW_FORM_GNU_addr_index)
10954             high = DW_ADDR (attr_high);
10955           else
10956             high = low + DW_UNSND (attr_high);
10957
10958           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10959         }
10960     }
10961
10962   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10963   if (attr)
10964     {
10965       bfd *obfd = objfile->obfd;
10966       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10967          We take advantage of the fact that DW_AT_ranges does not appear
10968          in DW_TAG_compile_unit of DWO files.  */
10969       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10970
10971       /* The value of the DW_AT_ranges attribute is the offset of the
10972          address range list in the .debug_ranges section.  */
10973       unsigned long offset = (DW_UNSND (attr)
10974                               + (need_ranges_base ? cu->ranges_base : 0));
10975       const gdb_byte *buffer;
10976
10977       /* For some target architectures, but not others, the
10978          read_address function sign-extends the addresses it returns.
10979          To recognize base address selection entries, we need a
10980          mask.  */
10981       unsigned int addr_size = cu->header.addr_size;
10982       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10983
10984       /* The base address, to which the next pair is relative.  Note
10985          that this 'base' is a DWARF concept: most entries in a range
10986          list are relative, to reduce the number of relocs against the
10987          debugging information.  This is separate from this function's
10988          'baseaddr' argument, which GDB uses to relocate debugging
10989          information from a shared library based on the address at
10990          which the library was loaded.  */
10991       CORE_ADDR base = cu->base_address;
10992       int base_known = cu->base_known;
10993
10994       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10995       if (offset >= dwarf2_per_objfile->ranges.size)
10996         {
10997           complaint (&symfile_complaints,
10998                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10999                      offset);
11000           return;
11001         }
11002       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11003
11004       for (;;)
11005         {
11006           unsigned int bytes_read;
11007           CORE_ADDR start, end;
11008
11009           start = read_address (obfd, buffer, cu, &bytes_read);
11010           buffer += bytes_read;
11011           end = read_address (obfd, buffer, cu, &bytes_read);
11012           buffer += bytes_read;
11013
11014           /* Did we find the end of the range list?  */
11015           if (start == 0 && end == 0)
11016             break;
11017
11018           /* Did we find a base address selection entry?  */
11019           else if ((start & base_select_mask) == base_select_mask)
11020             {
11021               base = end;
11022               base_known = 1;
11023             }
11024
11025           /* We found an ordinary address range.  */
11026           else
11027             {
11028               if (!base_known)
11029                 {
11030                   complaint (&symfile_complaints,
11031                              _("Invalid .debug_ranges data "
11032                                "(no base address)"));
11033                   return;
11034                 }
11035
11036               if (start > end)
11037                 {
11038                   /* Inverted range entries are invalid.  */
11039                   complaint (&symfile_complaints,
11040                              _("Invalid .debug_ranges data "
11041                                "(inverted range)"));
11042                   return;
11043                 }
11044
11045               /* Empty range entries have no effect.  */
11046               if (start == end)
11047                 continue;
11048
11049               start += base + baseaddr;
11050               end += base + baseaddr;
11051
11052               /* A not-uncommon case of bad debug info.
11053                  Don't pollute the addrmap with bad data.  */
11054               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11055                 {
11056                   complaint (&symfile_complaints,
11057                              _(".debug_ranges entry has start address of zero"
11058                                " [in module %s]"), objfile->name);
11059                   continue;
11060                 }
11061
11062               record_block_range (block, start, end - 1);
11063             }
11064         }
11065     }
11066 }
11067
11068 /* Check whether the producer field indicates either of GCC < 4.6, or the
11069    Intel C/C++ compiler, and cache the result in CU.  */
11070
11071 static void
11072 check_producer (struct dwarf2_cu *cu)
11073 {
11074   const char *cs;
11075   int major, minor, release;
11076
11077   if (cu->producer == NULL)
11078     {
11079       /* For unknown compilers expect their behavior is DWARF version
11080          compliant.
11081
11082          GCC started to support .debug_types sections by -gdwarf-4 since
11083          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11084          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11085          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11086          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11087     }
11088   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11089     {
11090       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11091
11092       cs = &cu->producer[strlen ("GNU ")];
11093       while (*cs && !isdigit (*cs))
11094         cs++;
11095       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11096         {
11097           /* Not recognized as GCC.  */
11098         }
11099       else
11100         {
11101           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11102           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11103         }
11104     }
11105   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11106     cu->producer_is_icc = 1;
11107   else
11108     {
11109       /* For other non-GCC compilers, expect their behavior is DWARF version
11110          compliant.  */
11111     }
11112
11113   cu->checked_producer = 1;
11114 }
11115
11116 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11117    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11118    during 4.6.0 experimental.  */
11119
11120 static int
11121 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11122 {
11123   if (!cu->checked_producer)
11124     check_producer (cu);
11125
11126   return cu->producer_is_gxx_lt_4_6;
11127 }
11128
11129 /* Return the default accessibility type if it is not overriden by
11130    DW_AT_accessibility.  */
11131
11132 static enum dwarf_access_attribute
11133 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11134 {
11135   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11136     {
11137       /* The default DWARF 2 accessibility for members is public, the default
11138          accessibility for inheritance is private.  */
11139
11140       if (die->tag != DW_TAG_inheritance)
11141         return DW_ACCESS_public;
11142       else
11143         return DW_ACCESS_private;
11144     }
11145   else
11146     {
11147       /* DWARF 3+ defines the default accessibility a different way.  The same
11148          rules apply now for DW_TAG_inheritance as for the members and it only
11149          depends on the container kind.  */
11150
11151       if (die->parent->tag == DW_TAG_class_type)
11152         return DW_ACCESS_private;
11153       else
11154         return DW_ACCESS_public;
11155     }
11156 }
11157
11158 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11159    offset.  If the attribute was not found return 0, otherwise return
11160    1.  If it was found but could not properly be handled, set *OFFSET
11161    to 0.  */
11162
11163 static int
11164 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11165                              LONGEST *offset)
11166 {
11167   struct attribute *attr;
11168
11169   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11170   if (attr != NULL)
11171     {
11172       *offset = 0;
11173
11174       /* Note that we do not check for a section offset first here.
11175          This is because DW_AT_data_member_location is new in DWARF 4,
11176          so if we see it, we can assume that a constant form is really
11177          a constant and not a section offset.  */
11178       if (attr_form_is_constant (attr))
11179         *offset = dwarf2_get_attr_constant_value (attr, 0);
11180       else if (attr_form_is_section_offset (attr))
11181         dwarf2_complex_location_expr_complaint ();
11182       else if (attr_form_is_block (attr))
11183         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11184       else
11185         dwarf2_complex_location_expr_complaint ();
11186
11187       return 1;
11188     }
11189
11190   return 0;
11191 }
11192
11193 /* Add an aggregate field to the field list.  */
11194
11195 static void
11196 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11197                   struct dwarf2_cu *cu)
11198 {
11199   struct objfile *objfile = cu->objfile;
11200   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11201   struct nextfield *new_field;
11202   struct attribute *attr;
11203   struct field *fp;
11204   const char *fieldname = "";
11205
11206   /* Allocate a new field list entry and link it in.  */
11207   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11208   make_cleanup (xfree, new_field);
11209   memset (new_field, 0, sizeof (struct nextfield));
11210
11211   if (die->tag == DW_TAG_inheritance)
11212     {
11213       new_field->next = fip->baseclasses;
11214       fip->baseclasses = new_field;
11215     }
11216   else
11217     {
11218       new_field->next = fip->fields;
11219       fip->fields = new_field;
11220     }
11221   fip->nfields++;
11222
11223   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11224   if (attr)
11225     new_field->accessibility = DW_UNSND (attr);
11226   else
11227     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11228   if (new_field->accessibility != DW_ACCESS_public)
11229     fip->non_public_fields = 1;
11230
11231   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11232   if (attr)
11233     new_field->virtuality = DW_UNSND (attr);
11234   else
11235     new_field->virtuality = DW_VIRTUALITY_none;
11236
11237   fp = &new_field->field;
11238
11239   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11240     {
11241       LONGEST offset;
11242
11243       /* Data member other than a C++ static data member.  */
11244
11245       /* Get type of field.  */
11246       fp->type = die_type (die, cu);
11247
11248       SET_FIELD_BITPOS (*fp, 0);
11249
11250       /* Get bit size of field (zero if none).  */
11251       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11252       if (attr)
11253         {
11254           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11255         }
11256       else
11257         {
11258           FIELD_BITSIZE (*fp) = 0;
11259         }
11260
11261       /* Get bit offset of field.  */
11262       if (handle_data_member_location (die, cu, &offset))
11263         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11264       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11265       if (attr)
11266         {
11267           if (gdbarch_bits_big_endian (gdbarch))
11268             {
11269               /* For big endian bits, the DW_AT_bit_offset gives the
11270                  additional bit offset from the MSB of the containing
11271                  anonymous object to the MSB of the field.  We don't
11272                  have to do anything special since we don't need to
11273                  know the size of the anonymous object.  */
11274               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11275             }
11276           else
11277             {
11278               /* For little endian bits, compute the bit offset to the
11279                  MSB of the anonymous object, subtract off the number of
11280                  bits from the MSB of the field to the MSB of the
11281                  object, and then subtract off the number of bits of
11282                  the field itself.  The result is the bit offset of
11283                  the LSB of the field.  */
11284               int anonymous_size;
11285               int bit_offset = DW_UNSND (attr);
11286
11287               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11288               if (attr)
11289                 {
11290                   /* The size of the anonymous object containing
11291                      the bit field is explicit, so use the
11292                      indicated size (in bytes).  */
11293                   anonymous_size = DW_UNSND (attr);
11294                 }
11295               else
11296                 {
11297                   /* The size of the anonymous object containing
11298                      the bit field must be inferred from the type
11299                      attribute of the data member containing the
11300                      bit field.  */
11301                   anonymous_size = TYPE_LENGTH (fp->type);
11302                 }
11303               SET_FIELD_BITPOS (*fp,
11304                                 (FIELD_BITPOS (*fp)
11305                                  + anonymous_size * bits_per_byte
11306                                  - bit_offset - FIELD_BITSIZE (*fp)));
11307             }
11308         }
11309
11310       /* Get name of field.  */
11311       fieldname = dwarf2_name (die, cu);
11312       if (fieldname == NULL)
11313         fieldname = "";
11314
11315       /* The name is already allocated along with this objfile, so we don't
11316          need to duplicate it for the type.  */
11317       fp->name = fieldname;
11318
11319       /* Change accessibility for artificial fields (e.g. virtual table
11320          pointer or virtual base class pointer) to private.  */
11321       if (dwarf2_attr (die, DW_AT_artificial, cu))
11322         {
11323           FIELD_ARTIFICIAL (*fp) = 1;
11324           new_field->accessibility = DW_ACCESS_private;
11325           fip->non_public_fields = 1;
11326         }
11327     }
11328   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11329     {
11330       /* C++ static member.  */
11331
11332       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11333          is a declaration, but all versions of G++ as of this writing
11334          (so through at least 3.2.1) incorrectly generate
11335          DW_TAG_variable tags.  */
11336
11337       const char *physname;
11338
11339       /* Get name of field.  */
11340       fieldname = dwarf2_name (die, cu);
11341       if (fieldname == NULL)
11342         return;
11343
11344       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11345       if (attr
11346           /* Only create a symbol if this is an external value.
11347              new_symbol checks this and puts the value in the global symbol
11348              table, which we want.  If it is not external, new_symbol
11349              will try to put the value in cu->list_in_scope which is wrong.  */
11350           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11351         {
11352           /* A static const member, not much different than an enum as far as
11353              we're concerned, except that we can support more types.  */
11354           new_symbol (die, NULL, cu);
11355         }
11356
11357       /* Get physical name.  */
11358       physname = dwarf2_physname (fieldname, die, cu);
11359
11360       /* The name is already allocated along with this objfile, so we don't
11361          need to duplicate it for the type.  */
11362       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11363       FIELD_TYPE (*fp) = die_type (die, cu);
11364       FIELD_NAME (*fp) = fieldname;
11365     }
11366   else if (die->tag == DW_TAG_inheritance)
11367     {
11368       LONGEST offset;
11369
11370       /* C++ base class field.  */
11371       if (handle_data_member_location (die, cu, &offset))
11372         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11373       FIELD_BITSIZE (*fp) = 0;
11374       FIELD_TYPE (*fp) = die_type (die, cu);
11375       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11376       fip->nbaseclasses++;
11377     }
11378 }
11379
11380 /* Add a typedef defined in the scope of the FIP's class.  */
11381
11382 static void
11383 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11384                     struct dwarf2_cu *cu)
11385 {
11386   struct objfile *objfile = cu->objfile;
11387   struct typedef_field_list *new_field;
11388   struct attribute *attr;
11389   struct typedef_field *fp;
11390   char *fieldname = "";
11391
11392   /* Allocate a new field list entry and link it in.  */
11393   new_field = xzalloc (sizeof (*new_field));
11394   make_cleanup (xfree, new_field);
11395
11396   gdb_assert (die->tag == DW_TAG_typedef);
11397
11398   fp = &new_field->field;
11399
11400   /* Get name of field.  */
11401   fp->name = dwarf2_name (die, cu);
11402   if (fp->name == NULL)
11403     return;
11404
11405   fp->type = read_type_die (die, cu);
11406
11407   new_field->next = fip->typedef_field_list;
11408   fip->typedef_field_list = new_field;
11409   fip->typedef_field_list_count++;
11410 }
11411
11412 /* Create the vector of fields, and attach it to the type.  */
11413
11414 static void
11415 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11416                               struct dwarf2_cu *cu)
11417 {
11418   int nfields = fip->nfields;
11419
11420   /* Record the field count, allocate space for the array of fields,
11421      and create blank accessibility bitfields if necessary.  */
11422   TYPE_NFIELDS (type) = nfields;
11423   TYPE_FIELDS (type) = (struct field *)
11424     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11425   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11426
11427   if (fip->non_public_fields && cu->language != language_ada)
11428     {
11429       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11430
11431       TYPE_FIELD_PRIVATE_BITS (type) =
11432         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11433       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11434
11435       TYPE_FIELD_PROTECTED_BITS (type) =
11436         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11437       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11438
11439       TYPE_FIELD_IGNORE_BITS (type) =
11440         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11441       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11442     }
11443
11444   /* If the type has baseclasses, allocate and clear a bit vector for
11445      TYPE_FIELD_VIRTUAL_BITS.  */
11446   if (fip->nbaseclasses && cu->language != language_ada)
11447     {
11448       int num_bytes = B_BYTES (fip->nbaseclasses);
11449       unsigned char *pointer;
11450
11451       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11452       pointer = TYPE_ALLOC (type, num_bytes);
11453       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11454       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11455       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11456     }
11457
11458   /* Copy the saved-up fields into the field vector.  Start from the head of
11459      the list, adding to the tail of the field array, so that they end up in
11460      the same order in the array in which they were added to the list.  */
11461   while (nfields-- > 0)
11462     {
11463       struct nextfield *fieldp;
11464
11465       if (fip->fields)
11466         {
11467           fieldp = fip->fields;
11468           fip->fields = fieldp->next;
11469         }
11470       else
11471         {
11472           fieldp = fip->baseclasses;
11473           fip->baseclasses = fieldp->next;
11474         }
11475
11476       TYPE_FIELD (type, nfields) = fieldp->field;
11477       switch (fieldp->accessibility)
11478         {
11479         case DW_ACCESS_private:
11480           if (cu->language != language_ada)
11481             SET_TYPE_FIELD_PRIVATE (type, nfields);
11482           break;
11483
11484         case DW_ACCESS_protected:
11485           if (cu->language != language_ada)
11486             SET_TYPE_FIELD_PROTECTED (type, nfields);
11487           break;
11488
11489         case DW_ACCESS_public:
11490           break;
11491
11492         default:
11493           /* Unknown accessibility.  Complain and treat it as public.  */
11494           {
11495             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11496                        fieldp->accessibility);
11497           }
11498           break;
11499         }
11500       if (nfields < fip->nbaseclasses)
11501         {
11502           switch (fieldp->virtuality)
11503             {
11504             case DW_VIRTUALITY_virtual:
11505             case DW_VIRTUALITY_pure_virtual:
11506               if (cu->language == language_ada)
11507                 error (_("unexpected virtuality in component of Ada type"));
11508               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11509               break;
11510             }
11511         }
11512     }
11513 }
11514
11515 /* Return true if this member function is a constructor, false
11516    otherwise.  */
11517
11518 static int
11519 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11520 {
11521   const char *fieldname;
11522   const char *typename;
11523   int len;
11524
11525   if (die->parent == NULL)
11526     return 0;
11527
11528   if (die->parent->tag != DW_TAG_structure_type
11529       && die->parent->tag != DW_TAG_union_type
11530       && die->parent->tag != DW_TAG_class_type)
11531     return 0;
11532
11533   fieldname = dwarf2_name (die, cu);
11534   typename = dwarf2_name (die->parent, cu);
11535   if (fieldname == NULL || typename == NULL)
11536     return 0;
11537
11538   len = strlen (fieldname);
11539   return (strncmp (fieldname, typename, len) == 0
11540           && (typename[len] == '\0' || typename[len] == '<'));
11541 }
11542
11543 /* Add a member function to the proper fieldlist.  */
11544
11545 static void
11546 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11547                       struct type *type, struct dwarf2_cu *cu)
11548 {
11549   struct objfile *objfile = cu->objfile;
11550   struct attribute *attr;
11551   struct fnfieldlist *flp;
11552   int i;
11553   struct fn_field *fnp;
11554   const char *fieldname;
11555   struct nextfnfield *new_fnfield;
11556   struct type *this_type;
11557   enum dwarf_access_attribute accessibility;
11558
11559   if (cu->language == language_ada)
11560     error (_("unexpected member function in Ada type"));
11561
11562   /* Get name of member function.  */
11563   fieldname = dwarf2_name (die, cu);
11564   if (fieldname == NULL)
11565     return;
11566
11567   /* Look up member function name in fieldlist.  */
11568   for (i = 0; i < fip->nfnfields; i++)
11569     {
11570       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11571         break;
11572     }
11573
11574   /* Create new list element if necessary.  */
11575   if (i < fip->nfnfields)
11576     flp = &fip->fnfieldlists[i];
11577   else
11578     {
11579       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11580         {
11581           fip->fnfieldlists = (struct fnfieldlist *)
11582             xrealloc (fip->fnfieldlists,
11583                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11584                       * sizeof (struct fnfieldlist));
11585           if (fip->nfnfields == 0)
11586             make_cleanup (free_current_contents, &fip->fnfieldlists);
11587         }
11588       flp = &fip->fnfieldlists[fip->nfnfields];
11589       flp->name = fieldname;
11590       flp->length = 0;
11591       flp->head = NULL;
11592       i = fip->nfnfields++;
11593     }
11594
11595   /* Create a new member function field and chain it to the field list
11596      entry.  */
11597   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11598   make_cleanup (xfree, new_fnfield);
11599   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11600   new_fnfield->next = flp->head;
11601   flp->head = new_fnfield;
11602   flp->length++;
11603
11604   /* Fill in the member function field info.  */
11605   fnp = &new_fnfield->fnfield;
11606
11607   /* Delay processing of the physname until later.  */
11608   if (cu->language == language_cplus || cu->language == language_java)
11609     {
11610       add_to_method_list (type, i, flp->length - 1, fieldname,
11611                           die, cu);
11612     }
11613   else
11614     {
11615       const char *physname = dwarf2_physname (fieldname, die, cu);
11616       fnp->physname = physname ? physname : "";
11617     }
11618
11619   fnp->type = alloc_type (objfile);
11620   this_type = read_type_die (die, cu);
11621   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11622     {
11623       int nparams = TYPE_NFIELDS (this_type);
11624
11625       /* TYPE is the domain of this method, and THIS_TYPE is the type
11626            of the method itself (TYPE_CODE_METHOD).  */
11627       smash_to_method_type (fnp->type, type,
11628                             TYPE_TARGET_TYPE (this_type),
11629                             TYPE_FIELDS (this_type),
11630                             TYPE_NFIELDS (this_type),
11631                             TYPE_VARARGS (this_type));
11632
11633       /* Handle static member functions.
11634          Dwarf2 has no clean way to discern C++ static and non-static
11635          member functions.  G++ helps GDB by marking the first
11636          parameter for non-static member functions (which is the this
11637          pointer) as artificial.  We obtain this information from
11638          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11639       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11640         fnp->voffset = VOFFSET_STATIC;
11641     }
11642   else
11643     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11644                dwarf2_full_name (fieldname, die, cu));
11645
11646   /* Get fcontext from DW_AT_containing_type if present.  */
11647   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11648     fnp->fcontext = die_containing_type (die, cu);
11649
11650   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11651      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11652
11653   /* Get accessibility.  */
11654   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11655   if (attr)
11656     accessibility = DW_UNSND (attr);
11657   else
11658     accessibility = dwarf2_default_access_attribute (die, cu);
11659   switch (accessibility)
11660     {
11661     case DW_ACCESS_private:
11662       fnp->is_private = 1;
11663       break;
11664     case DW_ACCESS_protected:
11665       fnp->is_protected = 1;
11666       break;
11667     }
11668
11669   /* Check for artificial methods.  */
11670   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11671   if (attr && DW_UNSND (attr) != 0)
11672     fnp->is_artificial = 1;
11673
11674   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11675
11676   /* Get index in virtual function table if it is a virtual member
11677      function.  For older versions of GCC, this is an offset in the
11678      appropriate virtual table, as specified by DW_AT_containing_type.
11679      For everyone else, it is an expression to be evaluated relative
11680      to the object address.  */
11681
11682   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11683   if (attr)
11684     {
11685       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11686         {
11687           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11688             {
11689               /* Old-style GCC.  */
11690               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11691             }
11692           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11693                    || (DW_BLOCK (attr)->size > 1
11694                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11695                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11696             {
11697               struct dwarf_block blk;
11698               int offset;
11699
11700               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11701                         ? 1 : 2);
11702               blk.size = DW_BLOCK (attr)->size - offset;
11703               blk.data = DW_BLOCK (attr)->data + offset;
11704               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11705               if ((fnp->voffset % cu->header.addr_size) != 0)
11706                 dwarf2_complex_location_expr_complaint ();
11707               else
11708                 fnp->voffset /= cu->header.addr_size;
11709               fnp->voffset += 2;
11710             }
11711           else
11712             dwarf2_complex_location_expr_complaint ();
11713
11714           if (!fnp->fcontext)
11715             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11716         }
11717       else if (attr_form_is_section_offset (attr))
11718         {
11719           dwarf2_complex_location_expr_complaint ();
11720         }
11721       else
11722         {
11723           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11724                                                  fieldname);
11725         }
11726     }
11727   else
11728     {
11729       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11730       if (attr && DW_UNSND (attr))
11731         {
11732           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11733           complaint (&symfile_complaints,
11734                      _("Member function \"%s\" (offset %d) is virtual "
11735                        "but the vtable offset is not specified"),
11736                      fieldname, die->offset.sect_off);
11737           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11738           TYPE_CPLUS_DYNAMIC (type) = 1;
11739         }
11740     }
11741 }
11742
11743 /* Create the vector of member function fields, and attach it to the type.  */
11744
11745 static void
11746 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11747                                  struct dwarf2_cu *cu)
11748 {
11749   struct fnfieldlist *flp;
11750   int i;
11751
11752   if (cu->language == language_ada)
11753     error (_("unexpected member functions in Ada type"));
11754
11755   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11756   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11757     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11758
11759   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11760     {
11761       struct nextfnfield *nfp = flp->head;
11762       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11763       int k;
11764
11765       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11766       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11767       fn_flp->fn_fields = (struct fn_field *)
11768         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11769       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11770         fn_flp->fn_fields[k] = nfp->fnfield;
11771     }
11772
11773   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11774 }
11775
11776 /* Returns non-zero if NAME is the name of a vtable member in CU's
11777    language, zero otherwise.  */
11778 static int
11779 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11780 {
11781   static const char vptr[] = "_vptr";
11782   static const char vtable[] = "vtable";
11783
11784   /* Look for the C++ and Java forms of the vtable.  */
11785   if ((cu->language == language_java
11786        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11787        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11788        && is_cplus_marker (name[sizeof (vptr) - 1])))
11789     return 1;
11790
11791   return 0;
11792 }
11793
11794 /* GCC outputs unnamed structures that are really pointers to member
11795    functions, with the ABI-specified layout.  If TYPE describes
11796    such a structure, smash it into a member function type.
11797
11798    GCC shouldn't do this; it should just output pointer to member DIEs.
11799    This is GCC PR debug/28767.  */
11800
11801 static void
11802 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11803 {
11804   struct type *pfn_type, *domain_type, *new_type;
11805
11806   /* Check for a structure with no name and two children.  */
11807   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11808     return;
11809
11810   /* Check for __pfn and __delta members.  */
11811   if (TYPE_FIELD_NAME (type, 0) == NULL
11812       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11813       || TYPE_FIELD_NAME (type, 1) == NULL
11814       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11815     return;
11816
11817   /* Find the type of the method.  */
11818   pfn_type = TYPE_FIELD_TYPE (type, 0);
11819   if (pfn_type == NULL
11820       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11821       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11822     return;
11823
11824   /* Look for the "this" argument.  */
11825   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11826   if (TYPE_NFIELDS (pfn_type) == 0
11827       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11828       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11829     return;
11830
11831   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11832   new_type = alloc_type (objfile);
11833   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11834                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11835                         TYPE_VARARGS (pfn_type));
11836   smash_to_methodptr_type (type, new_type);
11837 }
11838
11839 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11840    (icc).  */
11841
11842 static int
11843 producer_is_icc (struct dwarf2_cu *cu)
11844 {
11845   if (!cu->checked_producer)
11846     check_producer (cu);
11847
11848   return cu->producer_is_icc;
11849 }
11850
11851 /* Called when we find the DIE that starts a structure or union scope
11852    (definition) to create a type for the structure or union.  Fill in
11853    the type's name and general properties; the members will not be
11854    processed until process_structure_scope.
11855
11856    NOTE: we need to call these functions regardless of whether or not the
11857    DIE has a DW_AT_name attribute, since it might be an anonymous
11858    structure or union.  This gets the type entered into our set of
11859    user defined types.
11860
11861    However, if the structure is incomplete (an opaque struct/union)
11862    then suppress creating a symbol table entry for it since gdb only
11863    wants to find the one with the complete definition.  Note that if
11864    it is complete, we just call new_symbol, which does it's own
11865    checking about whether the struct/union is anonymous or not (and
11866    suppresses creating a symbol table entry itself).  */
11867
11868 static struct type *
11869 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11870 {
11871   struct objfile *objfile = cu->objfile;
11872   struct type *type;
11873   struct attribute *attr;
11874   const char *name;
11875
11876   /* If the definition of this type lives in .debug_types, read that type.
11877      Don't follow DW_AT_specification though, that will take us back up
11878      the chain and we want to go down.  */
11879   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11880   if (attr)
11881     {
11882       type = get_DW_AT_signature_type (die, attr, cu);
11883
11884       /* The type's CU may not be the same as CU.
11885          Ensure TYPE is recorded with CU in die_type_hash.  */
11886       return set_die_type (die, type, cu);
11887     }
11888
11889   type = alloc_type (objfile);
11890   INIT_CPLUS_SPECIFIC (type);
11891
11892   name = dwarf2_name (die, cu);
11893   if (name != NULL)
11894     {
11895       if (cu->language == language_cplus
11896           || cu->language == language_java)
11897         {
11898           const char *full_name = dwarf2_full_name (name, die, cu);
11899
11900           /* dwarf2_full_name might have already finished building the DIE's
11901              type.  If so, there is no need to continue.  */
11902           if (get_die_type (die, cu) != NULL)
11903             return get_die_type (die, cu);
11904
11905           TYPE_TAG_NAME (type) = full_name;
11906           if (die->tag == DW_TAG_structure_type
11907               || die->tag == DW_TAG_class_type)
11908             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11909         }
11910       else
11911         {
11912           /* The name is already allocated along with this objfile, so
11913              we don't need to duplicate it for the type.  */
11914           TYPE_TAG_NAME (type) = name;
11915           if (die->tag == DW_TAG_class_type)
11916             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11917         }
11918     }
11919
11920   if (die->tag == DW_TAG_structure_type)
11921     {
11922       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11923     }
11924   else if (die->tag == DW_TAG_union_type)
11925     {
11926       TYPE_CODE (type) = TYPE_CODE_UNION;
11927     }
11928   else
11929     {
11930       TYPE_CODE (type) = TYPE_CODE_CLASS;
11931     }
11932
11933   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11934     TYPE_DECLARED_CLASS (type) = 1;
11935
11936   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11937   if (attr)
11938     {
11939       TYPE_LENGTH (type) = DW_UNSND (attr);
11940     }
11941   else
11942     {
11943       TYPE_LENGTH (type) = 0;
11944     }
11945
11946   if (producer_is_icc (cu))
11947     {
11948       /* ICC does not output the required DW_AT_declaration
11949          on incomplete types, but gives them a size of zero.  */
11950     }
11951   else
11952     TYPE_STUB_SUPPORTED (type) = 1;
11953
11954   if (die_is_declaration (die, cu))
11955     TYPE_STUB (type) = 1;
11956   else if (attr == NULL && die->child == NULL
11957            && producer_is_realview (cu->producer))
11958     /* RealView does not output the required DW_AT_declaration
11959        on incomplete types.  */
11960     TYPE_STUB (type) = 1;
11961
11962   /* We need to add the type field to the die immediately so we don't
11963      infinitely recurse when dealing with pointers to the structure
11964      type within the structure itself.  */
11965   set_die_type (die, type, cu);
11966
11967   /* set_die_type should be already done.  */
11968   set_descriptive_type (type, die, cu);
11969
11970   return type;
11971 }
11972
11973 /* Finish creating a structure or union type, including filling in
11974    its members and creating a symbol for it.  */
11975
11976 static void
11977 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11978 {
11979   struct objfile *objfile = cu->objfile;
11980   struct die_info *child_die = die->child;
11981   struct type *type;
11982
11983   type = get_die_type (die, cu);
11984   if (type == NULL)
11985     type = read_structure_type (die, cu);
11986
11987   if (die->child != NULL && ! die_is_declaration (die, cu))
11988     {
11989       struct field_info fi;
11990       struct die_info *child_die;
11991       VEC (symbolp) *template_args = NULL;
11992       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11993
11994       memset (&fi, 0, sizeof (struct field_info));
11995
11996       child_die = die->child;
11997
11998       while (child_die && child_die->tag)
11999         {
12000           if (child_die->tag == DW_TAG_member
12001               || child_die->tag == DW_TAG_variable)
12002             {
12003               /* NOTE: carlton/2002-11-05: A C++ static data member
12004                  should be a DW_TAG_member that is a declaration, but
12005                  all versions of G++ as of this writing (so through at
12006                  least 3.2.1) incorrectly generate DW_TAG_variable
12007                  tags for them instead.  */
12008               dwarf2_add_field (&fi, child_die, cu);
12009             }
12010           else if (child_die->tag == DW_TAG_subprogram)
12011             {
12012               /* C++ member function.  */
12013               dwarf2_add_member_fn (&fi, child_die, type, cu);
12014             }
12015           else if (child_die->tag == DW_TAG_inheritance)
12016             {
12017               /* C++ base class field.  */
12018               dwarf2_add_field (&fi, child_die, cu);
12019             }
12020           else if (child_die->tag == DW_TAG_typedef)
12021             dwarf2_add_typedef (&fi, child_die, cu);
12022           else if (child_die->tag == DW_TAG_template_type_param
12023                    || child_die->tag == DW_TAG_template_value_param)
12024             {
12025               struct symbol *arg = new_symbol (child_die, NULL, cu);
12026
12027               if (arg != NULL)
12028                 VEC_safe_push (symbolp, template_args, arg);
12029             }
12030
12031           child_die = sibling_die (child_die);
12032         }
12033
12034       /* Attach template arguments to type.  */
12035       if (! VEC_empty (symbolp, template_args))
12036         {
12037           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12038           TYPE_N_TEMPLATE_ARGUMENTS (type)
12039             = VEC_length (symbolp, template_args);
12040           TYPE_TEMPLATE_ARGUMENTS (type)
12041             = obstack_alloc (&objfile->objfile_obstack,
12042                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12043                               * sizeof (struct symbol *)));
12044           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12045                   VEC_address (symbolp, template_args),
12046                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12047                    * sizeof (struct symbol *)));
12048           VEC_free (symbolp, template_args);
12049         }
12050
12051       /* Attach fields and member functions to the type.  */
12052       if (fi.nfields)
12053         dwarf2_attach_fields_to_type (&fi, type, cu);
12054       if (fi.nfnfields)
12055         {
12056           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12057
12058           /* Get the type which refers to the base class (possibly this
12059              class itself) which contains the vtable pointer for the current
12060              class from the DW_AT_containing_type attribute.  This use of
12061              DW_AT_containing_type is a GNU extension.  */
12062
12063           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12064             {
12065               struct type *t = die_containing_type (die, cu);
12066
12067               TYPE_VPTR_BASETYPE (type) = t;
12068               if (type == t)
12069                 {
12070                   int i;
12071
12072                   /* Our own class provides vtbl ptr.  */
12073                   for (i = TYPE_NFIELDS (t) - 1;
12074                        i >= TYPE_N_BASECLASSES (t);
12075                        --i)
12076                     {
12077                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12078
12079                       if (is_vtable_name (fieldname, cu))
12080                         {
12081                           TYPE_VPTR_FIELDNO (type) = i;
12082                           break;
12083                         }
12084                     }
12085
12086                   /* Complain if virtual function table field not found.  */
12087                   if (i < TYPE_N_BASECLASSES (t))
12088                     complaint (&symfile_complaints,
12089                                _("virtual function table pointer "
12090                                  "not found when defining class '%s'"),
12091                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12092                                "");
12093                 }
12094               else
12095                 {
12096                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12097                 }
12098             }
12099           else if (cu->producer
12100                    && strncmp (cu->producer,
12101                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12102             {
12103               /* The IBM XLC compiler does not provide direct indication
12104                  of the containing type, but the vtable pointer is
12105                  always named __vfp.  */
12106
12107               int i;
12108
12109               for (i = TYPE_NFIELDS (type) - 1;
12110                    i >= TYPE_N_BASECLASSES (type);
12111                    --i)
12112                 {
12113                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12114                     {
12115                       TYPE_VPTR_FIELDNO (type) = i;
12116                       TYPE_VPTR_BASETYPE (type) = type;
12117                       break;
12118                     }
12119                 }
12120             }
12121         }
12122
12123       /* Copy fi.typedef_field_list linked list elements content into the
12124          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12125       if (fi.typedef_field_list)
12126         {
12127           int i = fi.typedef_field_list_count;
12128
12129           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12130           TYPE_TYPEDEF_FIELD_ARRAY (type)
12131             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12132           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12133
12134           /* Reverse the list order to keep the debug info elements order.  */
12135           while (--i >= 0)
12136             {
12137               struct typedef_field *dest, *src;
12138
12139               dest = &TYPE_TYPEDEF_FIELD (type, i);
12140               src = &fi.typedef_field_list->field;
12141               fi.typedef_field_list = fi.typedef_field_list->next;
12142               *dest = *src;
12143             }
12144         }
12145
12146       do_cleanups (back_to);
12147
12148       if (HAVE_CPLUS_STRUCT (type))
12149         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12150     }
12151
12152   quirk_gcc_member_function_pointer (type, objfile);
12153
12154   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12155      snapshots) has been known to create a die giving a declaration
12156      for a class that has, as a child, a die giving a definition for a
12157      nested class.  So we have to process our children even if the
12158      current die is a declaration.  Normally, of course, a declaration
12159      won't have any children at all.  */
12160
12161   while (child_die != NULL && child_die->tag)
12162     {
12163       if (child_die->tag == DW_TAG_member
12164           || child_die->tag == DW_TAG_variable
12165           || child_die->tag == DW_TAG_inheritance
12166           || child_die->tag == DW_TAG_template_value_param
12167           || child_die->tag == DW_TAG_template_type_param)
12168         {
12169           /* Do nothing.  */
12170         }
12171       else
12172         process_die (child_die, cu);
12173
12174       child_die = sibling_die (child_die);
12175     }
12176
12177   /* Do not consider external references.  According to the DWARF standard,
12178      these DIEs are identified by the fact that they have no byte_size
12179      attribute, and a declaration attribute.  */
12180   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12181       || !die_is_declaration (die, cu))
12182     new_symbol (die, type, cu);
12183 }
12184
12185 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12186    complete the type's fields yet, or create any symbols.  */
12187
12188 static struct type *
12189 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12190 {
12191   struct objfile *objfile = cu->objfile;
12192   struct type *type;
12193   struct attribute *attr;
12194   const char *name;
12195
12196   /* If the definition of this type lives in .debug_types, read that type.
12197      Don't follow DW_AT_specification though, that will take us back up
12198      the chain and we want to go down.  */
12199   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12200   if (attr)
12201     {
12202       type = get_DW_AT_signature_type (die, attr, cu);
12203
12204       /* The type's CU may not be the same as CU.
12205          Ensure TYPE is recorded with CU in die_type_hash.  */
12206       return set_die_type (die, type, cu);
12207     }
12208
12209   type = alloc_type (objfile);
12210
12211   TYPE_CODE (type) = TYPE_CODE_ENUM;
12212   name = dwarf2_full_name (NULL, die, cu);
12213   if (name != NULL)
12214     TYPE_TAG_NAME (type) = name;
12215
12216   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12217   if (attr)
12218     {
12219       TYPE_LENGTH (type) = DW_UNSND (attr);
12220     }
12221   else
12222     {
12223       TYPE_LENGTH (type) = 0;
12224     }
12225
12226   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12227      declared as private in the package spec, and then defined only
12228      inside the package body.  Such types are known as Taft Amendment
12229      Types.  When another package uses such a type, an incomplete DIE
12230      may be generated by the compiler.  */
12231   if (die_is_declaration (die, cu))
12232     TYPE_STUB (type) = 1;
12233
12234   return set_die_type (die, type, cu);
12235 }
12236
12237 /* Given a pointer to a die which begins an enumeration, process all
12238    the dies that define the members of the enumeration, and create the
12239    symbol for the enumeration type.
12240
12241    NOTE: We reverse the order of the element list.  */
12242
12243 static void
12244 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12245 {
12246   struct type *this_type;
12247
12248   this_type = get_die_type (die, cu);
12249   if (this_type == NULL)
12250     this_type = read_enumeration_type (die, cu);
12251
12252   if (die->child != NULL)
12253     {
12254       struct die_info *child_die;
12255       struct symbol *sym;
12256       struct field *fields = NULL;
12257       int num_fields = 0;
12258       int unsigned_enum = 1;
12259       const char *name;
12260       int flag_enum = 1;
12261       ULONGEST mask = 0;
12262
12263       child_die = die->child;
12264       while (child_die && child_die->tag)
12265         {
12266           if (child_die->tag != DW_TAG_enumerator)
12267             {
12268               process_die (child_die, cu);
12269             }
12270           else
12271             {
12272               name = dwarf2_name (child_die, cu);
12273               if (name)
12274                 {
12275                   sym = new_symbol (child_die, this_type, cu);
12276                   if (SYMBOL_VALUE (sym) < 0)
12277                     {
12278                       unsigned_enum = 0;
12279                       flag_enum = 0;
12280                     }
12281                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12282                     flag_enum = 0;
12283                   else
12284                     mask |= SYMBOL_VALUE (sym);
12285
12286                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12287                     {
12288                       fields = (struct field *)
12289                         xrealloc (fields,
12290                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12291                                   * sizeof (struct field));
12292                     }
12293
12294                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12295                   FIELD_TYPE (fields[num_fields]) = NULL;
12296                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12297                   FIELD_BITSIZE (fields[num_fields]) = 0;
12298
12299                   num_fields++;
12300                 }
12301             }
12302
12303           child_die = sibling_die (child_die);
12304         }
12305
12306       if (num_fields)
12307         {
12308           TYPE_NFIELDS (this_type) = num_fields;
12309           TYPE_FIELDS (this_type) = (struct field *)
12310             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12311           memcpy (TYPE_FIELDS (this_type), fields,
12312                   sizeof (struct field) * num_fields);
12313           xfree (fields);
12314         }
12315       if (unsigned_enum)
12316         TYPE_UNSIGNED (this_type) = 1;
12317       if (flag_enum)
12318         TYPE_FLAG_ENUM (this_type) = 1;
12319     }
12320
12321   /* If we are reading an enum from a .debug_types unit, and the enum
12322      is a declaration, and the enum is not the signatured type in the
12323      unit, then we do not want to add a symbol for it.  Adding a
12324      symbol would in some cases obscure the true definition of the
12325      enum, giving users an incomplete type when the definition is
12326      actually available.  Note that we do not want to do this for all
12327      enums which are just declarations, because C++0x allows forward
12328      enum declarations.  */
12329   if (cu->per_cu->is_debug_types
12330       && die_is_declaration (die, cu))
12331     {
12332       struct signatured_type *sig_type;
12333
12334       sig_type = (struct signatured_type *) cu->per_cu;
12335       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12336       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12337         return;
12338     }
12339
12340   new_symbol (die, this_type, cu);
12341 }
12342
12343 /* Extract all information from a DW_TAG_array_type DIE and put it in
12344    the DIE's type field.  For now, this only handles one dimensional
12345    arrays.  */
12346
12347 static struct type *
12348 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12349 {
12350   struct objfile *objfile = cu->objfile;
12351   struct die_info *child_die;
12352   struct type *type;
12353   struct type *element_type, *range_type, *index_type;
12354   struct type **range_types = NULL;
12355   struct attribute *attr;
12356   int ndim = 0;
12357   struct cleanup *back_to;
12358   const char *name;
12359
12360   element_type = die_type (die, cu);
12361
12362   /* The die_type call above may have already set the type for this DIE.  */
12363   type = get_die_type (die, cu);
12364   if (type)
12365     return type;
12366
12367   /* Irix 6.2 native cc creates array types without children for
12368      arrays with unspecified length.  */
12369   if (die->child == NULL)
12370     {
12371       index_type = objfile_type (objfile)->builtin_int;
12372       range_type = create_range_type (NULL, index_type, 0, -1);
12373       type = create_array_type (NULL, element_type, range_type);
12374       return set_die_type (die, type, cu);
12375     }
12376
12377   back_to = make_cleanup (null_cleanup, NULL);
12378   child_die = die->child;
12379   while (child_die && child_die->tag)
12380     {
12381       if (child_die->tag == DW_TAG_subrange_type)
12382         {
12383           struct type *child_type = read_type_die (child_die, cu);
12384
12385           if (child_type != NULL)
12386             {
12387               /* The range type was succesfully read.  Save it for the
12388                  array type creation.  */
12389               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12390                 {
12391                   range_types = (struct type **)
12392                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12393                               * sizeof (struct type *));
12394                   if (ndim == 0)
12395                     make_cleanup (free_current_contents, &range_types);
12396                 }
12397               range_types[ndim++] = child_type;
12398             }
12399         }
12400       child_die = sibling_die (child_die);
12401     }
12402
12403   /* Dwarf2 dimensions are output from left to right, create the
12404      necessary array types in backwards order.  */
12405
12406   type = element_type;
12407
12408   if (read_array_order (die, cu) == DW_ORD_col_major)
12409     {
12410       int i = 0;
12411
12412       while (i < ndim)
12413         type = create_array_type (NULL, type, range_types[i++]);
12414     }
12415   else
12416     {
12417       while (ndim-- > 0)
12418         type = create_array_type (NULL, type, range_types[ndim]);
12419     }
12420
12421   /* Understand Dwarf2 support for vector types (like they occur on
12422      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12423      array type.  This is not part of the Dwarf2/3 standard yet, but a
12424      custom vendor extension.  The main difference between a regular
12425      array and the vector variant is that vectors are passed by value
12426      to functions.  */
12427   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12428   if (attr)
12429     make_vector_type (type);
12430
12431   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12432      implementation may choose to implement triple vectors using this
12433      attribute.  */
12434   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12435   if (attr)
12436     {
12437       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12438         TYPE_LENGTH (type) = DW_UNSND (attr);
12439       else
12440         complaint (&symfile_complaints,
12441                    _("DW_AT_byte_size for array type smaller "
12442                      "than the total size of elements"));
12443     }
12444
12445   name = dwarf2_name (die, cu);
12446   if (name)
12447     TYPE_NAME (type) = name;
12448
12449   /* Install the type in the die.  */
12450   set_die_type (die, type, cu);
12451
12452   /* set_die_type should be already done.  */
12453   set_descriptive_type (type, die, cu);
12454
12455   do_cleanups (back_to);
12456
12457   return type;
12458 }
12459
12460 static enum dwarf_array_dim_ordering
12461 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12462 {
12463   struct attribute *attr;
12464
12465   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12466
12467   if (attr) return DW_SND (attr);
12468
12469   /* GNU F77 is a special case, as at 08/2004 array type info is the
12470      opposite order to the dwarf2 specification, but data is still
12471      laid out as per normal fortran.
12472
12473      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12474      version checking.  */
12475
12476   if (cu->language == language_fortran
12477       && cu->producer && strstr (cu->producer, "GNU F77"))
12478     {
12479       return DW_ORD_row_major;
12480     }
12481
12482   switch (cu->language_defn->la_array_ordering)
12483     {
12484     case array_column_major:
12485       return DW_ORD_col_major;
12486     case array_row_major:
12487     default:
12488       return DW_ORD_row_major;
12489     };
12490 }
12491
12492 /* Extract all information from a DW_TAG_set_type DIE and put it in
12493    the DIE's type field.  */
12494
12495 static struct type *
12496 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12497 {
12498   struct type *domain_type, *set_type;
12499   struct attribute *attr;
12500
12501   domain_type = die_type (die, cu);
12502
12503   /* The die_type call above may have already set the type for this DIE.  */
12504   set_type = get_die_type (die, cu);
12505   if (set_type)
12506     return set_type;
12507
12508   set_type = create_set_type (NULL, domain_type);
12509
12510   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12511   if (attr)
12512     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12513
12514   return set_die_type (die, set_type, cu);
12515 }
12516
12517 /* A helper for read_common_block that creates a locexpr baton.
12518    SYM is the symbol which we are marking as computed.
12519    COMMON_DIE is the DIE for the common block.
12520    COMMON_LOC is the location expression attribute for the common
12521    block itself.
12522    MEMBER_LOC is the location expression attribute for the particular
12523    member of the common block that we are processing.
12524    CU is the CU from which the above come.  */
12525
12526 static void
12527 mark_common_block_symbol_computed (struct symbol *sym,
12528                                    struct die_info *common_die,
12529                                    struct attribute *common_loc,
12530                                    struct attribute *member_loc,
12531                                    struct dwarf2_cu *cu)
12532 {
12533   struct objfile *objfile = dwarf2_per_objfile->objfile;
12534   struct dwarf2_locexpr_baton *baton;
12535   gdb_byte *ptr;
12536   unsigned int cu_off;
12537   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12538   LONGEST offset = 0;
12539
12540   gdb_assert (common_loc && member_loc);
12541   gdb_assert (attr_form_is_block (common_loc));
12542   gdb_assert (attr_form_is_block (member_loc)
12543               || attr_form_is_constant (member_loc));
12544
12545   baton = obstack_alloc (&objfile->objfile_obstack,
12546                          sizeof (struct dwarf2_locexpr_baton));
12547   baton->per_cu = cu->per_cu;
12548   gdb_assert (baton->per_cu);
12549
12550   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12551
12552   if (attr_form_is_constant (member_loc))
12553     {
12554       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12555       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12556     }
12557   else
12558     baton->size += DW_BLOCK (member_loc)->size;
12559
12560   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12561   baton->data = ptr;
12562
12563   *ptr++ = DW_OP_call4;
12564   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12565   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12566   ptr += 4;
12567
12568   if (attr_form_is_constant (member_loc))
12569     {
12570       *ptr++ = DW_OP_addr;
12571       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12572       ptr += cu->header.addr_size;
12573     }
12574   else
12575     {
12576       /* We have to copy the data here, because DW_OP_call4 will only
12577          use a DW_AT_location attribute.  */
12578       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12579       ptr += DW_BLOCK (member_loc)->size;
12580     }
12581
12582   *ptr++ = DW_OP_plus;
12583   gdb_assert (ptr - baton->data == baton->size);
12584
12585   SYMBOL_LOCATION_BATON (sym) = baton;
12586   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12587 }
12588
12589 /* Create appropriate locally-scoped variables for all the
12590    DW_TAG_common_block entries.  Also create a struct common_block
12591    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12592    is used to sepate the common blocks name namespace from regular
12593    variable names.  */
12594
12595 static void
12596 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12597 {
12598   struct attribute *attr;
12599
12600   attr = dwarf2_attr (die, DW_AT_location, cu);
12601   if (attr)
12602     {
12603       /* Support the .debug_loc offsets.  */
12604       if (attr_form_is_block (attr))
12605         {
12606           /* Ok.  */
12607         }
12608       else if (attr_form_is_section_offset (attr))
12609         {
12610           dwarf2_complex_location_expr_complaint ();
12611           attr = NULL;
12612         }
12613       else
12614         {
12615           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12616                                                  "common block member");
12617           attr = NULL;
12618         }
12619     }
12620
12621   if (die->child != NULL)
12622     {
12623       struct objfile *objfile = cu->objfile;
12624       struct die_info *child_die;
12625       size_t n_entries = 0, size;
12626       struct common_block *common_block;
12627       struct symbol *sym;
12628
12629       for (child_die = die->child;
12630            child_die && child_die->tag;
12631            child_die = sibling_die (child_die))
12632         ++n_entries;
12633
12634       size = (sizeof (struct common_block)
12635               + (n_entries - 1) * sizeof (struct symbol *));
12636       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12637       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12638       common_block->n_entries = 0;
12639
12640       for (child_die = die->child;
12641            child_die && child_die->tag;
12642            child_die = sibling_die (child_die))
12643         {
12644           /* Create the symbol in the DW_TAG_common_block block in the current
12645              symbol scope.  */
12646           sym = new_symbol (child_die, NULL, cu);
12647           if (sym != NULL)
12648             {
12649               struct attribute *member_loc;
12650
12651               common_block->contents[common_block->n_entries++] = sym;
12652
12653               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12654                                         cu);
12655               if (member_loc)
12656                 {
12657                   /* GDB has handled this for a long time, but it is
12658                      not specified by DWARF.  It seems to have been
12659                      emitted by gfortran at least as recently as:
12660                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12661                   complaint (&symfile_complaints,
12662                              _("Variable in common block has "
12663                                "DW_AT_data_member_location "
12664                                "- DIE at 0x%x [in module %s]"),
12665                              child_die->offset.sect_off, cu->objfile->name);
12666
12667                   if (attr_form_is_section_offset (member_loc))
12668                     dwarf2_complex_location_expr_complaint ();
12669                   else if (attr_form_is_constant (member_loc)
12670                            || attr_form_is_block (member_loc))
12671                     {
12672                       if (attr)
12673                         mark_common_block_symbol_computed (sym, die, attr,
12674                                                            member_loc, cu);
12675                     }
12676                   else
12677                     dwarf2_complex_location_expr_complaint ();
12678                 }
12679             }
12680         }
12681
12682       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12683       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12684     }
12685 }
12686
12687 /* Create a type for a C++ namespace.  */
12688
12689 static struct type *
12690 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12691 {
12692   struct objfile *objfile = cu->objfile;
12693   const char *previous_prefix, *name;
12694   int is_anonymous;
12695   struct type *type;
12696
12697   /* For extensions, reuse the type of the original namespace.  */
12698   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12699     {
12700       struct die_info *ext_die;
12701       struct dwarf2_cu *ext_cu = cu;
12702
12703       ext_die = dwarf2_extension (die, &ext_cu);
12704       type = read_type_die (ext_die, ext_cu);
12705
12706       /* EXT_CU may not be the same as CU.
12707          Ensure TYPE is recorded with CU in die_type_hash.  */
12708       return set_die_type (die, type, cu);
12709     }
12710
12711   name = namespace_name (die, &is_anonymous, cu);
12712
12713   /* Now build the name of the current namespace.  */
12714
12715   previous_prefix = determine_prefix (die, cu);
12716   if (previous_prefix[0] != '\0')
12717     name = typename_concat (&objfile->objfile_obstack,
12718                             previous_prefix, name, 0, cu);
12719
12720   /* Create the type.  */
12721   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12722                     objfile);
12723   TYPE_NAME (type) = name;
12724   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12725
12726   return set_die_type (die, type, cu);
12727 }
12728
12729 /* Read a C++ namespace.  */
12730
12731 static void
12732 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12733 {
12734   struct objfile *objfile = cu->objfile;
12735   int is_anonymous;
12736
12737   /* Add a symbol associated to this if we haven't seen the namespace
12738      before.  Also, add a using directive if it's an anonymous
12739      namespace.  */
12740
12741   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12742     {
12743       struct type *type;
12744
12745       type = read_type_die (die, cu);
12746       new_symbol (die, type, cu);
12747
12748       namespace_name (die, &is_anonymous, cu);
12749       if (is_anonymous)
12750         {
12751           const char *previous_prefix = determine_prefix (die, cu);
12752
12753           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12754                                   NULL, NULL, 0, &objfile->objfile_obstack);
12755         }
12756     }
12757
12758   if (die->child != NULL)
12759     {
12760       struct die_info *child_die = die->child;
12761
12762       while (child_die && child_die->tag)
12763         {
12764           process_die (child_die, cu);
12765           child_die = sibling_die (child_die);
12766         }
12767     }
12768 }
12769
12770 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12771    imported module.  Still we need that type as local Fortran "use ... only"
12772    declaration imports depend on the created type in determine_prefix.  */
12773
12774 static struct type *
12775 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12776 {
12777   struct objfile *objfile = cu->objfile;
12778   const char *module_name;
12779   struct type *type;
12780
12781   module_name = dwarf2_name (die, cu);
12782   if (!module_name)
12783     complaint (&symfile_complaints,
12784                _("DW_TAG_module has no name, offset 0x%x"),
12785                die->offset.sect_off);
12786   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12787
12788   /* determine_prefix uses TYPE_TAG_NAME.  */
12789   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12790
12791   return set_die_type (die, type, cu);
12792 }
12793
12794 /* Read a Fortran module.  */
12795
12796 static void
12797 read_module (struct die_info *die, struct dwarf2_cu *cu)
12798 {
12799   struct die_info *child_die = die->child;
12800
12801   while (child_die && child_die->tag)
12802     {
12803       process_die (child_die, cu);
12804       child_die = sibling_die (child_die);
12805     }
12806 }
12807
12808 /* Return the name of the namespace represented by DIE.  Set
12809    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12810    namespace.  */
12811
12812 static const char *
12813 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12814 {
12815   struct die_info *current_die;
12816   const char *name = NULL;
12817
12818   /* Loop through the extensions until we find a name.  */
12819
12820   for (current_die = die;
12821        current_die != NULL;
12822        current_die = dwarf2_extension (die, &cu))
12823     {
12824       name = dwarf2_name (current_die, cu);
12825       if (name != NULL)
12826         break;
12827     }
12828
12829   /* Is it an anonymous namespace?  */
12830
12831   *is_anonymous = (name == NULL);
12832   if (*is_anonymous)
12833     name = CP_ANONYMOUS_NAMESPACE_STR;
12834
12835   return name;
12836 }
12837
12838 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12839    the user defined type vector.  */
12840
12841 static struct type *
12842 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12843 {
12844   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12845   struct comp_unit_head *cu_header = &cu->header;
12846   struct type *type;
12847   struct attribute *attr_byte_size;
12848   struct attribute *attr_address_class;
12849   int byte_size, addr_class;
12850   struct type *target_type;
12851
12852   target_type = die_type (die, cu);
12853
12854   /* The die_type call above may have already set the type for this DIE.  */
12855   type = get_die_type (die, cu);
12856   if (type)
12857     return type;
12858
12859   type = lookup_pointer_type (target_type);
12860
12861   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12862   if (attr_byte_size)
12863     byte_size = DW_UNSND (attr_byte_size);
12864   else
12865     byte_size = cu_header->addr_size;
12866
12867   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12868   if (attr_address_class)
12869     addr_class = DW_UNSND (attr_address_class);
12870   else
12871     addr_class = DW_ADDR_none;
12872
12873   /* If the pointer size or address class is different than the
12874      default, create a type variant marked as such and set the
12875      length accordingly.  */
12876   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12877     {
12878       if (gdbarch_address_class_type_flags_p (gdbarch))
12879         {
12880           int type_flags;
12881
12882           type_flags = gdbarch_address_class_type_flags
12883                          (gdbarch, byte_size, addr_class);
12884           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12885                       == 0);
12886           type = make_type_with_address_space (type, type_flags);
12887         }
12888       else if (TYPE_LENGTH (type) != byte_size)
12889         {
12890           complaint (&symfile_complaints,
12891                      _("invalid pointer size %d"), byte_size);
12892         }
12893       else
12894         {
12895           /* Should we also complain about unhandled address classes?  */
12896         }
12897     }
12898
12899   TYPE_LENGTH (type) = byte_size;
12900   return set_die_type (die, type, cu);
12901 }
12902
12903 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12904    the user defined type vector.  */
12905
12906 static struct type *
12907 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12908 {
12909   struct type *type;
12910   struct type *to_type;
12911   struct type *domain;
12912
12913   to_type = die_type (die, cu);
12914   domain = die_containing_type (die, cu);
12915
12916   /* The calls above may have already set the type for this DIE.  */
12917   type = get_die_type (die, cu);
12918   if (type)
12919     return type;
12920
12921   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12922     type = lookup_methodptr_type (to_type);
12923   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12924     {
12925       struct type *new_type = alloc_type (cu->objfile);
12926
12927       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12928                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12929                             TYPE_VARARGS (to_type));
12930       type = lookup_methodptr_type (new_type);
12931     }
12932   else
12933     type = lookup_memberptr_type (to_type, domain);
12934
12935   return set_die_type (die, type, cu);
12936 }
12937
12938 /* Extract all information from a DW_TAG_reference_type DIE and add to
12939    the user defined type vector.  */
12940
12941 static struct type *
12942 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12943 {
12944   struct comp_unit_head *cu_header = &cu->header;
12945   struct type *type, *target_type;
12946   struct attribute *attr;
12947
12948   target_type = die_type (die, cu);
12949
12950   /* The die_type call above may have already set the type for this DIE.  */
12951   type = get_die_type (die, cu);
12952   if (type)
12953     return type;
12954
12955   type = lookup_reference_type (target_type);
12956   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12957   if (attr)
12958     {
12959       TYPE_LENGTH (type) = DW_UNSND (attr);
12960     }
12961   else
12962     {
12963       TYPE_LENGTH (type) = cu_header->addr_size;
12964     }
12965   return set_die_type (die, type, cu);
12966 }
12967
12968 static struct type *
12969 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12970 {
12971   struct type *base_type, *cv_type;
12972
12973   base_type = die_type (die, cu);
12974
12975   /* The die_type call above may have already set the type for this DIE.  */
12976   cv_type = get_die_type (die, cu);
12977   if (cv_type)
12978     return cv_type;
12979
12980   /* In case the const qualifier is applied to an array type, the element type
12981      is so qualified, not the array type (section 6.7.3 of C99).  */
12982   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12983     {
12984       struct type *el_type, *inner_array;
12985
12986       base_type = copy_type (base_type);
12987       inner_array = base_type;
12988
12989       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12990         {
12991           TYPE_TARGET_TYPE (inner_array) =
12992             copy_type (TYPE_TARGET_TYPE (inner_array));
12993           inner_array = TYPE_TARGET_TYPE (inner_array);
12994         }
12995
12996       el_type = TYPE_TARGET_TYPE (inner_array);
12997       TYPE_TARGET_TYPE (inner_array) =
12998         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12999
13000       return set_die_type (die, base_type, cu);
13001     }
13002
13003   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13004   return set_die_type (die, cv_type, cu);
13005 }
13006
13007 static struct type *
13008 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13009 {
13010   struct type *base_type, *cv_type;
13011
13012   base_type = die_type (die, cu);
13013
13014   /* The die_type call above may have already set the type for this DIE.  */
13015   cv_type = get_die_type (die, cu);
13016   if (cv_type)
13017     return cv_type;
13018
13019   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13020   return set_die_type (die, cv_type, cu);
13021 }
13022
13023 /* Handle DW_TAG_restrict_type.  */
13024
13025 static struct type *
13026 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13027 {
13028   struct type *base_type, *cv_type;
13029
13030   base_type = die_type (die, cu);
13031
13032   /* The die_type call above may have already set the type for this DIE.  */
13033   cv_type = get_die_type (die, cu);
13034   if (cv_type)
13035     return cv_type;
13036
13037   cv_type = make_restrict_type (base_type);
13038   return set_die_type (die, cv_type, cu);
13039 }
13040
13041 /* Extract all information from a DW_TAG_string_type DIE and add to
13042    the user defined type vector.  It isn't really a user defined type,
13043    but it behaves like one, with other DIE's using an AT_user_def_type
13044    attribute to reference it.  */
13045
13046 static struct type *
13047 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13048 {
13049   struct objfile *objfile = cu->objfile;
13050   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13051   struct type *type, *range_type, *index_type, *char_type;
13052   struct attribute *attr;
13053   unsigned int length;
13054
13055   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13056   if (attr)
13057     {
13058       length = DW_UNSND (attr);
13059     }
13060   else
13061     {
13062       /* Check for the DW_AT_byte_size attribute.  */
13063       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13064       if (attr)
13065         {
13066           length = DW_UNSND (attr);
13067         }
13068       else
13069         {
13070           length = 1;
13071         }
13072     }
13073
13074   index_type = objfile_type (objfile)->builtin_int;
13075   range_type = create_range_type (NULL, index_type, 1, length);
13076   char_type = language_string_char_type (cu->language_defn, gdbarch);
13077   type = create_string_type (NULL, char_type, range_type);
13078
13079   return set_die_type (die, type, cu);
13080 }
13081
13082 /* Assuming that DIE corresponds to a function, returns nonzero
13083    if the function is prototyped.  */
13084
13085 static int
13086 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13087 {
13088   struct attribute *attr;
13089
13090   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13091   if (attr && (DW_UNSND (attr) != 0))
13092     return 1;
13093
13094   /* The DWARF standard implies that the DW_AT_prototyped attribute
13095      is only meaninful for C, but the concept also extends to other
13096      languages that allow unprototyped functions (Eg: Objective C).
13097      For all other languages, assume that functions are always
13098      prototyped.  */
13099   if (cu->language != language_c
13100       && cu->language != language_objc
13101       && cu->language != language_opencl)
13102     return 1;
13103
13104   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13105      prototyped and unprototyped functions; default to prototyped,
13106      since that is more common in modern code (and RealView warns
13107      about unprototyped functions).  */
13108   if (producer_is_realview (cu->producer))
13109     return 1;
13110
13111   return 0;
13112 }
13113
13114 /* Handle DIES due to C code like:
13115
13116    struct foo
13117    {
13118    int (*funcp)(int a, long l);
13119    int b;
13120    };
13121
13122    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13123
13124 static struct type *
13125 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13126 {
13127   struct objfile *objfile = cu->objfile;
13128   struct type *type;            /* Type that this function returns.  */
13129   struct type *ftype;           /* Function that returns above type.  */
13130   struct attribute *attr;
13131
13132   type = die_type (die, cu);
13133
13134   /* The die_type call above may have already set the type for this DIE.  */
13135   ftype = get_die_type (die, cu);
13136   if (ftype)
13137     return ftype;
13138
13139   ftype = lookup_function_type (type);
13140
13141   if (prototyped_function_p (die, cu))
13142     TYPE_PROTOTYPED (ftype) = 1;
13143
13144   /* Store the calling convention in the type if it's available in
13145      the subroutine die.  Otherwise set the calling convention to
13146      the default value DW_CC_normal.  */
13147   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13148   if (attr)
13149     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13150   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13151     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13152   else
13153     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13154
13155   /* We need to add the subroutine type to the die immediately so
13156      we don't infinitely recurse when dealing with parameters
13157      declared as the same subroutine type.  */
13158   set_die_type (die, ftype, cu);
13159
13160   if (die->child != NULL)
13161     {
13162       struct type *void_type = objfile_type (objfile)->builtin_void;
13163       struct die_info *child_die;
13164       int nparams, iparams;
13165
13166       /* Count the number of parameters.
13167          FIXME: GDB currently ignores vararg functions, but knows about
13168          vararg member functions.  */
13169       nparams = 0;
13170       child_die = die->child;
13171       while (child_die && child_die->tag)
13172         {
13173           if (child_die->tag == DW_TAG_formal_parameter)
13174             nparams++;
13175           else if (child_die->tag == DW_TAG_unspecified_parameters)
13176             TYPE_VARARGS (ftype) = 1;
13177           child_die = sibling_die (child_die);
13178         }
13179
13180       /* Allocate storage for parameters and fill them in.  */
13181       TYPE_NFIELDS (ftype) = nparams;
13182       TYPE_FIELDS (ftype) = (struct field *)
13183         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13184
13185       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13186          even if we error out during the parameters reading below.  */
13187       for (iparams = 0; iparams < nparams; iparams++)
13188         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13189
13190       iparams = 0;
13191       child_die = die->child;
13192       while (child_die && child_die->tag)
13193         {
13194           if (child_die->tag == DW_TAG_formal_parameter)
13195             {
13196               struct type *arg_type;
13197
13198               /* DWARF version 2 has no clean way to discern C++
13199                  static and non-static member functions.  G++ helps
13200                  GDB by marking the first parameter for non-static
13201                  member functions (which is the this pointer) as
13202                  artificial.  We pass this information to
13203                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13204
13205                  DWARF version 3 added DW_AT_object_pointer, which GCC
13206                  4.5 does not yet generate.  */
13207               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13208               if (attr)
13209                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13210               else
13211                 {
13212                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13213
13214                   /* GCC/43521: In java, the formal parameter
13215                      "this" is sometimes not marked with DW_AT_artificial.  */
13216                   if (cu->language == language_java)
13217                     {
13218                       const char *name = dwarf2_name (child_die, cu);
13219
13220                       if (name && !strcmp (name, "this"))
13221                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13222                     }
13223                 }
13224               arg_type = die_type (child_die, cu);
13225
13226               /* RealView does not mark THIS as const, which the testsuite
13227                  expects.  GCC marks THIS as const in method definitions,
13228                  but not in the class specifications (GCC PR 43053).  */
13229               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13230                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13231                 {
13232                   int is_this = 0;
13233                   struct dwarf2_cu *arg_cu = cu;
13234                   const char *name = dwarf2_name (child_die, cu);
13235
13236                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13237                   if (attr)
13238                     {
13239                       /* If the compiler emits this, use it.  */
13240                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13241                         is_this = 1;
13242                     }
13243                   else if (name && strcmp (name, "this") == 0)
13244                     /* Function definitions will have the argument names.  */
13245                     is_this = 1;
13246                   else if (name == NULL && iparams == 0)
13247                     /* Declarations may not have the names, so like
13248                        elsewhere in GDB, assume an artificial first
13249                        argument is "this".  */
13250                     is_this = 1;
13251
13252                   if (is_this)
13253                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13254                                              arg_type, 0);
13255                 }
13256
13257               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13258               iparams++;
13259             }
13260           child_die = sibling_die (child_die);
13261         }
13262     }
13263
13264   return ftype;
13265 }
13266
13267 static struct type *
13268 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13269 {
13270   struct objfile *objfile = cu->objfile;
13271   const char *name = NULL;
13272   struct type *this_type, *target_type;
13273
13274   name = dwarf2_full_name (NULL, die, cu);
13275   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13276                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13277   TYPE_NAME (this_type) = name;
13278   set_die_type (die, this_type, cu);
13279   target_type = die_type (die, cu);
13280   if (target_type != this_type)
13281     TYPE_TARGET_TYPE (this_type) = target_type;
13282   else
13283     {
13284       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13285          spec and cause infinite loops in GDB.  */
13286       complaint (&symfile_complaints,
13287                  _("Self-referential DW_TAG_typedef "
13288                    "- DIE at 0x%x [in module %s]"),
13289                  die->offset.sect_off, objfile->name);
13290       TYPE_TARGET_TYPE (this_type) = NULL;
13291     }
13292   return this_type;
13293 }
13294
13295 /* Find a representation of a given base type and install
13296    it in the TYPE field of the die.  */
13297
13298 static struct type *
13299 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13300 {
13301   struct objfile *objfile = cu->objfile;
13302   struct type *type;
13303   struct attribute *attr;
13304   int encoding = 0, size = 0;
13305   const char *name;
13306   enum type_code code = TYPE_CODE_INT;
13307   int type_flags = 0;
13308   struct type *target_type = NULL;
13309
13310   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13311   if (attr)
13312     {
13313       encoding = DW_UNSND (attr);
13314     }
13315   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13316   if (attr)
13317     {
13318       size = DW_UNSND (attr);
13319     }
13320   name = dwarf2_name (die, cu);
13321   if (!name)
13322     {
13323       complaint (&symfile_complaints,
13324                  _("DW_AT_name missing from DW_TAG_base_type"));
13325     }
13326
13327   switch (encoding)
13328     {
13329       case DW_ATE_address:
13330         /* Turn DW_ATE_address into a void * pointer.  */
13331         code = TYPE_CODE_PTR;
13332         type_flags |= TYPE_FLAG_UNSIGNED;
13333         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13334         break;
13335       case DW_ATE_boolean:
13336         code = TYPE_CODE_BOOL;
13337         type_flags |= TYPE_FLAG_UNSIGNED;
13338         break;
13339       case DW_ATE_complex_float:
13340         code = TYPE_CODE_COMPLEX;
13341         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13342         break;
13343       case DW_ATE_decimal_float:
13344         code = TYPE_CODE_DECFLOAT;
13345         break;
13346       case DW_ATE_float:
13347         code = TYPE_CODE_FLT;
13348         break;
13349       case DW_ATE_signed:
13350         break;
13351       case DW_ATE_unsigned:
13352         type_flags |= TYPE_FLAG_UNSIGNED;
13353         if (cu->language == language_fortran
13354             && name
13355             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13356           code = TYPE_CODE_CHAR;
13357         break;
13358       case DW_ATE_signed_char:
13359         if (cu->language == language_ada || cu->language == language_m2
13360             || cu->language == language_pascal
13361             || cu->language == language_fortran)
13362           code = TYPE_CODE_CHAR;
13363         break;
13364       case DW_ATE_unsigned_char:
13365         if (cu->language == language_ada || cu->language == language_m2
13366             || cu->language == language_pascal
13367             || cu->language == language_fortran)
13368           code = TYPE_CODE_CHAR;
13369         type_flags |= TYPE_FLAG_UNSIGNED;
13370         break;
13371       case DW_ATE_UTF:
13372         /* We just treat this as an integer and then recognize the
13373            type by name elsewhere.  */
13374         break;
13375
13376       default:
13377         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13378                    dwarf_type_encoding_name (encoding));
13379         break;
13380     }
13381
13382   type = init_type (code, size, type_flags, NULL, objfile);
13383   TYPE_NAME (type) = name;
13384   TYPE_TARGET_TYPE (type) = target_type;
13385
13386   if (name && strcmp (name, "char") == 0)
13387     TYPE_NOSIGN (type) = 1;
13388
13389   return set_die_type (die, type, cu);
13390 }
13391
13392 /* Read the given DW_AT_subrange DIE.  */
13393
13394 static struct type *
13395 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13396 {
13397   struct type *base_type, *orig_base_type;
13398   struct type *range_type;
13399   struct attribute *attr;
13400   LONGEST low, high;
13401   int low_default_is_valid;
13402   const char *name;
13403   LONGEST negative_mask;
13404
13405   orig_base_type = die_type (die, cu);
13406   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13407      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13408      creating the range type, but we use the result of check_typedef
13409      when examining properties of the type.  */
13410   base_type = check_typedef (orig_base_type);
13411
13412   /* The die_type call above may have already set the type for this DIE.  */
13413   range_type = get_die_type (die, cu);
13414   if (range_type)
13415     return range_type;
13416
13417   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13418      omitting DW_AT_lower_bound.  */
13419   switch (cu->language)
13420     {
13421     case language_c:
13422     case language_cplus:
13423       low = 0;
13424       low_default_is_valid = 1;
13425       break;
13426     case language_fortran:
13427       low = 1;
13428       low_default_is_valid = 1;
13429       break;
13430     case language_d:
13431     case language_java:
13432     case language_objc:
13433       low = 0;
13434       low_default_is_valid = (cu->header.version >= 4);
13435       break;
13436     case language_ada:
13437     case language_m2:
13438     case language_pascal:
13439       low = 1;
13440       low_default_is_valid = (cu->header.version >= 4);
13441       break;
13442     default:
13443       low = 0;
13444       low_default_is_valid = 0;
13445       break;
13446     }
13447
13448   /* FIXME: For variable sized arrays either of these could be
13449      a variable rather than a constant value.  We'll allow it,
13450      but we don't know how to handle it.  */
13451   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13452   if (attr)
13453     low = dwarf2_get_attr_constant_value (attr, low);
13454   else if (!low_default_is_valid)
13455     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13456                                       "- DIE at 0x%x [in module %s]"),
13457                die->offset.sect_off, cu->objfile->name);
13458
13459   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13460   if (attr)
13461     {
13462       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
13463         {
13464           /* GCC encodes arrays with unspecified or dynamic length
13465              with a DW_FORM_block1 attribute or a reference attribute.
13466              FIXME: GDB does not yet know how to handle dynamic
13467              arrays properly, treat them as arrays with unspecified
13468              length for now.
13469
13470              FIXME: jimb/2003-09-22: GDB does not really know
13471              how to handle arrays of unspecified length
13472              either; we just represent them as zero-length
13473              arrays.  Choose an appropriate upper bound given
13474              the lower bound we've computed above.  */
13475           high = low - 1;
13476         }
13477       else
13478         high = dwarf2_get_attr_constant_value (attr, 1);
13479     }
13480   else
13481     {
13482       attr = dwarf2_attr (die, DW_AT_count, cu);
13483       if (attr)
13484         {
13485           int count = dwarf2_get_attr_constant_value (attr, 1);
13486           high = low + count - 1;
13487         }
13488       else
13489         {
13490           /* Unspecified array length.  */
13491           high = low - 1;
13492         }
13493     }
13494
13495   /* Dwarf-2 specifications explicitly allows to create subrange types
13496      without specifying a base type.
13497      In that case, the base type must be set to the type of
13498      the lower bound, upper bound or count, in that order, if any of these
13499      three attributes references an object that has a type.
13500      If no base type is found, the Dwarf-2 specifications say that
13501      a signed integer type of size equal to the size of an address should
13502      be used.
13503      For the following C code: `extern char gdb_int [];'
13504      GCC produces an empty range DIE.
13505      FIXME: muller/2010-05-28: Possible references to object for low bound,
13506      high bound or count are not yet handled by this code.  */
13507   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13508     {
13509       struct objfile *objfile = cu->objfile;
13510       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13511       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13512       struct type *int_type = objfile_type (objfile)->builtin_int;
13513
13514       /* Test "int", "long int", and "long long int" objfile types,
13515          and select the first one having a size above or equal to the
13516          architecture address size.  */
13517       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13518         base_type = int_type;
13519       else
13520         {
13521           int_type = objfile_type (objfile)->builtin_long;
13522           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13523             base_type = int_type;
13524           else
13525             {
13526               int_type = objfile_type (objfile)->builtin_long_long;
13527               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13528                 base_type = int_type;
13529             }
13530         }
13531     }
13532
13533   negative_mask =
13534     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13535   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13536     low |= negative_mask;
13537   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13538     high |= negative_mask;
13539
13540   range_type = create_range_type (NULL, orig_base_type, low, high);
13541
13542   /* Mark arrays with dynamic length at least as an array of unspecified
13543      length.  GDB could check the boundary but before it gets implemented at
13544      least allow accessing the array elements.  */
13545   if (attr && attr_form_is_block (attr))
13546     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13547
13548   /* Ada expects an empty array on no boundary attributes.  */
13549   if (attr == NULL && cu->language != language_ada)
13550     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13551
13552   name = dwarf2_name (die, cu);
13553   if (name)
13554     TYPE_NAME (range_type) = name;
13555
13556   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13557   if (attr)
13558     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13559
13560   set_die_type (die, range_type, cu);
13561
13562   /* set_die_type should be already done.  */
13563   set_descriptive_type (range_type, die, cu);
13564
13565   return range_type;
13566 }
13567
13568 static struct type *
13569 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13570 {
13571   struct type *type;
13572
13573   /* For now, we only support the C meaning of an unspecified type: void.  */
13574
13575   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13576   TYPE_NAME (type) = dwarf2_name (die, cu);
13577
13578   return set_die_type (die, type, cu);
13579 }
13580
13581 /* Read a single die and all its descendents.  Set the die's sibling
13582    field to NULL; set other fields in the die correctly, and set all
13583    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13584    location of the info_ptr after reading all of those dies.  PARENT
13585    is the parent of the die in question.  */
13586
13587 static struct die_info *
13588 read_die_and_children (const struct die_reader_specs *reader,
13589                        const gdb_byte *info_ptr,
13590                        const gdb_byte **new_info_ptr,
13591                        struct die_info *parent)
13592 {
13593   struct die_info *die;
13594   const gdb_byte *cur_ptr;
13595   int has_children;
13596
13597   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13598   if (die == NULL)
13599     {
13600       *new_info_ptr = cur_ptr;
13601       return NULL;
13602     }
13603   store_in_ref_table (die, reader->cu);
13604
13605   if (has_children)
13606     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13607   else
13608     {
13609       die->child = NULL;
13610       *new_info_ptr = cur_ptr;
13611     }
13612
13613   die->sibling = NULL;
13614   die->parent = parent;
13615   return die;
13616 }
13617
13618 /* Read a die, all of its descendents, and all of its siblings; set
13619    all of the fields of all of the dies correctly.  Arguments are as
13620    in read_die_and_children.  */
13621
13622 static struct die_info *
13623 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13624                          const gdb_byte *info_ptr,
13625                          const gdb_byte **new_info_ptr,
13626                          struct die_info *parent)
13627 {
13628   struct die_info *first_die, *last_sibling;
13629   const gdb_byte *cur_ptr;
13630
13631   cur_ptr = info_ptr;
13632   first_die = last_sibling = NULL;
13633
13634   while (1)
13635     {
13636       struct die_info *die
13637         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13638
13639       if (die == NULL)
13640         {
13641           *new_info_ptr = cur_ptr;
13642           return first_die;
13643         }
13644
13645       if (!first_die)
13646         first_die = die;
13647       else
13648         last_sibling->sibling = die;
13649
13650       last_sibling = die;
13651     }
13652 }
13653
13654 /* Read a die, all of its descendents, and all of its siblings; set
13655    all of the fields of all of the dies correctly.  Arguments are as
13656    in read_die_and_children.
13657    This the main entry point for reading a DIE and all its children.  */
13658
13659 static struct die_info *
13660 read_die_and_siblings (const struct die_reader_specs *reader,
13661                        const gdb_byte *info_ptr,
13662                        const gdb_byte **new_info_ptr,
13663                        struct die_info *parent)
13664 {
13665   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13666                                                   new_info_ptr, parent);
13667
13668   if (dwarf2_die_debug)
13669     {
13670       fprintf_unfiltered (gdb_stdlog,
13671                           "Read die from %s@0x%x of %s:\n",
13672                           bfd_section_name (reader->abfd,
13673                                             reader->die_section->asection),
13674                           (unsigned) (info_ptr - reader->die_section->buffer),
13675                           bfd_get_filename (reader->abfd));
13676       dump_die (die, dwarf2_die_debug);
13677     }
13678
13679   return die;
13680 }
13681
13682 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13683    attributes.
13684    The caller is responsible for filling in the extra attributes
13685    and updating (*DIEP)->num_attrs.
13686    Set DIEP to point to a newly allocated die with its information,
13687    except for its child, sibling, and parent fields.
13688    Set HAS_CHILDREN to tell whether the die has children or not.  */
13689
13690 static const gdb_byte *
13691 read_full_die_1 (const struct die_reader_specs *reader,
13692                  struct die_info **diep, const gdb_byte *info_ptr,
13693                  int *has_children, int num_extra_attrs)
13694 {
13695   unsigned int abbrev_number, bytes_read, i;
13696   sect_offset offset;
13697   struct abbrev_info *abbrev;
13698   struct die_info *die;
13699   struct dwarf2_cu *cu = reader->cu;
13700   bfd *abfd = reader->abfd;
13701
13702   offset.sect_off = info_ptr - reader->buffer;
13703   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13704   info_ptr += bytes_read;
13705   if (!abbrev_number)
13706     {
13707       *diep = NULL;
13708       *has_children = 0;
13709       return info_ptr;
13710     }
13711
13712   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13713   if (!abbrev)
13714     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13715            abbrev_number,
13716            bfd_get_filename (abfd));
13717
13718   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13719   die->offset = offset;
13720   die->tag = abbrev->tag;
13721   die->abbrev = abbrev_number;
13722
13723   /* Make the result usable.
13724      The caller needs to update num_attrs after adding the extra
13725      attributes.  */
13726   die->num_attrs = abbrev->num_attrs;
13727
13728   for (i = 0; i < abbrev->num_attrs; ++i)
13729     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13730                                info_ptr);
13731
13732   *diep = die;
13733   *has_children = abbrev->has_children;
13734   return info_ptr;
13735 }
13736
13737 /* Read a die and all its attributes.
13738    Set DIEP to point to a newly allocated die with its information,
13739    except for its child, sibling, and parent fields.
13740    Set HAS_CHILDREN to tell whether the die has children or not.  */
13741
13742 static const gdb_byte *
13743 read_full_die (const struct die_reader_specs *reader,
13744                struct die_info **diep, const gdb_byte *info_ptr,
13745                int *has_children)
13746 {
13747   const gdb_byte *result;
13748
13749   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13750
13751   if (dwarf2_die_debug)
13752     {
13753       fprintf_unfiltered (gdb_stdlog,
13754                           "Read die from %s@0x%x of %s:\n",
13755                           bfd_section_name (reader->abfd,
13756                                             reader->die_section->asection),
13757                           (unsigned) (info_ptr - reader->die_section->buffer),
13758                           bfd_get_filename (reader->abfd));
13759       dump_die (*diep, dwarf2_die_debug);
13760     }
13761
13762   return result;
13763 }
13764 \f
13765 /* Abbreviation tables.
13766
13767    In DWARF version 2, the description of the debugging information is
13768    stored in a separate .debug_abbrev section.  Before we read any
13769    dies from a section we read in all abbreviations and install them
13770    in a hash table.  */
13771
13772 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13773
13774 static struct abbrev_info *
13775 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13776 {
13777   struct abbrev_info *abbrev;
13778
13779   abbrev = (struct abbrev_info *)
13780     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13781   memset (abbrev, 0, sizeof (struct abbrev_info));
13782   return abbrev;
13783 }
13784
13785 /* Add an abbreviation to the table.  */
13786
13787 static void
13788 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13789                          unsigned int abbrev_number,
13790                          struct abbrev_info *abbrev)
13791 {
13792   unsigned int hash_number;
13793
13794   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13795   abbrev->next = abbrev_table->abbrevs[hash_number];
13796   abbrev_table->abbrevs[hash_number] = abbrev;
13797 }
13798
13799 /* Look up an abbrev in the table.
13800    Returns NULL if the abbrev is not found.  */
13801
13802 static struct abbrev_info *
13803 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13804                             unsigned int abbrev_number)
13805 {
13806   unsigned int hash_number;
13807   struct abbrev_info *abbrev;
13808
13809   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13810   abbrev = abbrev_table->abbrevs[hash_number];
13811
13812   while (abbrev)
13813     {
13814       if (abbrev->number == abbrev_number)
13815         return abbrev;
13816       abbrev = abbrev->next;
13817     }
13818   return NULL;
13819 }
13820
13821 /* Read in an abbrev table.  */
13822
13823 static struct abbrev_table *
13824 abbrev_table_read_table (struct dwarf2_section_info *section,
13825                          sect_offset offset)
13826 {
13827   struct objfile *objfile = dwarf2_per_objfile->objfile;
13828   bfd *abfd = section->asection->owner;
13829   struct abbrev_table *abbrev_table;
13830   const gdb_byte *abbrev_ptr;
13831   struct abbrev_info *cur_abbrev;
13832   unsigned int abbrev_number, bytes_read, abbrev_name;
13833   unsigned int abbrev_form;
13834   struct attr_abbrev *cur_attrs;
13835   unsigned int allocated_attrs;
13836
13837   abbrev_table = XMALLOC (struct abbrev_table);
13838   abbrev_table->offset = offset;
13839   obstack_init (&abbrev_table->abbrev_obstack);
13840   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13841                                          (ABBREV_HASH_SIZE
13842                                           * sizeof (struct abbrev_info *)));
13843   memset (abbrev_table->abbrevs, 0,
13844           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13845
13846   dwarf2_read_section (objfile, section);
13847   abbrev_ptr = section->buffer + offset.sect_off;
13848   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13849   abbrev_ptr += bytes_read;
13850
13851   allocated_attrs = ATTR_ALLOC_CHUNK;
13852   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13853
13854   /* Loop until we reach an abbrev number of 0.  */
13855   while (abbrev_number)
13856     {
13857       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13858
13859       /* read in abbrev header */
13860       cur_abbrev->number = abbrev_number;
13861       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13862       abbrev_ptr += bytes_read;
13863       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13864       abbrev_ptr += 1;
13865
13866       /* now read in declarations */
13867       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13868       abbrev_ptr += bytes_read;
13869       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13870       abbrev_ptr += bytes_read;
13871       while (abbrev_name)
13872         {
13873           if (cur_abbrev->num_attrs == allocated_attrs)
13874             {
13875               allocated_attrs += ATTR_ALLOC_CHUNK;
13876               cur_attrs
13877                 = xrealloc (cur_attrs, (allocated_attrs
13878                                         * sizeof (struct attr_abbrev)));
13879             }
13880
13881           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13882           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13883           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13884           abbrev_ptr += bytes_read;
13885           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13886           abbrev_ptr += bytes_read;
13887         }
13888
13889       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13890                                          (cur_abbrev->num_attrs
13891                                           * sizeof (struct attr_abbrev)));
13892       memcpy (cur_abbrev->attrs, cur_attrs,
13893               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13894
13895       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13896
13897       /* Get next abbreviation.
13898          Under Irix6 the abbreviations for a compilation unit are not
13899          always properly terminated with an abbrev number of 0.
13900          Exit loop if we encounter an abbreviation which we have
13901          already read (which means we are about to read the abbreviations
13902          for the next compile unit) or if the end of the abbreviation
13903          table is reached.  */
13904       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13905         break;
13906       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13907       abbrev_ptr += bytes_read;
13908       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13909         break;
13910     }
13911
13912   xfree (cur_attrs);
13913   return abbrev_table;
13914 }
13915
13916 /* Free the resources held by ABBREV_TABLE.  */
13917
13918 static void
13919 abbrev_table_free (struct abbrev_table *abbrev_table)
13920 {
13921   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13922   xfree (abbrev_table);
13923 }
13924
13925 /* Same as abbrev_table_free but as a cleanup.
13926    We pass in a pointer to the pointer to the table so that we can
13927    set the pointer to NULL when we're done.  It also simplifies
13928    build_type_unit_groups.  */
13929
13930 static void
13931 abbrev_table_free_cleanup (void *table_ptr)
13932 {
13933   struct abbrev_table **abbrev_table_ptr = table_ptr;
13934
13935   if (*abbrev_table_ptr != NULL)
13936     abbrev_table_free (*abbrev_table_ptr);
13937   *abbrev_table_ptr = NULL;
13938 }
13939
13940 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13941
13942 static void
13943 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13944                      struct dwarf2_section_info *abbrev_section)
13945 {
13946   cu->abbrev_table =
13947     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13948 }
13949
13950 /* Release the memory used by the abbrev table for a compilation unit.  */
13951
13952 static void
13953 dwarf2_free_abbrev_table (void *ptr_to_cu)
13954 {
13955   struct dwarf2_cu *cu = ptr_to_cu;
13956
13957   if (cu->abbrev_table != NULL)
13958     abbrev_table_free (cu->abbrev_table);
13959   /* Set this to NULL so that we SEGV if we try to read it later,
13960      and also because free_comp_unit verifies this is NULL.  */
13961   cu->abbrev_table = NULL;
13962 }
13963 \f
13964 /* Returns nonzero if TAG represents a type that we might generate a partial
13965    symbol for.  */
13966
13967 static int
13968 is_type_tag_for_partial (int tag)
13969 {
13970   switch (tag)
13971     {
13972 #if 0
13973     /* Some types that would be reasonable to generate partial symbols for,
13974        that we don't at present.  */
13975     case DW_TAG_array_type:
13976     case DW_TAG_file_type:
13977     case DW_TAG_ptr_to_member_type:
13978     case DW_TAG_set_type:
13979     case DW_TAG_string_type:
13980     case DW_TAG_subroutine_type:
13981 #endif
13982     case DW_TAG_base_type:
13983     case DW_TAG_class_type:
13984     case DW_TAG_interface_type:
13985     case DW_TAG_enumeration_type:
13986     case DW_TAG_structure_type:
13987     case DW_TAG_subrange_type:
13988     case DW_TAG_typedef:
13989     case DW_TAG_union_type:
13990       return 1;
13991     default:
13992       return 0;
13993     }
13994 }
13995
13996 /* Load all DIEs that are interesting for partial symbols into memory.  */
13997
13998 static struct partial_die_info *
13999 load_partial_dies (const struct die_reader_specs *reader,
14000                    const gdb_byte *info_ptr, int building_psymtab)
14001 {
14002   struct dwarf2_cu *cu = reader->cu;
14003   struct objfile *objfile = cu->objfile;
14004   struct partial_die_info *part_die;
14005   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14006   struct abbrev_info *abbrev;
14007   unsigned int bytes_read;
14008   unsigned int load_all = 0;
14009   int nesting_level = 1;
14010
14011   parent_die = NULL;
14012   last_die = NULL;
14013
14014   gdb_assert (cu->per_cu != NULL);
14015   if (cu->per_cu->load_all_dies)
14016     load_all = 1;
14017
14018   cu->partial_dies
14019     = htab_create_alloc_ex (cu->header.length / 12,
14020                             partial_die_hash,
14021                             partial_die_eq,
14022                             NULL,
14023                             &cu->comp_unit_obstack,
14024                             hashtab_obstack_allocate,
14025                             dummy_obstack_deallocate);
14026
14027   part_die = obstack_alloc (&cu->comp_unit_obstack,
14028                             sizeof (struct partial_die_info));
14029
14030   while (1)
14031     {
14032       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14033
14034       /* A NULL abbrev means the end of a series of children.  */
14035       if (abbrev == NULL)
14036         {
14037           if (--nesting_level == 0)
14038             {
14039               /* PART_DIE was probably the last thing allocated on the
14040                  comp_unit_obstack, so we could call obstack_free
14041                  here.  We don't do that because the waste is small,
14042                  and will be cleaned up when we're done with this
14043                  compilation unit.  This way, we're also more robust
14044                  against other users of the comp_unit_obstack.  */
14045               return first_die;
14046             }
14047           info_ptr += bytes_read;
14048           last_die = parent_die;
14049           parent_die = parent_die->die_parent;
14050           continue;
14051         }
14052
14053       /* Check for template arguments.  We never save these; if
14054          they're seen, we just mark the parent, and go on our way.  */
14055       if (parent_die != NULL
14056           && cu->language == language_cplus
14057           && (abbrev->tag == DW_TAG_template_type_param
14058               || abbrev->tag == DW_TAG_template_value_param))
14059         {
14060           parent_die->has_template_arguments = 1;
14061
14062           if (!load_all)
14063             {
14064               /* We don't need a partial DIE for the template argument.  */
14065               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14066               continue;
14067             }
14068         }
14069
14070       /* We only recurse into c++ subprograms looking for template arguments.
14071          Skip their other children.  */
14072       if (!load_all
14073           && cu->language == language_cplus
14074           && parent_die != NULL
14075           && parent_die->tag == DW_TAG_subprogram)
14076         {
14077           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14078           continue;
14079         }
14080
14081       /* Check whether this DIE is interesting enough to save.  Normally
14082          we would not be interested in members here, but there may be
14083          later variables referencing them via DW_AT_specification (for
14084          static members).  */
14085       if (!load_all
14086           && !is_type_tag_for_partial (abbrev->tag)
14087           && abbrev->tag != DW_TAG_constant
14088           && abbrev->tag != DW_TAG_enumerator
14089           && abbrev->tag != DW_TAG_subprogram
14090           && abbrev->tag != DW_TAG_lexical_block
14091           && abbrev->tag != DW_TAG_variable
14092           && abbrev->tag != DW_TAG_namespace
14093           && abbrev->tag != DW_TAG_module
14094           && abbrev->tag != DW_TAG_member
14095           && abbrev->tag != DW_TAG_imported_unit)
14096         {
14097           /* Otherwise we skip to the next sibling, if any.  */
14098           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14099           continue;
14100         }
14101
14102       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14103                                    info_ptr);
14104
14105       /* This two-pass algorithm for processing partial symbols has a
14106          high cost in cache pressure.  Thus, handle some simple cases
14107          here which cover the majority of C partial symbols.  DIEs
14108          which neither have specification tags in them, nor could have
14109          specification tags elsewhere pointing at them, can simply be
14110          processed and discarded.
14111
14112          This segment is also optional; scan_partial_symbols and
14113          add_partial_symbol will handle these DIEs if we chain
14114          them in normally.  When compilers which do not emit large
14115          quantities of duplicate debug information are more common,
14116          this code can probably be removed.  */
14117
14118       /* Any complete simple types at the top level (pretty much all
14119          of them, for a language without namespaces), can be processed
14120          directly.  */
14121       if (parent_die == NULL
14122           && part_die->has_specification == 0
14123           && part_die->is_declaration == 0
14124           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14125               || part_die->tag == DW_TAG_base_type
14126               || part_die->tag == DW_TAG_subrange_type))
14127         {
14128           if (building_psymtab && part_die->name != NULL)
14129             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14130                                  VAR_DOMAIN, LOC_TYPEDEF,
14131                                  &objfile->static_psymbols,
14132                                  0, (CORE_ADDR) 0, cu->language, objfile);
14133           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14134           continue;
14135         }
14136
14137       /* The exception for DW_TAG_typedef with has_children above is
14138          a workaround of GCC PR debug/47510.  In the case of this complaint
14139          type_name_no_tag_or_error will error on such types later.
14140
14141          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14142          it could not find the child DIEs referenced later, this is checked
14143          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14144
14145       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14146         complaint (&symfile_complaints,
14147                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14148                      "- DIE at 0x%x [in module %s]"),
14149                    part_die->offset.sect_off, objfile->name);
14150
14151       /* If we're at the second level, and we're an enumerator, and
14152          our parent has no specification (meaning possibly lives in a
14153          namespace elsewhere), then we can add the partial symbol now
14154          instead of queueing it.  */
14155       if (part_die->tag == DW_TAG_enumerator
14156           && parent_die != NULL
14157           && parent_die->die_parent == NULL
14158           && parent_die->tag == DW_TAG_enumeration_type
14159           && parent_die->has_specification == 0)
14160         {
14161           if (part_die->name == NULL)
14162             complaint (&symfile_complaints,
14163                        _("malformed enumerator DIE ignored"));
14164           else if (building_psymtab)
14165             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14166                                  VAR_DOMAIN, LOC_CONST,
14167                                  (cu->language == language_cplus
14168                                   || cu->language == language_java)
14169                                  ? &objfile->global_psymbols
14170                                  : &objfile->static_psymbols,
14171                                  0, (CORE_ADDR) 0, cu->language, objfile);
14172
14173           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14174           continue;
14175         }
14176
14177       /* We'll save this DIE so link it in.  */
14178       part_die->die_parent = parent_die;
14179       part_die->die_sibling = NULL;
14180       part_die->die_child = NULL;
14181
14182       if (last_die && last_die == parent_die)
14183         last_die->die_child = part_die;
14184       else if (last_die)
14185         last_die->die_sibling = part_die;
14186
14187       last_die = part_die;
14188
14189       if (first_die == NULL)
14190         first_die = part_die;
14191
14192       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14193          find interesting need to be in the hash table, because we
14194          also have the parent/sibling/child chains; only those that we
14195          might refer to by offset later during partial symbol reading.
14196
14197          For now this means things that might have be the target of a
14198          DW_AT_specification, DW_AT_abstract_origin, or
14199          DW_AT_extension.  DW_AT_extension will refer only to
14200          namespaces; DW_AT_abstract_origin refers to functions (and
14201          many things under the function DIE, but we do not recurse
14202          into function DIEs during partial symbol reading) and
14203          possibly variables as well; DW_AT_specification refers to
14204          declarations.  Declarations ought to have the DW_AT_declaration
14205          flag.  It happens that GCC forgets to put it in sometimes, but
14206          only for functions, not for types.
14207
14208          Adding more things than necessary to the hash table is harmless
14209          except for the performance cost.  Adding too few will result in
14210          wasted time in find_partial_die, when we reread the compilation
14211          unit with load_all_dies set.  */
14212
14213       if (load_all
14214           || abbrev->tag == DW_TAG_constant
14215           || abbrev->tag == DW_TAG_subprogram
14216           || abbrev->tag == DW_TAG_variable
14217           || abbrev->tag == DW_TAG_namespace
14218           || part_die->is_declaration)
14219         {
14220           void **slot;
14221
14222           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14223                                            part_die->offset.sect_off, INSERT);
14224           *slot = part_die;
14225         }
14226
14227       part_die = obstack_alloc (&cu->comp_unit_obstack,
14228                                 sizeof (struct partial_die_info));
14229
14230       /* For some DIEs we want to follow their children (if any).  For C
14231          we have no reason to follow the children of structures; for other
14232          languages we have to, so that we can get at method physnames
14233          to infer fully qualified class names, for DW_AT_specification,
14234          and for C++ template arguments.  For C++, we also look one level
14235          inside functions to find template arguments (if the name of the
14236          function does not already contain the template arguments).
14237
14238          For Ada, we need to scan the children of subprograms and lexical
14239          blocks as well because Ada allows the definition of nested
14240          entities that could be interesting for the debugger, such as
14241          nested subprograms for instance.  */
14242       if (last_die->has_children
14243           && (load_all
14244               || last_die->tag == DW_TAG_namespace
14245               || last_die->tag == DW_TAG_module
14246               || last_die->tag == DW_TAG_enumeration_type
14247               || (cu->language == language_cplus
14248                   && last_die->tag == DW_TAG_subprogram
14249                   && (last_die->name == NULL
14250                       || strchr (last_die->name, '<') == NULL))
14251               || (cu->language != language_c
14252                   && (last_die->tag == DW_TAG_class_type
14253                       || last_die->tag == DW_TAG_interface_type
14254                       || last_die->tag == DW_TAG_structure_type
14255                       || last_die->tag == DW_TAG_union_type))
14256               || (cu->language == language_ada
14257                   && (last_die->tag == DW_TAG_subprogram
14258                       || last_die->tag == DW_TAG_lexical_block))))
14259         {
14260           nesting_level++;
14261           parent_die = last_die;
14262           continue;
14263         }
14264
14265       /* Otherwise we skip to the next sibling, if any.  */
14266       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14267
14268       /* Back to the top, do it again.  */
14269     }
14270 }
14271
14272 /* Read a minimal amount of information into the minimal die structure.  */
14273
14274 static const gdb_byte *
14275 read_partial_die (const struct die_reader_specs *reader,
14276                   struct partial_die_info *part_die,
14277                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14278                   const gdb_byte *info_ptr)
14279 {
14280   struct dwarf2_cu *cu = reader->cu;
14281   struct objfile *objfile = cu->objfile;
14282   const gdb_byte *buffer = reader->buffer;
14283   unsigned int i;
14284   struct attribute attr;
14285   int has_low_pc_attr = 0;
14286   int has_high_pc_attr = 0;
14287   int high_pc_relative = 0;
14288
14289   memset (part_die, 0, sizeof (struct partial_die_info));
14290
14291   part_die->offset.sect_off = info_ptr - buffer;
14292
14293   info_ptr += abbrev_len;
14294
14295   if (abbrev == NULL)
14296     return info_ptr;
14297
14298   part_die->tag = abbrev->tag;
14299   part_die->has_children = abbrev->has_children;
14300
14301   for (i = 0; i < abbrev->num_attrs; ++i)
14302     {
14303       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14304
14305       /* Store the data if it is of an attribute we want to keep in a
14306          partial symbol table.  */
14307       switch (attr.name)
14308         {
14309         case DW_AT_name:
14310           switch (part_die->tag)
14311             {
14312             case DW_TAG_compile_unit:
14313             case DW_TAG_partial_unit:
14314             case DW_TAG_type_unit:
14315               /* Compilation units have a DW_AT_name that is a filename, not
14316                  a source language identifier.  */
14317             case DW_TAG_enumeration_type:
14318             case DW_TAG_enumerator:
14319               /* These tags always have simple identifiers already; no need
14320                  to canonicalize them.  */
14321               part_die->name = DW_STRING (&attr);
14322               break;
14323             default:
14324               part_die->name
14325                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14326                                             &objfile->objfile_obstack);
14327               break;
14328             }
14329           break;
14330         case DW_AT_linkage_name:
14331         case DW_AT_MIPS_linkage_name:
14332           /* Note that both forms of linkage name might appear.  We
14333              assume they will be the same, and we only store the last
14334              one we see.  */
14335           if (cu->language == language_ada)
14336             part_die->name = DW_STRING (&attr);
14337           part_die->linkage_name = DW_STRING (&attr);
14338           break;
14339         case DW_AT_low_pc:
14340           has_low_pc_attr = 1;
14341           part_die->lowpc = DW_ADDR (&attr);
14342           break;
14343         case DW_AT_high_pc:
14344           has_high_pc_attr = 1;
14345           if (attr.form == DW_FORM_addr
14346               || attr.form == DW_FORM_GNU_addr_index)
14347             part_die->highpc = DW_ADDR (&attr);
14348           else
14349             {
14350               high_pc_relative = 1;
14351               part_die->highpc = DW_UNSND (&attr);
14352             }
14353           break;
14354         case DW_AT_location:
14355           /* Support the .debug_loc offsets.  */
14356           if (attr_form_is_block (&attr))
14357             {
14358                part_die->d.locdesc = DW_BLOCK (&attr);
14359             }
14360           else if (attr_form_is_section_offset (&attr))
14361             {
14362               dwarf2_complex_location_expr_complaint ();
14363             }
14364           else
14365             {
14366               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14367                                                      "partial symbol information");
14368             }
14369           break;
14370         case DW_AT_external:
14371           part_die->is_external = DW_UNSND (&attr);
14372           break;
14373         case DW_AT_declaration:
14374           part_die->is_declaration = DW_UNSND (&attr);
14375           break;
14376         case DW_AT_type:
14377           part_die->has_type = 1;
14378           break;
14379         case DW_AT_abstract_origin:
14380         case DW_AT_specification:
14381         case DW_AT_extension:
14382           part_die->has_specification = 1;
14383           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14384           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14385                                    || cu->per_cu->is_dwz);
14386           break;
14387         case DW_AT_sibling:
14388           /* Ignore absolute siblings, they might point outside of
14389              the current compile unit.  */
14390           if (attr.form == DW_FORM_ref_addr)
14391             complaint (&symfile_complaints,
14392                        _("ignoring absolute DW_AT_sibling"));
14393           else
14394             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14395           break;
14396         case DW_AT_byte_size:
14397           part_die->has_byte_size = 1;
14398           break;
14399         case DW_AT_calling_convention:
14400           /* DWARF doesn't provide a way to identify a program's source-level
14401              entry point.  DW_AT_calling_convention attributes are only meant
14402              to describe functions' calling conventions.
14403
14404              However, because it's a necessary piece of information in
14405              Fortran, and because DW_CC_program is the only piece of debugging
14406              information whose definition refers to a 'main program' at all,
14407              several compilers have begun marking Fortran main programs with
14408              DW_CC_program --- even when those functions use the standard
14409              calling conventions.
14410
14411              So until DWARF specifies a way to provide this information and
14412              compilers pick up the new representation, we'll support this
14413              practice.  */
14414           if (DW_UNSND (&attr) == DW_CC_program
14415               && cu->language == language_fortran)
14416             {
14417               set_main_name (part_die->name);
14418
14419               /* As this DIE has a static linkage the name would be difficult
14420                  to look up later.  */
14421               language_of_main = language_fortran;
14422             }
14423           break;
14424         case DW_AT_inline:
14425           if (DW_UNSND (&attr) == DW_INL_inlined
14426               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14427             part_die->may_be_inlined = 1;
14428           break;
14429
14430         case DW_AT_import:
14431           if (part_die->tag == DW_TAG_imported_unit)
14432             {
14433               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14434               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14435                                   || cu->per_cu->is_dwz);
14436             }
14437           break;
14438
14439         default:
14440           break;
14441         }
14442     }
14443
14444   if (high_pc_relative)
14445     part_die->highpc += part_die->lowpc;
14446
14447   if (has_low_pc_attr && has_high_pc_attr)
14448     {
14449       /* When using the GNU linker, .gnu.linkonce. sections are used to
14450          eliminate duplicate copies of functions and vtables and such.
14451          The linker will arbitrarily choose one and discard the others.
14452          The AT_*_pc values for such functions refer to local labels in
14453          these sections.  If the section from that file was discarded, the
14454          labels are not in the output, so the relocs get a value of 0.
14455          If this is a discarded function, mark the pc bounds as invalid,
14456          so that GDB will ignore it.  */
14457       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14458         {
14459           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14460
14461           complaint (&symfile_complaints,
14462                      _("DW_AT_low_pc %s is zero "
14463                        "for DIE at 0x%x [in module %s]"),
14464                      paddress (gdbarch, part_die->lowpc),
14465                      part_die->offset.sect_off, objfile->name);
14466         }
14467       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14468       else if (part_die->lowpc >= part_die->highpc)
14469         {
14470           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14471
14472           complaint (&symfile_complaints,
14473                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14474                        "for DIE at 0x%x [in module %s]"),
14475                      paddress (gdbarch, part_die->lowpc),
14476                      paddress (gdbarch, part_die->highpc),
14477                      part_die->offset.sect_off, objfile->name);
14478         }
14479       else
14480         part_die->has_pc_info = 1;
14481     }
14482
14483   return info_ptr;
14484 }
14485
14486 /* Find a cached partial DIE at OFFSET in CU.  */
14487
14488 static struct partial_die_info *
14489 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14490 {
14491   struct partial_die_info *lookup_die = NULL;
14492   struct partial_die_info part_die;
14493
14494   part_die.offset = offset;
14495   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14496                                     offset.sect_off);
14497
14498   return lookup_die;
14499 }
14500
14501 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14502    except in the case of .debug_types DIEs which do not reference
14503    outside their CU (they do however referencing other types via
14504    DW_FORM_ref_sig8).  */
14505
14506 static struct partial_die_info *
14507 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14508 {
14509   struct objfile *objfile = cu->objfile;
14510   struct dwarf2_per_cu_data *per_cu = NULL;
14511   struct partial_die_info *pd = NULL;
14512
14513   if (offset_in_dwz == cu->per_cu->is_dwz
14514       && offset_in_cu_p (&cu->header, offset))
14515     {
14516       pd = find_partial_die_in_comp_unit (offset, cu);
14517       if (pd != NULL)
14518         return pd;
14519       /* We missed recording what we needed.
14520          Load all dies and try again.  */
14521       per_cu = cu->per_cu;
14522     }
14523   else
14524     {
14525       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14526       if (cu->per_cu->is_debug_types)
14527         {
14528           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14529                    " external reference to offset 0x%lx [in module %s].\n"),
14530                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14531                  bfd_get_filename (objfile->obfd));
14532         }
14533       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14534                                                  objfile);
14535
14536       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14537         load_partial_comp_unit (per_cu);
14538
14539       per_cu->cu->last_used = 0;
14540       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14541     }
14542
14543   /* If we didn't find it, and not all dies have been loaded,
14544      load them all and try again.  */
14545
14546   if (pd == NULL && per_cu->load_all_dies == 0)
14547     {
14548       per_cu->load_all_dies = 1;
14549
14550       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14551          THIS_CU->cu may already be in use.  So we can't just free it and
14552          replace its DIEs with the ones we read in.  Instead, we leave those
14553          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14554          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14555          set.  */
14556       load_partial_comp_unit (per_cu);
14557
14558       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14559     }
14560
14561   if (pd == NULL)
14562     internal_error (__FILE__, __LINE__,
14563                     _("could not find partial DIE 0x%x "
14564                       "in cache [from module %s]\n"),
14565                     offset.sect_off, bfd_get_filename (objfile->obfd));
14566   return pd;
14567 }
14568
14569 /* See if we can figure out if the class lives in a namespace.  We do
14570    this by looking for a member function; its demangled name will
14571    contain namespace info, if there is any.  */
14572
14573 static void
14574 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14575                                   struct dwarf2_cu *cu)
14576 {
14577   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14578      what template types look like, because the demangler
14579      frequently doesn't give the same name as the debug info.  We
14580      could fix this by only using the demangled name to get the
14581      prefix (but see comment in read_structure_type).  */
14582
14583   struct partial_die_info *real_pdi;
14584   struct partial_die_info *child_pdi;
14585
14586   /* If this DIE (this DIE's specification, if any) has a parent, then
14587      we should not do this.  We'll prepend the parent's fully qualified
14588      name when we create the partial symbol.  */
14589
14590   real_pdi = struct_pdi;
14591   while (real_pdi->has_specification)
14592     real_pdi = find_partial_die (real_pdi->spec_offset,
14593                                  real_pdi->spec_is_dwz, cu);
14594
14595   if (real_pdi->die_parent != NULL)
14596     return;
14597
14598   for (child_pdi = struct_pdi->die_child;
14599        child_pdi != NULL;
14600        child_pdi = child_pdi->die_sibling)
14601     {
14602       if (child_pdi->tag == DW_TAG_subprogram
14603           && child_pdi->linkage_name != NULL)
14604         {
14605           char *actual_class_name
14606             = language_class_name_from_physname (cu->language_defn,
14607                                                  child_pdi->linkage_name);
14608           if (actual_class_name != NULL)
14609             {
14610               struct_pdi->name
14611                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14612                                  actual_class_name,
14613                                  strlen (actual_class_name));
14614               xfree (actual_class_name);
14615             }
14616           break;
14617         }
14618     }
14619 }
14620
14621 /* Adjust PART_DIE before generating a symbol for it.  This function
14622    may set the is_external flag or change the DIE's name.  */
14623
14624 static void
14625 fixup_partial_die (struct partial_die_info *part_die,
14626                    struct dwarf2_cu *cu)
14627 {
14628   /* Once we've fixed up a die, there's no point in doing so again.
14629      This also avoids a memory leak if we were to call
14630      guess_partial_die_structure_name multiple times.  */
14631   if (part_die->fixup_called)
14632     return;
14633
14634   /* If we found a reference attribute and the DIE has no name, try
14635      to find a name in the referred to DIE.  */
14636
14637   if (part_die->name == NULL && part_die->has_specification)
14638     {
14639       struct partial_die_info *spec_die;
14640
14641       spec_die = find_partial_die (part_die->spec_offset,
14642                                    part_die->spec_is_dwz, cu);
14643
14644       fixup_partial_die (spec_die, cu);
14645
14646       if (spec_die->name)
14647         {
14648           part_die->name = spec_die->name;
14649
14650           /* Copy DW_AT_external attribute if it is set.  */
14651           if (spec_die->is_external)
14652             part_die->is_external = spec_die->is_external;
14653         }
14654     }
14655
14656   /* Set default names for some unnamed DIEs.  */
14657
14658   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14659     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14660
14661   /* If there is no parent die to provide a namespace, and there are
14662      children, see if we can determine the namespace from their linkage
14663      name.  */
14664   if (cu->language == language_cplus
14665       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14666       && part_die->die_parent == NULL
14667       && part_die->has_children
14668       && (part_die->tag == DW_TAG_class_type
14669           || part_die->tag == DW_TAG_structure_type
14670           || part_die->tag == DW_TAG_union_type))
14671     guess_partial_die_structure_name (part_die, cu);
14672
14673   /* GCC might emit a nameless struct or union that has a linkage
14674      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14675   if (part_die->name == NULL
14676       && (part_die->tag == DW_TAG_class_type
14677           || part_die->tag == DW_TAG_interface_type
14678           || part_die->tag == DW_TAG_structure_type
14679           || part_die->tag == DW_TAG_union_type)
14680       && part_die->linkage_name != NULL)
14681     {
14682       char *demangled;
14683
14684       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14685       if (demangled)
14686         {
14687           const char *base;
14688
14689           /* Strip any leading namespaces/classes, keep only the base name.
14690              DW_AT_name for named DIEs does not contain the prefixes.  */
14691           base = strrchr (demangled, ':');
14692           if (base && base > demangled && base[-1] == ':')
14693             base++;
14694           else
14695             base = demangled;
14696
14697           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14698                                           base, strlen (base));
14699           xfree (demangled);
14700         }
14701     }
14702
14703   part_die->fixup_called = 1;
14704 }
14705
14706 /* Read an attribute value described by an attribute form.  */
14707
14708 static const gdb_byte *
14709 read_attribute_value (const struct die_reader_specs *reader,
14710                       struct attribute *attr, unsigned form,
14711                       const gdb_byte *info_ptr)
14712 {
14713   struct dwarf2_cu *cu = reader->cu;
14714   bfd *abfd = reader->abfd;
14715   struct comp_unit_head *cu_header = &cu->header;
14716   unsigned int bytes_read;
14717   struct dwarf_block *blk;
14718
14719   attr->form = form;
14720   switch (form)
14721     {
14722     case DW_FORM_ref_addr:
14723       if (cu->header.version == 2)
14724         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14725       else
14726         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14727                                        &cu->header, &bytes_read);
14728       info_ptr += bytes_read;
14729       break;
14730     case DW_FORM_GNU_ref_alt:
14731       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14732       info_ptr += bytes_read;
14733       break;
14734     case DW_FORM_addr:
14735       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14736       info_ptr += bytes_read;
14737       break;
14738     case DW_FORM_block2:
14739       blk = dwarf_alloc_block (cu);
14740       blk->size = read_2_bytes (abfd, info_ptr);
14741       info_ptr += 2;
14742       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14743       info_ptr += blk->size;
14744       DW_BLOCK (attr) = blk;
14745       break;
14746     case DW_FORM_block4:
14747       blk = dwarf_alloc_block (cu);
14748       blk->size = read_4_bytes (abfd, info_ptr);
14749       info_ptr += 4;
14750       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14751       info_ptr += blk->size;
14752       DW_BLOCK (attr) = blk;
14753       break;
14754     case DW_FORM_data2:
14755       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14756       info_ptr += 2;
14757       break;
14758     case DW_FORM_data4:
14759       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14760       info_ptr += 4;
14761       break;
14762     case DW_FORM_data8:
14763       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14764       info_ptr += 8;
14765       break;
14766     case DW_FORM_sec_offset:
14767       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14768       info_ptr += bytes_read;
14769       break;
14770     case DW_FORM_string:
14771       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14772       DW_STRING_IS_CANONICAL (attr) = 0;
14773       info_ptr += bytes_read;
14774       break;
14775     case DW_FORM_strp:
14776       if (!cu->per_cu->is_dwz)
14777         {
14778           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14779                                                    &bytes_read);
14780           DW_STRING_IS_CANONICAL (attr) = 0;
14781           info_ptr += bytes_read;
14782           break;
14783         }
14784       /* FALLTHROUGH */
14785     case DW_FORM_GNU_strp_alt:
14786       {
14787         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14788         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14789                                           &bytes_read);
14790
14791         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14792         DW_STRING_IS_CANONICAL (attr) = 0;
14793         info_ptr += bytes_read;
14794       }
14795       break;
14796     case DW_FORM_exprloc:
14797     case DW_FORM_block:
14798       blk = dwarf_alloc_block (cu);
14799       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14800       info_ptr += bytes_read;
14801       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14802       info_ptr += blk->size;
14803       DW_BLOCK (attr) = blk;
14804       break;
14805     case DW_FORM_block1:
14806       blk = dwarf_alloc_block (cu);
14807       blk->size = read_1_byte (abfd, info_ptr);
14808       info_ptr += 1;
14809       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14810       info_ptr += blk->size;
14811       DW_BLOCK (attr) = blk;
14812       break;
14813     case DW_FORM_data1:
14814       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14815       info_ptr += 1;
14816       break;
14817     case DW_FORM_flag:
14818       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14819       info_ptr += 1;
14820       break;
14821     case DW_FORM_flag_present:
14822       DW_UNSND (attr) = 1;
14823       break;
14824     case DW_FORM_sdata:
14825       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14826       info_ptr += bytes_read;
14827       break;
14828     case DW_FORM_udata:
14829       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14830       info_ptr += bytes_read;
14831       break;
14832     case DW_FORM_ref1:
14833       DW_UNSND (attr) = (cu->header.offset.sect_off
14834                          + read_1_byte (abfd, info_ptr));
14835       info_ptr += 1;
14836       break;
14837     case DW_FORM_ref2:
14838       DW_UNSND (attr) = (cu->header.offset.sect_off
14839                          + read_2_bytes (abfd, info_ptr));
14840       info_ptr += 2;
14841       break;
14842     case DW_FORM_ref4:
14843       DW_UNSND (attr) = (cu->header.offset.sect_off
14844                          + read_4_bytes (abfd, info_ptr));
14845       info_ptr += 4;
14846       break;
14847     case DW_FORM_ref8:
14848       DW_UNSND (attr) = (cu->header.offset.sect_off
14849                          + read_8_bytes (abfd, info_ptr));
14850       info_ptr += 8;
14851       break;
14852     case DW_FORM_ref_sig8:
14853       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14854       info_ptr += 8;
14855       break;
14856     case DW_FORM_ref_udata:
14857       DW_UNSND (attr) = (cu->header.offset.sect_off
14858                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14859       info_ptr += bytes_read;
14860       break;
14861     case DW_FORM_indirect:
14862       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14863       info_ptr += bytes_read;
14864       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14865       break;
14866     case DW_FORM_GNU_addr_index:
14867       if (reader->dwo_file == NULL)
14868         {
14869           /* For now flag a hard error.
14870              Later we can turn this into a complaint.  */
14871           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14872                  dwarf_form_name (form),
14873                  bfd_get_filename (abfd));
14874         }
14875       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14876       info_ptr += bytes_read;
14877       break;
14878     case DW_FORM_GNU_str_index:
14879       if (reader->dwo_file == NULL)
14880         {
14881           /* For now flag a hard error.
14882              Later we can turn this into a complaint if warranted.  */
14883           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14884                  dwarf_form_name (form),
14885                  bfd_get_filename (abfd));
14886         }
14887       {
14888         ULONGEST str_index =
14889           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14890
14891         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14892         DW_STRING_IS_CANONICAL (attr) = 0;
14893         info_ptr += bytes_read;
14894       }
14895       break;
14896     default:
14897       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14898              dwarf_form_name (form),
14899              bfd_get_filename (abfd));
14900     }
14901
14902   /* Super hack.  */
14903   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
14904     attr->form = DW_FORM_GNU_ref_alt;
14905
14906   /* We have seen instances where the compiler tried to emit a byte
14907      size attribute of -1 which ended up being encoded as an unsigned
14908      0xffffffff.  Although 0xffffffff is technically a valid size value,
14909      an object of this size seems pretty unlikely so we can relatively
14910      safely treat these cases as if the size attribute was invalid and
14911      treat them as zero by default.  */
14912   if (attr->name == DW_AT_byte_size
14913       && form == DW_FORM_data4
14914       && DW_UNSND (attr) >= 0xffffffff)
14915     {
14916       complaint
14917         (&symfile_complaints,
14918          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14919          hex_string (DW_UNSND (attr)));
14920       DW_UNSND (attr) = 0;
14921     }
14922
14923   return info_ptr;
14924 }
14925
14926 /* Read an attribute described by an abbreviated attribute.  */
14927
14928 static const gdb_byte *
14929 read_attribute (const struct die_reader_specs *reader,
14930                 struct attribute *attr, struct attr_abbrev *abbrev,
14931                 const gdb_byte *info_ptr)
14932 {
14933   attr->name = abbrev->name;
14934   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14935 }
14936
14937 /* Read dwarf information from a buffer.  */
14938
14939 static unsigned int
14940 read_1_byte (bfd *abfd, const gdb_byte *buf)
14941 {
14942   return bfd_get_8 (abfd, buf);
14943 }
14944
14945 static int
14946 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14947 {
14948   return bfd_get_signed_8 (abfd, buf);
14949 }
14950
14951 static unsigned int
14952 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14953 {
14954   return bfd_get_16 (abfd, buf);
14955 }
14956
14957 static int
14958 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14959 {
14960   return bfd_get_signed_16 (abfd, buf);
14961 }
14962
14963 static unsigned int
14964 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14965 {
14966   return bfd_get_32 (abfd, buf);
14967 }
14968
14969 static int
14970 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14971 {
14972   return bfd_get_signed_32 (abfd, buf);
14973 }
14974
14975 static ULONGEST
14976 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14977 {
14978   return bfd_get_64 (abfd, buf);
14979 }
14980
14981 static CORE_ADDR
14982 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14983               unsigned int *bytes_read)
14984 {
14985   struct comp_unit_head *cu_header = &cu->header;
14986   CORE_ADDR retval = 0;
14987
14988   if (cu_header->signed_addr_p)
14989     {
14990       switch (cu_header->addr_size)
14991         {
14992         case 2:
14993           retval = bfd_get_signed_16 (abfd, buf);
14994           break;
14995         case 4:
14996           retval = bfd_get_signed_32 (abfd, buf);
14997           break;
14998         case 8:
14999           retval = bfd_get_signed_64 (abfd, buf);
15000           break;
15001         default:
15002           internal_error (__FILE__, __LINE__,
15003                           _("read_address: bad switch, signed [in module %s]"),
15004                           bfd_get_filename (abfd));
15005         }
15006     }
15007   else
15008     {
15009       switch (cu_header->addr_size)
15010         {
15011         case 2:
15012           retval = bfd_get_16 (abfd, buf);
15013           break;
15014         case 4:
15015           retval = bfd_get_32 (abfd, buf);
15016           break;
15017         case 8:
15018           retval = bfd_get_64 (abfd, buf);
15019           break;
15020         default:
15021           internal_error (__FILE__, __LINE__,
15022                           _("read_address: bad switch, "
15023                             "unsigned [in module %s]"),
15024                           bfd_get_filename (abfd));
15025         }
15026     }
15027
15028   *bytes_read = cu_header->addr_size;
15029   return retval;
15030 }
15031
15032 /* Read the initial length from a section.  The (draft) DWARF 3
15033    specification allows the initial length to take up either 4 bytes
15034    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15035    bytes describe the length and all offsets will be 8 bytes in length
15036    instead of 4.
15037
15038    An older, non-standard 64-bit format is also handled by this
15039    function.  The older format in question stores the initial length
15040    as an 8-byte quantity without an escape value.  Lengths greater
15041    than 2^32 aren't very common which means that the initial 4 bytes
15042    is almost always zero.  Since a length value of zero doesn't make
15043    sense for the 32-bit format, this initial zero can be considered to
15044    be an escape value which indicates the presence of the older 64-bit
15045    format.  As written, the code can't detect (old format) lengths
15046    greater than 4GB.  If it becomes necessary to handle lengths
15047    somewhat larger than 4GB, we could allow other small values (such
15048    as the non-sensical values of 1, 2, and 3) to also be used as
15049    escape values indicating the presence of the old format.
15050
15051    The value returned via bytes_read should be used to increment the
15052    relevant pointer after calling read_initial_length().
15053
15054    [ Note:  read_initial_length() and read_offset() are based on the
15055      document entitled "DWARF Debugging Information Format", revision
15056      3, draft 8, dated November 19, 2001.  This document was obtained
15057      from:
15058
15059         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15060
15061      This document is only a draft and is subject to change.  (So beware.)
15062
15063      Details regarding the older, non-standard 64-bit format were
15064      determined empirically by examining 64-bit ELF files produced by
15065      the SGI toolchain on an IRIX 6.5 machine.
15066
15067      - Kevin, July 16, 2002
15068    ] */
15069
15070 static LONGEST
15071 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15072 {
15073   LONGEST length = bfd_get_32 (abfd, buf);
15074
15075   if (length == 0xffffffff)
15076     {
15077       length = bfd_get_64 (abfd, buf + 4);
15078       *bytes_read = 12;
15079     }
15080   else if (length == 0)
15081     {
15082       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15083       length = bfd_get_64 (abfd, buf);
15084       *bytes_read = 8;
15085     }
15086   else
15087     {
15088       *bytes_read = 4;
15089     }
15090
15091   return length;
15092 }
15093
15094 /* Cover function for read_initial_length.
15095    Returns the length of the object at BUF, and stores the size of the
15096    initial length in *BYTES_READ and stores the size that offsets will be in
15097    *OFFSET_SIZE.
15098    If the initial length size is not equivalent to that specified in
15099    CU_HEADER then issue a complaint.
15100    This is useful when reading non-comp-unit headers.  */
15101
15102 static LONGEST
15103 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15104                                         const struct comp_unit_head *cu_header,
15105                                         unsigned int *bytes_read,
15106                                         unsigned int *offset_size)
15107 {
15108   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15109
15110   gdb_assert (cu_header->initial_length_size == 4
15111               || cu_header->initial_length_size == 8
15112               || cu_header->initial_length_size == 12);
15113
15114   if (cu_header->initial_length_size != *bytes_read)
15115     complaint (&symfile_complaints,
15116                _("intermixed 32-bit and 64-bit DWARF sections"));
15117
15118   *offset_size = (*bytes_read == 4) ? 4 : 8;
15119   return length;
15120 }
15121
15122 /* Read an offset from the data stream.  The size of the offset is
15123    given by cu_header->offset_size.  */
15124
15125 static LONGEST
15126 read_offset (bfd *abfd, const gdb_byte *buf,
15127              const struct comp_unit_head *cu_header,
15128              unsigned int *bytes_read)
15129 {
15130   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15131
15132   *bytes_read = cu_header->offset_size;
15133   return offset;
15134 }
15135
15136 /* Read an offset from the data stream.  */
15137
15138 static LONGEST
15139 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15140 {
15141   LONGEST retval = 0;
15142
15143   switch (offset_size)
15144     {
15145     case 4:
15146       retval = bfd_get_32 (abfd, buf);
15147       break;
15148     case 8:
15149       retval = bfd_get_64 (abfd, buf);
15150       break;
15151     default:
15152       internal_error (__FILE__, __LINE__,
15153                       _("read_offset_1: bad switch [in module %s]"),
15154                       bfd_get_filename (abfd));
15155     }
15156
15157   return retval;
15158 }
15159
15160 static const gdb_byte *
15161 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15162 {
15163   /* If the size of a host char is 8 bits, we can return a pointer
15164      to the buffer, otherwise we have to copy the data to a buffer
15165      allocated on the temporary obstack.  */
15166   gdb_assert (HOST_CHAR_BIT == 8);
15167   return buf;
15168 }
15169
15170 static const char *
15171 read_direct_string (bfd *abfd, const gdb_byte *buf,
15172                     unsigned int *bytes_read_ptr)
15173 {
15174   /* If the size of a host char is 8 bits, we can return a pointer
15175      to the string, otherwise we have to copy the string to a buffer
15176      allocated on the temporary obstack.  */
15177   gdb_assert (HOST_CHAR_BIT == 8);
15178   if (*buf == '\0')
15179     {
15180       *bytes_read_ptr = 1;
15181       return NULL;
15182     }
15183   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15184   return (const char *) buf;
15185 }
15186
15187 static const char *
15188 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15189 {
15190   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15191   if (dwarf2_per_objfile->str.buffer == NULL)
15192     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15193            bfd_get_filename (abfd));
15194   if (str_offset >= dwarf2_per_objfile->str.size)
15195     error (_("DW_FORM_strp pointing outside of "
15196              ".debug_str section [in module %s]"),
15197            bfd_get_filename (abfd));
15198   gdb_assert (HOST_CHAR_BIT == 8);
15199   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15200     return NULL;
15201   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15202 }
15203
15204 /* Read a string at offset STR_OFFSET in the .debug_str section from
15205    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15206    the string consists of a single NUL byte, return NULL; otherwise
15207    return a pointer to the string.  */
15208
15209 static const char *
15210 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15211 {
15212   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15213
15214   if (dwz->str.buffer == NULL)
15215     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15216              "section [in module %s]"),
15217            bfd_get_filename (dwz->dwz_bfd));
15218   if (str_offset >= dwz->str.size)
15219     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15220              ".debug_str section [in module %s]"),
15221            bfd_get_filename (dwz->dwz_bfd));
15222   gdb_assert (HOST_CHAR_BIT == 8);
15223   if (dwz->str.buffer[str_offset] == '\0')
15224     return NULL;
15225   return (const char *) (dwz->str.buffer + str_offset);
15226 }
15227
15228 static const char *
15229 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15230                       const struct comp_unit_head *cu_header,
15231                       unsigned int *bytes_read_ptr)
15232 {
15233   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15234
15235   return read_indirect_string_at_offset (abfd, str_offset);
15236 }
15237
15238 static ULONGEST
15239 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15240                       unsigned int *bytes_read_ptr)
15241 {
15242   ULONGEST result;
15243   unsigned int num_read;
15244   int i, shift;
15245   unsigned char byte;
15246
15247   result = 0;
15248   shift = 0;
15249   num_read = 0;
15250   i = 0;
15251   while (1)
15252     {
15253       byte = bfd_get_8 (abfd, buf);
15254       buf++;
15255       num_read++;
15256       result |= ((ULONGEST) (byte & 127) << shift);
15257       if ((byte & 128) == 0)
15258         {
15259           break;
15260         }
15261       shift += 7;
15262     }
15263   *bytes_read_ptr = num_read;
15264   return result;
15265 }
15266
15267 static LONGEST
15268 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15269                     unsigned int *bytes_read_ptr)
15270 {
15271   LONGEST result;
15272   int i, shift, num_read;
15273   unsigned char byte;
15274
15275   result = 0;
15276   shift = 0;
15277   num_read = 0;
15278   i = 0;
15279   while (1)
15280     {
15281       byte = bfd_get_8 (abfd, buf);
15282       buf++;
15283       num_read++;
15284       result |= ((LONGEST) (byte & 127) << shift);
15285       shift += 7;
15286       if ((byte & 128) == 0)
15287         {
15288           break;
15289         }
15290     }
15291   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15292     result |= -(((LONGEST) 1) << shift);
15293   *bytes_read_ptr = num_read;
15294   return result;
15295 }
15296
15297 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15298    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15299    ADDR_SIZE is the size of addresses from the CU header.  */
15300
15301 static CORE_ADDR
15302 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15303 {
15304   struct objfile *objfile = dwarf2_per_objfile->objfile;
15305   bfd *abfd = objfile->obfd;
15306   const gdb_byte *info_ptr;
15307
15308   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15309   if (dwarf2_per_objfile->addr.buffer == NULL)
15310     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15311            objfile->name);
15312   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15313     error (_("DW_FORM_addr_index pointing outside of "
15314              ".debug_addr section [in module %s]"),
15315            objfile->name);
15316   info_ptr = (dwarf2_per_objfile->addr.buffer
15317               + addr_base + addr_index * addr_size);
15318   if (addr_size == 4)
15319     return bfd_get_32 (abfd, info_ptr);
15320   else
15321     return bfd_get_64 (abfd, info_ptr);
15322 }
15323
15324 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15325
15326 static CORE_ADDR
15327 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15328 {
15329   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15330 }
15331
15332 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15333
15334 static CORE_ADDR
15335 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15336                              unsigned int *bytes_read)
15337 {
15338   bfd *abfd = cu->objfile->obfd;
15339   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15340
15341   return read_addr_index (cu, addr_index);
15342 }
15343
15344 /* Data structure to pass results from dwarf2_read_addr_index_reader
15345    back to dwarf2_read_addr_index.  */
15346
15347 struct dwarf2_read_addr_index_data
15348 {
15349   ULONGEST addr_base;
15350   int addr_size;
15351 };
15352
15353 /* die_reader_func for dwarf2_read_addr_index.  */
15354
15355 static void
15356 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15357                                const gdb_byte *info_ptr,
15358                                struct die_info *comp_unit_die,
15359                                int has_children,
15360                                void *data)
15361 {
15362   struct dwarf2_cu *cu = reader->cu;
15363   struct dwarf2_read_addr_index_data *aidata =
15364     (struct dwarf2_read_addr_index_data *) data;
15365
15366   aidata->addr_base = cu->addr_base;
15367   aidata->addr_size = cu->header.addr_size;
15368 }
15369
15370 /* Given an index in .debug_addr, fetch the value.
15371    NOTE: This can be called during dwarf expression evaluation,
15372    long after the debug information has been read, and thus per_cu->cu
15373    may no longer exist.  */
15374
15375 CORE_ADDR
15376 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15377                         unsigned int addr_index)
15378 {
15379   struct objfile *objfile = per_cu->objfile;
15380   struct dwarf2_cu *cu = per_cu->cu;
15381   ULONGEST addr_base;
15382   int addr_size;
15383
15384   /* This is intended to be called from outside this file.  */
15385   dw2_setup (objfile);
15386
15387   /* We need addr_base and addr_size.
15388      If we don't have PER_CU->cu, we have to get it.
15389      Nasty, but the alternative is storing the needed info in PER_CU,
15390      which at this point doesn't seem justified: it's not clear how frequently
15391      it would get used and it would increase the size of every PER_CU.
15392      Entry points like dwarf2_per_cu_addr_size do a similar thing
15393      so we're not in uncharted territory here.
15394      Alas we need to be a bit more complicated as addr_base is contained
15395      in the DIE.
15396
15397      We don't need to read the entire CU(/TU).
15398      We just need the header and top level die.
15399
15400      IWBN to use the aging mechanism to let us lazily later discard the CU.
15401      For now we skip this optimization.  */
15402
15403   if (cu != NULL)
15404     {
15405       addr_base = cu->addr_base;
15406       addr_size = cu->header.addr_size;
15407     }
15408   else
15409     {
15410       struct dwarf2_read_addr_index_data aidata;
15411
15412       /* Note: We can't use init_cutu_and_read_dies_simple here,
15413          we need addr_base.  */
15414       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15415                                dwarf2_read_addr_index_reader, &aidata);
15416       addr_base = aidata.addr_base;
15417       addr_size = aidata.addr_size;
15418     }
15419
15420   return read_addr_index_1 (addr_index, addr_base, addr_size);
15421 }
15422
15423 /* Given a DW_AT_str_index, fetch the string.  */
15424
15425 static const char *
15426 read_str_index (const struct die_reader_specs *reader,
15427                 struct dwarf2_cu *cu, ULONGEST str_index)
15428 {
15429   struct objfile *objfile = dwarf2_per_objfile->objfile;
15430   const char *dwo_name = objfile->name;
15431   bfd *abfd = objfile->obfd;
15432   struct dwo_sections *sections = &reader->dwo_file->sections;
15433   const gdb_byte *info_ptr;
15434   ULONGEST str_offset;
15435
15436   dwarf2_read_section (objfile, &sections->str);
15437   dwarf2_read_section (objfile, &sections->str_offsets);
15438   if (sections->str.buffer == NULL)
15439     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15440              " in CU at offset 0x%lx [in module %s]"),
15441            (long) cu->header.offset.sect_off, dwo_name);
15442   if (sections->str_offsets.buffer == NULL)
15443     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15444              " in CU at offset 0x%lx [in module %s]"),
15445            (long) cu->header.offset.sect_off, dwo_name);
15446   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15447     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15448              " section in CU at offset 0x%lx [in module %s]"),
15449            (long) cu->header.offset.sect_off, dwo_name);
15450   info_ptr = (sections->str_offsets.buffer
15451               + str_index * cu->header.offset_size);
15452   if (cu->header.offset_size == 4)
15453     str_offset = bfd_get_32 (abfd, info_ptr);
15454   else
15455     str_offset = bfd_get_64 (abfd, info_ptr);
15456   if (str_offset >= sections->str.size)
15457     error (_("Offset from DW_FORM_str_index pointing outside of"
15458              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15459            (long) cu->header.offset.sect_off, dwo_name);
15460   return (const char *) (sections->str.buffer + str_offset);
15461 }
15462
15463 /* Return the length of an LEB128 number in BUF.  */
15464
15465 static int
15466 leb128_size (const gdb_byte *buf)
15467 {
15468   const gdb_byte *begin = buf;
15469   gdb_byte byte;
15470
15471   while (1)
15472     {
15473       byte = *buf++;
15474       if ((byte & 128) == 0)
15475         return buf - begin;
15476     }
15477 }
15478
15479 static void
15480 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15481 {
15482   switch (lang)
15483     {
15484     case DW_LANG_C89:
15485     case DW_LANG_C99:
15486     case DW_LANG_C:
15487     case DW_LANG_UPC:
15488       cu->language = language_c;
15489       break;
15490     case DW_LANG_C_plus_plus:
15491       cu->language = language_cplus;
15492       break;
15493     case DW_LANG_D:
15494       cu->language = language_d;
15495       break;
15496     case DW_LANG_Fortran77:
15497     case DW_LANG_Fortran90:
15498     case DW_LANG_Fortran95:
15499       cu->language = language_fortran;
15500       break;
15501     case DW_LANG_Go:
15502       cu->language = language_go;
15503       break;
15504     case DW_LANG_Mips_Assembler:
15505       cu->language = language_asm;
15506       break;
15507     case DW_LANG_Java:
15508       cu->language = language_java;
15509       break;
15510     case DW_LANG_Ada83:
15511     case DW_LANG_Ada95:
15512       cu->language = language_ada;
15513       break;
15514     case DW_LANG_Modula2:
15515       cu->language = language_m2;
15516       break;
15517     case DW_LANG_Pascal83:
15518       cu->language = language_pascal;
15519       break;
15520     case DW_LANG_ObjC:
15521       cu->language = language_objc;
15522       break;
15523     case DW_LANG_Cobol74:
15524     case DW_LANG_Cobol85:
15525     default:
15526       cu->language = language_minimal;
15527       break;
15528     }
15529   cu->language_defn = language_def (cu->language);
15530 }
15531
15532 /* Return the named attribute or NULL if not there.  */
15533
15534 static struct attribute *
15535 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15536 {
15537   for (;;)
15538     {
15539       unsigned int i;
15540       struct attribute *spec = NULL;
15541
15542       for (i = 0; i < die->num_attrs; ++i)
15543         {
15544           if (die->attrs[i].name == name)
15545             return &die->attrs[i];
15546           if (die->attrs[i].name == DW_AT_specification
15547               || die->attrs[i].name == DW_AT_abstract_origin)
15548             spec = &die->attrs[i];
15549         }
15550
15551       if (!spec)
15552         break;
15553
15554       die = follow_die_ref (die, spec, &cu);
15555     }
15556
15557   return NULL;
15558 }
15559
15560 /* Return the named attribute or NULL if not there,
15561    but do not follow DW_AT_specification, etc.
15562    This is for use in contexts where we're reading .debug_types dies.
15563    Following DW_AT_specification, DW_AT_abstract_origin will take us
15564    back up the chain, and we want to go down.  */
15565
15566 static struct attribute *
15567 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15568 {
15569   unsigned int i;
15570
15571   for (i = 0; i < die->num_attrs; ++i)
15572     if (die->attrs[i].name == name)
15573       return &die->attrs[i];
15574
15575   return NULL;
15576 }
15577
15578 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15579    and holds a non-zero value.  This function should only be used for
15580    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15581
15582 static int
15583 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15584 {
15585   struct attribute *attr = dwarf2_attr (die, name, cu);
15586
15587   return (attr && DW_UNSND (attr));
15588 }
15589
15590 static int
15591 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15592 {
15593   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15594      which value is non-zero.  However, we have to be careful with
15595      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15596      (via dwarf2_flag_true_p) follows this attribute.  So we may
15597      end up accidently finding a declaration attribute that belongs
15598      to a different DIE referenced by the specification attribute,
15599      even though the given DIE does not have a declaration attribute.  */
15600   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15601           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15602 }
15603
15604 /* Return the die giving the specification for DIE, if there is
15605    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15606    containing the return value on output.  If there is no
15607    specification, but there is an abstract origin, that is
15608    returned.  */
15609
15610 static struct die_info *
15611 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15612 {
15613   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15614                                              *spec_cu);
15615
15616   if (spec_attr == NULL)
15617     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15618
15619   if (spec_attr == NULL)
15620     return NULL;
15621   else
15622     return follow_die_ref (die, spec_attr, spec_cu);
15623 }
15624
15625 /* Free the line_header structure *LH, and any arrays and strings it
15626    refers to.
15627    NOTE: This is also used as a "cleanup" function.  */
15628
15629 static void
15630 free_line_header (struct line_header *lh)
15631 {
15632   if (lh->standard_opcode_lengths)
15633     xfree (lh->standard_opcode_lengths);
15634
15635   /* Remember that all the lh->file_names[i].name pointers are
15636      pointers into debug_line_buffer, and don't need to be freed.  */
15637   if (lh->file_names)
15638     xfree (lh->file_names);
15639
15640   /* Similarly for the include directory names.  */
15641   if (lh->include_dirs)
15642     xfree (lh->include_dirs);
15643
15644   xfree (lh);
15645 }
15646
15647 /* Add an entry to LH's include directory table.  */
15648
15649 static void
15650 add_include_dir (struct line_header *lh, const char *include_dir)
15651 {
15652   /* Grow the array if necessary.  */
15653   if (lh->include_dirs_size == 0)
15654     {
15655       lh->include_dirs_size = 1; /* for testing */
15656       lh->include_dirs = xmalloc (lh->include_dirs_size
15657                                   * sizeof (*lh->include_dirs));
15658     }
15659   else if (lh->num_include_dirs >= lh->include_dirs_size)
15660     {
15661       lh->include_dirs_size *= 2;
15662       lh->include_dirs = xrealloc (lh->include_dirs,
15663                                    (lh->include_dirs_size
15664                                     * sizeof (*lh->include_dirs)));
15665     }
15666
15667   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15668 }
15669
15670 /* Add an entry to LH's file name table.  */
15671
15672 static void
15673 add_file_name (struct line_header *lh,
15674                const char *name,
15675                unsigned int dir_index,
15676                unsigned int mod_time,
15677                unsigned int length)
15678 {
15679   struct file_entry *fe;
15680
15681   /* Grow the array if necessary.  */
15682   if (lh->file_names_size == 0)
15683     {
15684       lh->file_names_size = 1; /* for testing */
15685       lh->file_names = xmalloc (lh->file_names_size
15686                                 * sizeof (*lh->file_names));
15687     }
15688   else if (lh->num_file_names >= lh->file_names_size)
15689     {
15690       lh->file_names_size *= 2;
15691       lh->file_names = xrealloc (lh->file_names,
15692                                  (lh->file_names_size
15693                                   * sizeof (*lh->file_names)));
15694     }
15695
15696   fe = &lh->file_names[lh->num_file_names++];
15697   fe->name = name;
15698   fe->dir_index = dir_index;
15699   fe->mod_time = mod_time;
15700   fe->length = length;
15701   fe->included_p = 0;
15702   fe->symtab = NULL;
15703 }
15704
15705 /* A convenience function to find the proper .debug_line section for a
15706    CU.  */
15707
15708 static struct dwarf2_section_info *
15709 get_debug_line_section (struct dwarf2_cu *cu)
15710 {
15711   struct dwarf2_section_info *section;
15712
15713   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15714      DWO file.  */
15715   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15716     section = &cu->dwo_unit->dwo_file->sections.line;
15717   else if (cu->per_cu->is_dwz)
15718     {
15719       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15720
15721       section = &dwz->line;
15722     }
15723   else
15724     section = &dwarf2_per_objfile->line;
15725
15726   return section;
15727 }
15728
15729 /* Read the statement program header starting at OFFSET in
15730    .debug_line, or .debug_line.dwo.  Return a pointer
15731    to a struct line_header, allocated using xmalloc.
15732
15733    NOTE: the strings in the include directory and file name tables of
15734    the returned object point into the dwarf line section buffer,
15735    and must not be freed.  */
15736
15737 static struct line_header *
15738 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15739 {
15740   struct cleanup *back_to;
15741   struct line_header *lh;
15742   const gdb_byte *line_ptr;
15743   unsigned int bytes_read, offset_size;
15744   int i;
15745   const char *cur_dir, *cur_file;
15746   struct dwarf2_section_info *section;
15747   bfd *abfd;
15748
15749   section = get_debug_line_section (cu);
15750   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15751   if (section->buffer == NULL)
15752     {
15753       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15754         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15755       else
15756         complaint (&symfile_complaints, _("missing .debug_line section"));
15757       return 0;
15758     }
15759
15760   /* We can't do this until we know the section is non-empty.
15761      Only then do we know we have such a section.  */
15762   abfd = section->asection->owner;
15763
15764   /* Make sure that at least there's room for the total_length field.
15765      That could be 12 bytes long, but we're just going to fudge that.  */
15766   if (offset + 4 >= section->size)
15767     {
15768       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15769       return 0;
15770     }
15771
15772   lh = xmalloc (sizeof (*lh));
15773   memset (lh, 0, sizeof (*lh));
15774   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15775                           (void *) lh);
15776
15777   line_ptr = section->buffer + offset;
15778
15779   /* Read in the header.  */
15780   lh->total_length =
15781     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15782                                             &bytes_read, &offset_size);
15783   line_ptr += bytes_read;
15784   if (line_ptr + lh->total_length > (section->buffer + section->size))
15785     {
15786       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15787       do_cleanups (back_to);
15788       return 0;
15789     }
15790   lh->statement_program_end = line_ptr + lh->total_length;
15791   lh->version = read_2_bytes (abfd, line_ptr);
15792   line_ptr += 2;
15793   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15794   line_ptr += offset_size;
15795   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15796   line_ptr += 1;
15797   if (lh->version >= 4)
15798     {
15799       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15800       line_ptr += 1;
15801     }
15802   else
15803     lh->maximum_ops_per_instruction = 1;
15804
15805   if (lh->maximum_ops_per_instruction == 0)
15806     {
15807       lh->maximum_ops_per_instruction = 1;
15808       complaint (&symfile_complaints,
15809                  _("invalid maximum_ops_per_instruction "
15810                    "in `.debug_line' section"));
15811     }
15812
15813   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15814   line_ptr += 1;
15815   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15816   line_ptr += 1;
15817   lh->line_range = read_1_byte (abfd, line_ptr);
15818   line_ptr += 1;
15819   lh->opcode_base = read_1_byte (abfd, line_ptr);
15820   line_ptr += 1;
15821   lh->standard_opcode_lengths
15822     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15823
15824   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15825   for (i = 1; i < lh->opcode_base; ++i)
15826     {
15827       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15828       line_ptr += 1;
15829     }
15830
15831   /* Read directory table.  */
15832   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15833     {
15834       line_ptr += bytes_read;
15835       add_include_dir (lh, cur_dir);
15836     }
15837   line_ptr += bytes_read;
15838
15839   /* Read file name table.  */
15840   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15841     {
15842       unsigned int dir_index, mod_time, length;
15843
15844       line_ptr += bytes_read;
15845       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15846       line_ptr += bytes_read;
15847       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15848       line_ptr += bytes_read;
15849       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15850       line_ptr += bytes_read;
15851
15852       add_file_name (lh, cur_file, dir_index, mod_time, length);
15853     }
15854   line_ptr += bytes_read;
15855   lh->statement_program_start = line_ptr;
15856
15857   if (line_ptr > (section->buffer + section->size))
15858     complaint (&symfile_complaints,
15859                _("line number info header doesn't "
15860                  "fit in `.debug_line' section"));
15861
15862   discard_cleanups (back_to);
15863   return lh;
15864 }
15865
15866 /* Subroutine of dwarf_decode_lines to simplify it.
15867    Return the file name of the psymtab for included file FILE_INDEX
15868    in line header LH of PST.
15869    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15870    If space for the result is malloc'd, it will be freed by a cleanup.
15871    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15872
15873    The function creates dangling cleanup registration.  */
15874
15875 static const char *
15876 psymtab_include_file_name (const struct line_header *lh, int file_index,
15877                            const struct partial_symtab *pst,
15878                            const char *comp_dir)
15879 {
15880   const struct file_entry fe = lh->file_names [file_index];
15881   const char *include_name = fe.name;
15882   const char *include_name_to_compare = include_name;
15883   const char *dir_name = NULL;
15884   const char *pst_filename;
15885   char *copied_name = NULL;
15886   int file_is_pst;
15887
15888   if (fe.dir_index)
15889     dir_name = lh->include_dirs[fe.dir_index - 1];
15890
15891   if (!IS_ABSOLUTE_PATH (include_name)
15892       && (dir_name != NULL || comp_dir != NULL))
15893     {
15894       /* Avoid creating a duplicate psymtab for PST.
15895          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15896          Before we do the comparison, however, we need to account
15897          for DIR_NAME and COMP_DIR.
15898          First prepend dir_name (if non-NULL).  If we still don't
15899          have an absolute path prepend comp_dir (if non-NULL).
15900          However, the directory we record in the include-file's
15901          psymtab does not contain COMP_DIR (to match the
15902          corresponding symtab(s)).
15903
15904          Example:
15905
15906          bash$ cd /tmp
15907          bash$ gcc -g ./hello.c
15908          include_name = "hello.c"
15909          dir_name = "."
15910          DW_AT_comp_dir = comp_dir = "/tmp"
15911          DW_AT_name = "./hello.c"  */
15912
15913       if (dir_name != NULL)
15914         {
15915           char *tem = concat (dir_name, SLASH_STRING,
15916                               include_name, (char *)NULL);
15917
15918           make_cleanup (xfree, tem);
15919           include_name = tem;
15920           include_name_to_compare = include_name;
15921         }
15922       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15923         {
15924           char *tem = concat (comp_dir, SLASH_STRING,
15925                               include_name, (char *)NULL);
15926
15927           make_cleanup (xfree, tem);
15928           include_name_to_compare = tem;
15929         }
15930     }
15931
15932   pst_filename = pst->filename;
15933   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15934     {
15935       copied_name = concat (pst->dirname, SLASH_STRING,
15936                             pst_filename, (char *)NULL);
15937       pst_filename = copied_name;
15938     }
15939
15940   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15941
15942   if (copied_name != NULL)
15943     xfree (copied_name);
15944
15945   if (file_is_pst)
15946     return NULL;
15947   return include_name;
15948 }
15949
15950 /* Ignore this record_line request.  */
15951
15952 static void
15953 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15954 {
15955   return;
15956 }
15957
15958 /* Subroutine of dwarf_decode_lines to simplify it.
15959    Process the line number information in LH.  */
15960
15961 static void
15962 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15963                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15964 {
15965   const gdb_byte *line_ptr, *extended_end;
15966   const gdb_byte *line_end;
15967   unsigned int bytes_read, extended_len;
15968   unsigned char op_code, extended_op, adj_opcode;
15969   CORE_ADDR baseaddr;
15970   struct objfile *objfile = cu->objfile;
15971   bfd *abfd = objfile->obfd;
15972   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15973   const int decode_for_pst_p = (pst != NULL);
15974   struct subfile *last_subfile = NULL;
15975   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15976     = record_line;
15977
15978   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15979
15980   line_ptr = lh->statement_program_start;
15981   line_end = lh->statement_program_end;
15982
15983   /* Read the statement sequences until there's nothing left.  */
15984   while (line_ptr < line_end)
15985     {
15986       /* state machine registers  */
15987       CORE_ADDR address = 0;
15988       unsigned int file = 1;
15989       unsigned int line = 1;
15990       unsigned int column = 0;
15991       int is_stmt = lh->default_is_stmt;
15992       int basic_block = 0;
15993       int end_sequence = 0;
15994       CORE_ADDR addr;
15995       unsigned char op_index = 0;
15996
15997       if (!decode_for_pst_p && lh->num_file_names >= file)
15998         {
15999           /* Start a subfile for the current file of the state machine.  */
16000           /* lh->include_dirs and lh->file_names are 0-based, but the
16001              directory and file name numbers in the statement program
16002              are 1-based.  */
16003           struct file_entry *fe = &lh->file_names[file - 1];
16004           const char *dir = NULL;
16005
16006           if (fe->dir_index)
16007             dir = lh->include_dirs[fe->dir_index - 1];
16008
16009           dwarf2_start_subfile (fe->name, dir, comp_dir);
16010         }
16011
16012       /* Decode the table.  */
16013       while (!end_sequence)
16014         {
16015           op_code = read_1_byte (abfd, line_ptr);
16016           line_ptr += 1;
16017           if (line_ptr > line_end)
16018             {
16019               dwarf2_debug_line_missing_end_sequence_complaint ();
16020               break;
16021             }
16022
16023           if (op_code >= lh->opcode_base)
16024             {
16025               /* Special operand.  */
16026               adj_opcode = op_code - lh->opcode_base;
16027               address += (((op_index + (adj_opcode / lh->line_range))
16028                            / lh->maximum_ops_per_instruction)
16029                           * lh->minimum_instruction_length);
16030               op_index = ((op_index + (adj_opcode / lh->line_range))
16031                           % lh->maximum_ops_per_instruction);
16032               line += lh->line_base + (adj_opcode % lh->line_range);
16033               if (lh->num_file_names < file || file == 0)
16034                 dwarf2_debug_line_missing_file_complaint ();
16035               /* For now we ignore lines not starting on an
16036                  instruction boundary.  */
16037               else if (op_index == 0)
16038                 {
16039                   lh->file_names[file - 1].included_p = 1;
16040                   if (!decode_for_pst_p && is_stmt)
16041                     {
16042                       if (last_subfile != current_subfile)
16043                         {
16044                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16045                           if (last_subfile)
16046                             (*p_record_line) (last_subfile, 0, addr);
16047                           last_subfile = current_subfile;
16048                         }
16049                       /* Append row to matrix using current values.  */
16050                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16051                       (*p_record_line) (current_subfile, line, addr);
16052                     }
16053                 }
16054               basic_block = 0;
16055             }
16056           else switch (op_code)
16057             {
16058             case DW_LNS_extended_op:
16059               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16060                                                    &bytes_read);
16061               line_ptr += bytes_read;
16062               extended_end = line_ptr + extended_len;
16063               extended_op = read_1_byte (abfd, line_ptr);
16064               line_ptr += 1;
16065               switch (extended_op)
16066                 {
16067                 case DW_LNE_end_sequence:
16068                   p_record_line = record_line;
16069                   end_sequence = 1;
16070                   break;
16071                 case DW_LNE_set_address:
16072                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16073
16074                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16075                     {
16076                       /* This line table is for a function which has been
16077                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16078
16079                       long line_offset
16080                         = line_ptr - get_debug_line_section (cu)->buffer;
16081
16082                       complaint (&symfile_complaints,
16083                                  _(".debug_line address at offset 0x%lx is 0 "
16084                                    "[in module %s]"),
16085                                  line_offset, objfile->name);
16086                       p_record_line = noop_record_line;
16087                     }
16088
16089                   op_index = 0;
16090                   line_ptr += bytes_read;
16091                   address += baseaddr;
16092                   break;
16093                 case DW_LNE_define_file:
16094                   {
16095                     const char *cur_file;
16096                     unsigned int dir_index, mod_time, length;
16097
16098                     cur_file = read_direct_string (abfd, line_ptr,
16099                                                    &bytes_read);
16100                     line_ptr += bytes_read;
16101                     dir_index =
16102                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16103                     line_ptr += bytes_read;
16104                     mod_time =
16105                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16106                     line_ptr += bytes_read;
16107                     length =
16108                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16109                     line_ptr += bytes_read;
16110                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16111                   }
16112                   break;
16113                 case DW_LNE_set_discriminator:
16114                   /* The discriminator is not interesting to the debugger;
16115                      just ignore it.  */
16116                   line_ptr = extended_end;
16117                   break;
16118                 default:
16119                   complaint (&symfile_complaints,
16120                              _("mangled .debug_line section"));
16121                   return;
16122                 }
16123               /* Make sure that we parsed the extended op correctly.  If e.g.
16124                  we expected a different address size than the producer used,
16125                  we may have read the wrong number of bytes.  */
16126               if (line_ptr != extended_end)
16127                 {
16128                   complaint (&symfile_complaints,
16129                              _("mangled .debug_line section"));
16130                   return;
16131                 }
16132               break;
16133             case DW_LNS_copy:
16134               if (lh->num_file_names < file || file == 0)
16135                 dwarf2_debug_line_missing_file_complaint ();
16136               else
16137                 {
16138                   lh->file_names[file - 1].included_p = 1;
16139                   if (!decode_for_pst_p && is_stmt)
16140                     {
16141                       if (last_subfile != current_subfile)
16142                         {
16143                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16144                           if (last_subfile)
16145                             (*p_record_line) (last_subfile, 0, addr);
16146                           last_subfile = current_subfile;
16147                         }
16148                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16149                       (*p_record_line) (current_subfile, line, addr);
16150                     }
16151                 }
16152               basic_block = 0;
16153               break;
16154             case DW_LNS_advance_pc:
16155               {
16156                 CORE_ADDR adjust
16157                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16158
16159                 address += (((op_index + adjust)
16160                              / lh->maximum_ops_per_instruction)
16161                             * lh->minimum_instruction_length);
16162                 op_index = ((op_index + adjust)
16163                             % lh->maximum_ops_per_instruction);
16164                 line_ptr += bytes_read;
16165               }
16166               break;
16167             case DW_LNS_advance_line:
16168               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16169               line_ptr += bytes_read;
16170               break;
16171             case DW_LNS_set_file:
16172               {
16173                 /* The arrays lh->include_dirs and lh->file_names are
16174                    0-based, but the directory and file name numbers in
16175                    the statement program are 1-based.  */
16176                 struct file_entry *fe;
16177                 const char *dir = NULL;
16178
16179                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16180                 line_ptr += bytes_read;
16181                 if (lh->num_file_names < file || file == 0)
16182                   dwarf2_debug_line_missing_file_complaint ();
16183                 else
16184                   {
16185                     fe = &lh->file_names[file - 1];
16186                     if (fe->dir_index)
16187                       dir = lh->include_dirs[fe->dir_index - 1];
16188                     if (!decode_for_pst_p)
16189                       {
16190                         last_subfile = current_subfile;
16191                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16192                       }
16193                   }
16194               }
16195               break;
16196             case DW_LNS_set_column:
16197               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16198               line_ptr += bytes_read;
16199               break;
16200             case DW_LNS_negate_stmt:
16201               is_stmt = (!is_stmt);
16202               break;
16203             case DW_LNS_set_basic_block:
16204               basic_block = 1;
16205               break;
16206             /* Add to the address register of the state machine the
16207                address increment value corresponding to special opcode
16208                255.  I.e., this value is scaled by the minimum
16209                instruction length since special opcode 255 would have
16210                scaled the increment.  */
16211             case DW_LNS_const_add_pc:
16212               {
16213                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16214
16215                 address += (((op_index + adjust)
16216                              / lh->maximum_ops_per_instruction)
16217                             * lh->minimum_instruction_length);
16218                 op_index = ((op_index + adjust)
16219                             % lh->maximum_ops_per_instruction);
16220               }
16221               break;
16222             case DW_LNS_fixed_advance_pc:
16223               address += read_2_bytes (abfd, line_ptr);
16224               op_index = 0;
16225               line_ptr += 2;
16226               break;
16227             default:
16228               {
16229                 /* Unknown standard opcode, ignore it.  */
16230                 int i;
16231
16232                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16233                   {
16234                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16235                     line_ptr += bytes_read;
16236                   }
16237               }
16238             }
16239         }
16240       if (lh->num_file_names < file || file == 0)
16241         dwarf2_debug_line_missing_file_complaint ();
16242       else
16243         {
16244           lh->file_names[file - 1].included_p = 1;
16245           if (!decode_for_pst_p)
16246             {
16247               addr = gdbarch_addr_bits_remove (gdbarch, address);
16248               (*p_record_line) (current_subfile, 0, addr);
16249             }
16250         }
16251     }
16252 }
16253
16254 /* Decode the Line Number Program (LNP) for the given line_header
16255    structure and CU.  The actual information extracted and the type
16256    of structures created from the LNP depends on the value of PST.
16257
16258    1. If PST is NULL, then this procedure uses the data from the program
16259       to create all necessary symbol tables, and their linetables.
16260
16261    2. If PST is not NULL, this procedure reads the program to determine
16262       the list of files included by the unit represented by PST, and
16263       builds all the associated partial symbol tables.
16264
16265    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16266    It is used for relative paths in the line table.
16267    NOTE: When processing partial symtabs (pst != NULL),
16268    comp_dir == pst->dirname.
16269
16270    NOTE: It is important that psymtabs have the same file name (via strcmp)
16271    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16272    symtab we don't use it in the name of the psymtabs we create.
16273    E.g. expand_line_sal requires this when finding psymtabs to expand.
16274    A good testcase for this is mb-inline.exp.  */
16275
16276 static void
16277 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16278                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16279                     int want_line_info)
16280 {
16281   struct objfile *objfile = cu->objfile;
16282   const int decode_for_pst_p = (pst != NULL);
16283   struct subfile *first_subfile = current_subfile;
16284
16285   if (want_line_info)
16286     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16287
16288   if (decode_for_pst_p)
16289     {
16290       int file_index;
16291
16292       /* Now that we're done scanning the Line Header Program, we can
16293          create the psymtab of each included file.  */
16294       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16295         if (lh->file_names[file_index].included_p == 1)
16296           {
16297             const char *include_name =
16298               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16299             if (include_name != NULL)
16300               dwarf2_create_include_psymtab (include_name, pst, objfile);
16301           }
16302     }
16303   else
16304     {
16305       /* Make sure a symtab is created for every file, even files
16306          which contain only variables (i.e. no code with associated
16307          line numbers).  */
16308       int i;
16309
16310       for (i = 0; i < lh->num_file_names; i++)
16311         {
16312           const char *dir = NULL;
16313           struct file_entry *fe;
16314
16315           fe = &lh->file_names[i];
16316           if (fe->dir_index)
16317             dir = lh->include_dirs[fe->dir_index - 1];
16318           dwarf2_start_subfile (fe->name, dir, comp_dir);
16319
16320           /* Skip the main file; we don't need it, and it must be
16321              allocated last, so that it will show up before the
16322              non-primary symtabs in the objfile's symtab list.  */
16323           if (current_subfile == first_subfile)
16324             continue;
16325
16326           if (current_subfile->symtab == NULL)
16327             current_subfile->symtab = allocate_symtab (current_subfile->name,
16328                                                        objfile);
16329           fe->symtab = current_subfile->symtab;
16330         }
16331     }
16332 }
16333
16334 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16335    DIRNAME the name of the source directory which contains FILENAME
16336    or NULL if not known.  COMP_DIR is the compilation directory for the
16337    linetable's compilation unit or NULL if not known.
16338    This routine tries to keep line numbers from identical absolute and
16339    relative file names in a common subfile.
16340
16341    Using the `list' example from the GDB testsuite, which resides in
16342    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16343    of /srcdir/list0.c yields the following debugging information for list0.c:
16344
16345    DW_AT_name:          /srcdir/list0.c
16346    DW_AT_comp_dir:              /compdir
16347    files.files[0].name: list0.h
16348    files.files[0].dir:  /srcdir
16349    files.files[1].name: list0.c
16350    files.files[1].dir:  /srcdir
16351
16352    The line number information for list0.c has to end up in a single
16353    subfile, so that `break /srcdir/list0.c:1' works as expected.
16354    start_subfile will ensure that this happens provided that we pass the
16355    concatenation of files.files[1].dir and files.files[1].name as the
16356    subfile's name.  */
16357
16358 static void
16359 dwarf2_start_subfile (const char *filename, const char *dirname,
16360                       const char *comp_dir)
16361 {
16362   char *copy = NULL;
16363
16364   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16365      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16366      second argument to start_subfile.  To be consistent, we do the
16367      same here.  In order not to lose the line information directory,
16368      we concatenate it to the filename when it makes sense.
16369      Note that the Dwarf3 standard says (speaking of filenames in line
16370      information): ``The directory index is ignored for file names
16371      that represent full path names''.  Thus ignoring dirname in the
16372      `else' branch below isn't an issue.  */
16373
16374   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16375     {
16376       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16377       filename = copy;
16378     }
16379
16380   start_subfile (filename, comp_dir);
16381
16382   if (copy != NULL)
16383     xfree (copy);
16384 }
16385
16386 /* Start a symtab for DWARF.
16387    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16388
16389 static void
16390 dwarf2_start_symtab (struct dwarf2_cu *cu,
16391                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16392 {
16393   start_symtab (name, comp_dir, low_pc);
16394   record_debugformat ("DWARF 2");
16395   record_producer (cu->producer);
16396
16397   /* We assume that we're processing GCC output.  */
16398   processing_gcc_compilation = 2;
16399
16400   cu->processing_has_namespace_info = 0;
16401 }
16402
16403 static void
16404 var_decode_location (struct attribute *attr, struct symbol *sym,
16405                      struct dwarf2_cu *cu)
16406 {
16407   struct objfile *objfile = cu->objfile;
16408   struct comp_unit_head *cu_header = &cu->header;
16409
16410   /* NOTE drow/2003-01-30: There used to be a comment and some special
16411      code here to turn a symbol with DW_AT_external and a
16412      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16413      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16414      with some versions of binutils) where shared libraries could have
16415      relocations against symbols in their debug information - the
16416      minimal symbol would have the right address, but the debug info
16417      would not.  It's no longer necessary, because we will explicitly
16418      apply relocations when we read in the debug information now.  */
16419
16420   /* A DW_AT_location attribute with no contents indicates that a
16421      variable has been optimized away.  */
16422   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16423     {
16424       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16425       return;
16426     }
16427
16428   /* Handle one degenerate form of location expression specially, to
16429      preserve GDB's previous behavior when section offsets are
16430      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16431      then mark this symbol as LOC_STATIC.  */
16432
16433   if (attr_form_is_block (attr)
16434       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16435            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16436           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16437               && (DW_BLOCK (attr)->size
16438                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16439     {
16440       unsigned int dummy;
16441
16442       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16443         SYMBOL_VALUE_ADDRESS (sym) =
16444           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16445       else
16446         SYMBOL_VALUE_ADDRESS (sym) =
16447           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16448       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16449       fixup_symbol_section (sym, objfile);
16450       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16451                                               SYMBOL_SECTION (sym));
16452       return;
16453     }
16454
16455   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16456      expression evaluator, and use LOC_COMPUTED only when necessary
16457      (i.e. when the value of a register or memory location is
16458      referenced, or a thread-local block, etc.).  Then again, it might
16459      not be worthwhile.  I'm assuming that it isn't unless performance
16460      or memory numbers show me otherwise.  */
16461
16462   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16463
16464   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16465     cu->has_loclist = 1;
16466 }
16467
16468 /* Given a pointer to a DWARF information entry, figure out if we need
16469    to make a symbol table entry for it, and if so, create a new entry
16470    and return a pointer to it.
16471    If TYPE is NULL, determine symbol type from the die, otherwise
16472    used the passed type.
16473    If SPACE is not NULL, use it to hold the new symbol.  If it is
16474    NULL, allocate a new symbol on the objfile's obstack.  */
16475
16476 static struct symbol *
16477 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16478                  struct symbol *space)
16479 {
16480   struct objfile *objfile = cu->objfile;
16481   struct symbol *sym = NULL;
16482   const char *name;
16483   struct attribute *attr = NULL;
16484   struct attribute *attr2 = NULL;
16485   CORE_ADDR baseaddr;
16486   struct pending **list_to_add = NULL;
16487
16488   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16489
16490   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16491
16492   name = dwarf2_name (die, cu);
16493   if (name)
16494     {
16495       const char *linkagename;
16496       int suppress_add = 0;
16497
16498       if (space)
16499         sym = space;
16500       else
16501         sym = allocate_symbol (objfile);
16502       OBJSTAT (objfile, n_syms++);
16503
16504       /* Cache this symbol's name and the name's demangled form (if any).  */
16505       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16506       linkagename = dwarf2_physname (name, die, cu);
16507       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16508
16509       /* Fortran does not have mangling standard and the mangling does differ
16510          between gfortran, iFort etc.  */
16511       if (cu->language == language_fortran
16512           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16513         symbol_set_demangled_name (&(sym->ginfo),
16514                                    dwarf2_full_name (name, die, cu),
16515                                    NULL);
16516
16517       /* Default assumptions.
16518          Use the passed type or decode it from the die.  */
16519       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16520       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16521       if (type != NULL)
16522         SYMBOL_TYPE (sym) = type;
16523       else
16524         SYMBOL_TYPE (sym) = die_type (die, cu);
16525       attr = dwarf2_attr (die,
16526                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16527                           cu);
16528       if (attr)
16529         {
16530           SYMBOL_LINE (sym) = DW_UNSND (attr);
16531         }
16532
16533       attr = dwarf2_attr (die,
16534                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16535                           cu);
16536       if (attr)
16537         {
16538           int file_index = DW_UNSND (attr);
16539
16540           if (cu->line_header == NULL
16541               || file_index > cu->line_header->num_file_names)
16542             complaint (&symfile_complaints,
16543                        _("file index out of range"));
16544           else if (file_index > 0)
16545             {
16546               struct file_entry *fe;
16547
16548               fe = &cu->line_header->file_names[file_index - 1];
16549               SYMBOL_SYMTAB (sym) = fe->symtab;
16550             }
16551         }
16552
16553       switch (die->tag)
16554         {
16555         case DW_TAG_label:
16556           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16557           if (attr)
16558             {
16559               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16560             }
16561           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16562           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16563           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16564           add_symbol_to_list (sym, cu->list_in_scope);
16565           break;
16566         case DW_TAG_subprogram:
16567           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16568              finish_block.  */
16569           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16570           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16571           if ((attr2 && (DW_UNSND (attr2) != 0))
16572               || cu->language == language_ada)
16573             {
16574               /* Subprograms marked external are stored as a global symbol.
16575                  Ada subprograms, whether marked external or not, are always
16576                  stored as a global symbol, because we want to be able to
16577                  access them globally.  For instance, we want to be able
16578                  to break on a nested subprogram without having to
16579                  specify the context.  */
16580               list_to_add = &global_symbols;
16581             }
16582           else
16583             {
16584               list_to_add = cu->list_in_scope;
16585             }
16586           break;
16587         case DW_TAG_inlined_subroutine:
16588           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16589              finish_block.  */
16590           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16591           SYMBOL_INLINED (sym) = 1;
16592           list_to_add = cu->list_in_scope;
16593           break;
16594         case DW_TAG_template_value_param:
16595           suppress_add = 1;
16596           /* Fall through.  */
16597         case DW_TAG_constant:
16598         case DW_TAG_variable:
16599         case DW_TAG_member:
16600           /* Compilation with minimal debug info may result in
16601              variables with missing type entries.  Change the
16602              misleading `void' type to something sensible.  */
16603           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16604             SYMBOL_TYPE (sym)
16605               = objfile_type (objfile)->nodebug_data_symbol;
16606
16607           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16608           /* In the case of DW_TAG_member, we should only be called for
16609              static const members.  */
16610           if (die->tag == DW_TAG_member)
16611             {
16612               /* dwarf2_add_field uses die_is_declaration,
16613                  so we do the same.  */
16614               gdb_assert (die_is_declaration (die, cu));
16615               gdb_assert (attr);
16616             }
16617           if (attr)
16618             {
16619               dwarf2_const_value (attr, sym, cu);
16620               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16621               if (!suppress_add)
16622                 {
16623                   if (attr2 && (DW_UNSND (attr2) != 0))
16624                     list_to_add = &global_symbols;
16625                   else
16626                     list_to_add = cu->list_in_scope;
16627                 }
16628               break;
16629             }
16630           attr = dwarf2_attr (die, DW_AT_location, cu);
16631           if (attr)
16632             {
16633               var_decode_location (attr, sym, cu);
16634               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16635
16636               /* Fortran explicitly imports any global symbols to the local
16637                  scope by DW_TAG_common_block.  */
16638               if (cu->language == language_fortran && die->parent
16639                   && die->parent->tag == DW_TAG_common_block)
16640                 attr2 = NULL;
16641
16642               if (SYMBOL_CLASS (sym) == LOC_STATIC
16643                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16644                   && !dwarf2_per_objfile->has_section_at_zero)
16645                 {
16646                   /* When a static variable is eliminated by the linker,
16647                      the corresponding debug information is not stripped
16648                      out, but the variable address is set to null;
16649                      do not add such variables into symbol table.  */
16650                 }
16651               else if (attr2 && (DW_UNSND (attr2) != 0))
16652                 {
16653                   /* Workaround gfortran PR debug/40040 - it uses
16654                      DW_AT_location for variables in -fPIC libraries which may
16655                      get overriden by other libraries/executable and get
16656                      a different address.  Resolve it by the minimal symbol
16657                      which may come from inferior's executable using copy
16658                      relocation.  Make this workaround only for gfortran as for
16659                      other compilers GDB cannot guess the minimal symbol
16660                      Fortran mangling kind.  */
16661                   if (cu->language == language_fortran && die->parent
16662                       && die->parent->tag == DW_TAG_module
16663                       && cu->producer
16664                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16665                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16666
16667                   /* A variable with DW_AT_external is never static,
16668                      but it may be block-scoped.  */
16669                   list_to_add = (cu->list_in_scope == &file_symbols
16670                                  ? &global_symbols : cu->list_in_scope);
16671                 }
16672               else
16673                 list_to_add = cu->list_in_scope;
16674             }
16675           else
16676             {
16677               /* We do not know the address of this symbol.
16678                  If it is an external symbol and we have type information
16679                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16680                  The address of the variable will then be determined from
16681                  the minimal symbol table whenever the variable is
16682                  referenced.  */
16683               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16684
16685               /* Fortran explicitly imports any global symbols to the local
16686                  scope by DW_TAG_common_block.  */
16687               if (cu->language == language_fortran && die->parent
16688                   && die->parent->tag == DW_TAG_common_block)
16689                 {
16690                   /* SYMBOL_CLASS doesn't matter here because
16691                      read_common_block is going to reset it.  */
16692                   if (!suppress_add)
16693                     list_to_add = cu->list_in_scope;
16694                 }
16695               else if (attr2 && (DW_UNSND (attr2) != 0)
16696                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16697                 {
16698                   /* A variable with DW_AT_external is never static, but it
16699                      may be block-scoped.  */
16700                   list_to_add = (cu->list_in_scope == &file_symbols
16701                                  ? &global_symbols : cu->list_in_scope);
16702
16703                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16704                 }
16705               else if (!die_is_declaration (die, cu))
16706                 {
16707                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16708                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16709                   if (!suppress_add)
16710                     list_to_add = cu->list_in_scope;
16711                 }
16712             }
16713           break;
16714         case DW_TAG_formal_parameter:
16715           /* If we are inside a function, mark this as an argument.  If
16716              not, we might be looking at an argument to an inlined function
16717              when we do not have enough information to show inlined frames;
16718              pretend it's a local variable in that case so that the user can
16719              still see it.  */
16720           if (context_stack_depth > 0
16721               && context_stack[context_stack_depth - 1].name != NULL)
16722             SYMBOL_IS_ARGUMENT (sym) = 1;
16723           attr = dwarf2_attr (die, DW_AT_location, cu);
16724           if (attr)
16725             {
16726               var_decode_location (attr, sym, cu);
16727             }
16728           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16729           if (attr)
16730             {
16731               dwarf2_const_value (attr, sym, cu);
16732             }
16733
16734           list_to_add = cu->list_in_scope;
16735           break;
16736         case DW_TAG_unspecified_parameters:
16737           /* From varargs functions; gdb doesn't seem to have any
16738              interest in this information, so just ignore it for now.
16739              (FIXME?) */
16740           break;
16741         case DW_TAG_template_type_param:
16742           suppress_add = 1;
16743           /* Fall through.  */
16744         case DW_TAG_class_type:
16745         case DW_TAG_interface_type:
16746         case DW_TAG_structure_type:
16747         case DW_TAG_union_type:
16748         case DW_TAG_set_type:
16749         case DW_TAG_enumeration_type:
16750           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16751           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16752
16753           {
16754             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16755                really ever be static objects: otherwise, if you try
16756                to, say, break of a class's method and you're in a file
16757                which doesn't mention that class, it won't work unless
16758                the check for all static symbols in lookup_symbol_aux
16759                saves you.  See the OtherFileClass tests in
16760                gdb.c++/namespace.exp.  */
16761
16762             if (!suppress_add)
16763               {
16764                 list_to_add = (cu->list_in_scope == &file_symbols
16765                                && (cu->language == language_cplus
16766                                    || cu->language == language_java)
16767                                ? &global_symbols : cu->list_in_scope);
16768
16769                 /* The semantics of C++ state that "struct foo {
16770                    ... }" also defines a typedef for "foo".  A Java
16771                    class declaration also defines a typedef for the
16772                    class.  */
16773                 if (cu->language == language_cplus
16774                     || cu->language == language_java
16775                     || cu->language == language_ada)
16776                   {
16777                     /* The symbol's name is already allocated along
16778                        with this objfile, so we don't need to
16779                        duplicate it for the type.  */
16780                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16781                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16782                   }
16783               }
16784           }
16785           break;
16786         case DW_TAG_typedef:
16787           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16788           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16789           list_to_add = cu->list_in_scope;
16790           break;
16791         case DW_TAG_base_type:
16792         case DW_TAG_subrange_type:
16793           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16794           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16795           list_to_add = cu->list_in_scope;
16796           break;
16797         case DW_TAG_enumerator:
16798           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16799           if (attr)
16800             {
16801               dwarf2_const_value (attr, sym, cu);
16802             }
16803           {
16804             /* NOTE: carlton/2003-11-10: See comment above in the
16805                DW_TAG_class_type, etc. block.  */
16806
16807             list_to_add = (cu->list_in_scope == &file_symbols
16808                            && (cu->language == language_cplus
16809                                || cu->language == language_java)
16810                            ? &global_symbols : cu->list_in_scope);
16811           }
16812           break;
16813         case DW_TAG_namespace:
16814           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16815           list_to_add = &global_symbols;
16816           break;
16817         case DW_TAG_common_block:
16818           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16819           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16820           add_symbol_to_list (sym, cu->list_in_scope);
16821           break;
16822         default:
16823           /* Not a tag we recognize.  Hopefully we aren't processing
16824              trash data, but since we must specifically ignore things
16825              we don't recognize, there is nothing else we should do at
16826              this point.  */
16827           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16828                      dwarf_tag_name (die->tag));
16829           break;
16830         }
16831
16832       if (suppress_add)
16833         {
16834           sym->hash_next = objfile->template_symbols;
16835           objfile->template_symbols = sym;
16836           list_to_add = NULL;
16837         }
16838
16839       if (list_to_add != NULL)
16840         add_symbol_to_list (sym, list_to_add);
16841
16842       /* For the benefit of old versions of GCC, check for anonymous
16843          namespaces based on the demangled name.  */
16844       if (!cu->processing_has_namespace_info
16845           && cu->language == language_cplus)
16846         cp_scan_for_anonymous_namespaces (sym, objfile);
16847     }
16848   return (sym);
16849 }
16850
16851 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16852
16853 static struct symbol *
16854 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16855 {
16856   return new_symbol_full (die, type, cu, NULL);
16857 }
16858
16859 /* Given an attr with a DW_FORM_dataN value in host byte order,
16860    zero-extend it as appropriate for the symbol's type.  The DWARF
16861    standard (v4) is not entirely clear about the meaning of using
16862    DW_FORM_dataN for a constant with a signed type, where the type is
16863    wider than the data.  The conclusion of a discussion on the DWARF
16864    list was that this is unspecified.  We choose to always zero-extend
16865    because that is the interpretation long in use by GCC.  */
16866
16867 static gdb_byte *
16868 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
16869                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16870 {
16871   struct objfile *objfile = cu->objfile;
16872   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16873                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16874   LONGEST l = DW_UNSND (attr);
16875
16876   if (bits < sizeof (*value) * 8)
16877     {
16878       l &= ((LONGEST) 1 << bits) - 1;
16879       *value = l;
16880     }
16881   else if (bits == sizeof (*value) * 8)
16882     *value = l;
16883   else
16884     {
16885       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16886       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16887       return bytes;
16888     }
16889
16890   return NULL;
16891 }
16892
16893 /* Read a constant value from an attribute.  Either set *VALUE, or if
16894    the value does not fit in *VALUE, set *BYTES - either already
16895    allocated on the objfile obstack, or newly allocated on OBSTACK,
16896    or, set *BATON, if we translated the constant to a location
16897    expression.  */
16898
16899 static void
16900 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
16901                          const char *name, struct obstack *obstack,
16902                          struct dwarf2_cu *cu,
16903                          LONGEST *value, const gdb_byte **bytes,
16904                          struct dwarf2_locexpr_baton **baton)
16905 {
16906   struct objfile *objfile = cu->objfile;
16907   struct comp_unit_head *cu_header = &cu->header;
16908   struct dwarf_block *blk;
16909   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16910                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16911
16912   *value = 0;
16913   *bytes = NULL;
16914   *baton = NULL;
16915
16916   switch (attr->form)
16917     {
16918     case DW_FORM_addr:
16919     case DW_FORM_GNU_addr_index:
16920       {
16921         gdb_byte *data;
16922
16923         if (TYPE_LENGTH (type) != cu_header->addr_size)
16924           dwarf2_const_value_length_mismatch_complaint (name,
16925                                                         cu_header->addr_size,
16926                                                         TYPE_LENGTH (type));
16927         /* Symbols of this form are reasonably rare, so we just
16928            piggyback on the existing location code rather than writing
16929            a new implementation of symbol_computed_ops.  */
16930         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16931         (*baton)->per_cu = cu->per_cu;
16932         gdb_assert ((*baton)->per_cu);
16933
16934         (*baton)->size = 2 + cu_header->addr_size;
16935         data = obstack_alloc (obstack, (*baton)->size);
16936         (*baton)->data = data;
16937
16938         data[0] = DW_OP_addr;
16939         store_unsigned_integer (&data[1], cu_header->addr_size,
16940                                 byte_order, DW_ADDR (attr));
16941         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16942       }
16943       break;
16944     case DW_FORM_string:
16945     case DW_FORM_strp:
16946     case DW_FORM_GNU_str_index:
16947     case DW_FORM_GNU_strp_alt:
16948       /* DW_STRING is already allocated on the objfile obstack, point
16949          directly to it.  */
16950       *bytes = (const gdb_byte *) DW_STRING (attr);
16951       break;
16952     case DW_FORM_block1:
16953     case DW_FORM_block2:
16954     case DW_FORM_block4:
16955     case DW_FORM_block:
16956     case DW_FORM_exprloc:
16957       blk = DW_BLOCK (attr);
16958       if (TYPE_LENGTH (type) != blk->size)
16959         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16960                                                       TYPE_LENGTH (type));
16961       *bytes = blk->data;
16962       break;
16963
16964       /* The DW_AT_const_value attributes are supposed to carry the
16965          symbol's value "represented as it would be on the target
16966          architecture."  By the time we get here, it's already been
16967          converted to host endianness, so we just need to sign- or
16968          zero-extend it as appropriate.  */
16969     case DW_FORM_data1:
16970       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16971       break;
16972     case DW_FORM_data2:
16973       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16974       break;
16975     case DW_FORM_data4:
16976       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16977       break;
16978     case DW_FORM_data8:
16979       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16980       break;
16981
16982     case DW_FORM_sdata:
16983       *value = DW_SND (attr);
16984       break;
16985
16986     case DW_FORM_udata:
16987       *value = DW_UNSND (attr);
16988       break;
16989
16990     default:
16991       complaint (&symfile_complaints,
16992                  _("unsupported const value attribute form: '%s'"),
16993                  dwarf_form_name (attr->form));
16994       *value = 0;
16995       break;
16996     }
16997 }
16998
16999
17000 /* Copy constant value from an attribute to a symbol.  */
17001
17002 static void
17003 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17004                     struct dwarf2_cu *cu)
17005 {
17006   struct objfile *objfile = cu->objfile;
17007   struct comp_unit_head *cu_header = &cu->header;
17008   LONGEST value;
17009   const gdb_byte *bytes;
17010   struct dwarf2_locexpr_baton *baton;
17011
17012   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17013                            SYMBOL_PRINT_NAME (sym),
17014                            &objfile->objfile_obstack, cu,
17015                            &value, &bytes, &baton);
17016
17017   if (baton != NULL)
17018     {
17019       SYMBOL_LOCATION_BATON (sym) = baton;
17020       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17021     }
17022   else if (bytes != NULL)
17023      {
17024       SYMBOL_VALUE_BYTES (sym) = bytes;
17025       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17026     }
17027   else
17028     {
17029       SYMBOL_VALUE (sym) = value;
17030       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17031     }
17032 }
17033
17034 /* Return the type of the die in question using its DW_AT_type attribute.  */
17035
17036 static struct type *
17037 die_type (struct die_info *die, struct dwarf2_cu *cu)
17038 {
17039   struct attribute *type_attr;
17040
17041   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17042   if (!type_attr)
17043     {
17044       /* A missing DW_AT_type represents a void type.  */
17045       return objfile_type (cu->objfile)->builtin_void;
17046     }
17047
17048   return lookup_die_type (die, type_attr, cu);
17049 }
17050
17051 /* True iff CU's producer generates GNAT Ada auxiliary information
17052    that allows to find parallel types through that information instead
17053    of having to do expensive parallel lookups by type name.  */
17054
17055 static int
17056 need_gnat_info (struct dwarf2_cu *cu)
17057 {
17058   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17059      of GNAT produces this auxiliary information, without any indication
17060      that it is produced.  Part of enhancing the FSF version of GNAT
17061      to produce that information will be to put in place an indicator
17062      that we can use in order to determine whether the descriptive type
17063      info is available or not.  One suggestion that has been made is
17064      to use a new attribute, attached to the CU die.  For now, assume
17065      that the descriptive type info is not available.  */
17066   return 0;
17067 }
17068
17069 /* Return the auxiliary type of the die in question using its
17070    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17071    attribute is not present.  */
17072
17073 static struct type *
17074 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17075 {
17076   struct attribute *type_attr;
17077
17078   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17079   if (!type_attr)
17080     return NULL;
17081
17082   return lookup_die_type (die, type_attr, cu);
17083 }
17084
17085 /* If DIE has a descriptive_type attribute, then set the TYPE's
17086    descriptive type accordingly.  */
17087
17088 static void
17089 set_descriptive_type (struct type *type, struct die_info *die,
17090                       struct dwarf2_cu *cu)
17091 {
17092   struct type *descriptive_type = die_descriptive_type (die, cu);
17093
17094   if (descriptive_type)
17095     {
17096       ALLOCATE_GNAT_AUX_TYPE (type);
17097       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17098     }
17099 }
17100
17101 /* Return the containing type of the die in question using its
17102    DW_AT_containing_type attribute.  */
17103
17104 static struct type *
17105 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17106 {
17107   struct attribute *type_attr;
17108
17109   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17110   if (!type_attr)
17111     error (_("Dwarf Error: Problem turning containing type into gdb type "
17112              "[in module %s]"), cu->objfile->name);
17113
17114   return lookup_die_type (die, type_attr, cu);
17115 }
17116
17117 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17118
17119 static struct type *
17120 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17121 {
17122   struct objfile *objfile = dwarf2_per_objfile->objfile;
17123   char *message, *saved;
17124
17125   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17126                         objfile->name,
17127                         cu->header.offset.sect_off,
17128                         die->offset.sect_off);
17129   saved = obstack_copy0 (&objfile->objfile_obstack,
17130                          message, strlen (message));
17131   xfree (message);
17132
17133   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17134 }
17135
17136 /* Look up the type of DIE in CU using its type attribute ATTR.
17137    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17138    DW_AT_containing_type.
17139    If there is no type substitute an error marker.  */
17140
17141 static struct type *
17142 lookup_die_type (struct die_info *die, const struct attribute *attr,
17143                  struct dwarf2_cu *cu)
17144 {
17145   struct objfile *objfile = cu->objfile;
17146   struct type *this_type;
17147
17148   gdb_assert (attr->name == DW_AT_type
17149               || attr->name == DW_AT_GNAT_descriptive_type
17150               || attr->name == DW_AT_containing_type);
17151
17152   /* First see if we have it cached.  */
17153
17154   if (attr->form == DW_FORM_GNU_ref_alt)
17155     {
17156       struct dwarf2_per_cu_data *per_cu;
17157       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17158
17159       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17160       this_type = get_die_type_at_offset (offset, per_cu);
17161     }
17162   else if (attr_form_is_ref (attr))
17163     {
17164       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17165
17166       this_type = get_die_type_at_offset (offset, cu->per_cu);
17167     }
17168   else if (attr->form == DW_FORM_ref_sig8)
17169     {
17170       ULONGEST signature = DW_SIGNATURE (attr);
17171
17172       return get_signatured_type (die, signature, cu);
17173     }
17174   else
17175     {
17176       complaint (&symfile_complaints,
17177                  _("Dwarf Error: Bad type attribute %s in DIE"
17178                    " at 0x%x [in module %s]"),
17179                  dwarf_attr_name (attr->name), die->offset.sect_off,
17180                  objfile->name);
17181       return build_error_marker_type (cu, die);
17182     }
17183
17184   /* If not cached we need to read it in.  */
17185
17186   if (this_type == NULL)
17187     {
17188       struct die_info *type_die = NULL;
17189       struct dwarf2_cu *type_cu = cu;
17190
17191       if (attr_form_is_ref (attr))
17192         type_die = follow_die_ref (die, attr, &type_cu);
17193       if (type_die == NULL)
17194         return build_error_marker_type (cu, die);
17195       /* If we find the type now, it's probably because the type came
17196          from an inter-CU reference and the type's CU got expanded before
17197          ours.  */
17198       this_type = read_type_die (type_die, type_cu);
17199     }
17200
17201   /* If we still don't have a type use an error marker.  */
17202
17203   if (this_type == NULL)
17204     return build_error_marker_type (cu, die);
17205
17206   return this_type;
17207 }
17208
17209 /* Return the type in DIE, CU.
17210    Returns NULL for invalid types.
17211
17212    This first does a lookup in die_type_hash,
17213    and only reads the die in if necessary.
17214
17215    NOTE: This can be called when reading in partial or full symbols.  */
17216
17217 static struct type *
17218 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17219 {
17220   struct type *this_type;
17221
17222   this_type = get_die_type (die, cu);
17223   if (this_type)
17224     return this_type;
17225
17226   return read_type_die_1 (die, cu);
17227 }
17228
17229 /* Read the type in DIE, CU.
17230    Returns NULL for invalid types.  */
17231
17232 static struct type *
17233 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17234 {
17235   struct type *this_type = NULL;
17236
17237   switch (die->tag)
17238     {
17239     case DW_TAG_class_type:
17240     case DW_TAG_interface_type:
17241     case DW_TAG_structure_type:
17242     case DW_TAG_union_type:
17243       this_type = read_structure_type (die, cu);
17244       break;
17245     case DW_TAG_enumeration_type:
17246       this_type = read_enumeration_type (die, cu);
17247       break;
17248     case DW_TAG_subprogram:
17249     case DW_TAG_subroutine_type:
17250     case DW_TAG_inlined_subroutine:
17251       this_type = read_subroutine_type (die, cu);
17252       break;
17253     case DW_TAG_array_type:
17254       this_type = read_array_type (die, cu);
17255       break;
17256     case DW_TAG_set_type:
17257       this_type = read_set_type (die, cu);
17258       break;
17259     case DW_TAG_pointer_type:
17260       this_type = read_tag_pointer_type (die, cu);
17261       break;
17262     case DW_TAG_ptr_to_member_type:
17263       this_type = read_tag_ptr_to_member_type (die, cu);
17264       break;
17265     case DW_TAG_reference_type:
17266       this_type = read_tag_reference_type (die, cu);
17267       break;
17268     case DW_TAG_const_type:
17269       this_type = read_tag_const_type (die, cu);
17270       break;
17271     case DW_TAG_volatile_type:
17272       this_type = read_tag_volatile_type (die, cu);
17273       break;
17274     case DW_TAG_restrict_type:
17275       this_type = read_tag_restrict_type (die, cu);
17276       break;
17277     case DW_TAG_string_type:
17278       this_type = read_tag_string_type (die, cu);
17279       break;
17280     case DW_TAG_typedef:
17281       this_type = read_typedef (die, cu);
17282       break;
17283     case DW_TAG_subrange_type:
17284       this_type = read_subrange_type (die, cu);
17285       break;
17286     case DW_TAG_base_type:
17287       this_type = read_base_type (die, cu);
17288       break;
17289     case DW_TAG_unspecified_type:
17290       this_type = read_unspecified_type (die, cu);
17291       break;
17292     case DW_TAG_namespace:
17293       this_type = read_namespace_type (die, cu);
17294       break;
17295     case DW_TAG_module:
17296       this_type = read_module_type (die, cu);
17297       break;
17298     default:
17299       complaint (&symfile_complaints,
17300                  _("unexpected tag in read_type_die: '%s'"),
17301                  dwarf_tag_name (die->tag));
17302       break;
17303     }
17304
17305   return this_type;
17306 }
17307
17308 /* See if we can figure out if the class lives in a namespace.  We do
17309    this by looking for a member function; its demangled name will
17310    contain namespace info, if there is any.
17311    Return the computed name or NULL.
17312    Space for the result is allocated on the objfile's obstack.
17313    This is the full-die version of guess_partial_die_structure_name.
17314    In this case we know DIE has no useful parent.  */
17315
17316 static char *
17317 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17318 {
17319   struct die_info *spec_die;
17320   struct dwarf2_cu *spec_cu;
17321   struct die_info *child;
17322
17323   spec_cu = cu;
17324   spec_die = die_specification (die, &spec_cu);
17325   if (spec_die != NULL)
17326     {
17327       die = spec_die;
17328       cu = spec_cu;
17329     }
17330
17331   for (child = die->child;
17332        child != NULL;
17333        child = child->sibling)
17334     {
17335       if (child->tag == DW_TAG_subprogram)
17336         {
17337           struct attribute *attr;
17338
17339           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17340           if (attr == NULL)
17341             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17342           if (attr != NULL)
17343             {
17344               char *actual_name
17345                 = language_class_name_from_physname (cu->language_defn,
17346                                                      DW_STRING (attr));
17347               char *name = NULL;
17348
17349               if (actual_name != NULL)
17350                 {
17351                   const char *die_name = dwarf2_name (die, cu);
17352
17353                   if (die_name != NULL
17354                       && strcmp (die_name, actual_name) != 0)
17355                     {
17356                       /* Strip off the class name from the full name.
17357                          We want the prefix.  */
17358                       int die_name_len = strlen (die_name);
17359                       int actual_name_len = strlen (actual_name);
17360
17361                       /* Test for '::' as a sanity check.  */
17362                       if (actual_name_len > die_name_len + 2
17363                           && actual_name[actual_name_len
17364                                          - die_name_len - 1] == ':')
17365                         name =
17366                           obstack_copy0 (&cu->objfile->objfile_obstack,
17367                                          actual_name,
17368                                          actual_name_len - die_name_len - 2);
17369                     }
17370                 }
17371               xfree (actual_name);
17372               return name;
17373             }
17374         }
17375     }
17376
17377   return NULL;
17378 }
17379
17380 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17381    prefix part in such case.  See
17382    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17383
17384 static char *
17385 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17386 {
17387   struct attribute *attr;
17388   char *base;
17389
17390   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17391       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17392     return NULL;
17393
17394   attr = dwarf2_attr (die, DW_AT_name, cu);
17395   if (attr != NULL && DW_STRING (attr) != NULL)
17396     return NULL;
17397
17398   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17399   if (attr == NULL)
17400     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17401   if (attr == NULL || DW_STRING (attr) == NULL)
17402     return NULL;
17403
17404   /* dwarf2_name had to be already called.  */
17405   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17406
17407   /* Strip the base name, keep any leading namespaces/classes.  */
17408   base = strrchr (DW_STRING (attr), ':');
17409   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17410     return "";
17411
17412   return obstack_copy0 (&cu->objfile->objfile_obstack,
17413                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17414 }
17415
17416 /* Return the name of the namespace/class that DIE is defined within,
17417    or "" if we can't tell.  The caller should not xfree the result.
17418
17419    For example, if we're within the method foo() in the following
17420    code:
17421
17422    namespace N {
17423      class C {
17424        void foo () {
17425        }
17426      };
17427    }
17428
17429    then determine_prefix on foo's die will return "N::C".  */
17430
17431 static const char *
17432 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17433 {
17434   struct die_info *parent, *spec_die;
17435   struct dwarf2_cu *spec_cu;
17436   struct type *parent_type;
17437   char *retval;
17438
17439   if (cu->language != language_cplus && cu->language != language_java
17440       && cu->language != language_fortran)
17441     return "";
17442
17443   retval = anonymous_struct_prefix (die, cu);
17444   if (retval)
17445     return retval;
17446
17447   /* We have to be careful in the presence of DW_AT_specification.
17448      For example, with GCC 3.4, given the code
17449
17450      namespace N {
17451        void foo() {
17452          // Definition of N::foo.
17453        }
17454      }
17455
17456      then we'll have a tree of DIEs like this:
17457
17458      1: DW_TAG_compile_unit
17459        2: DW_TAG_namespace        // N
17460          3: DW_TAG_subprogram     // declaration of N::foo
17461        4: DW_TAG_subprogram       // definition of N::foo
17462             DW_AT_specification   // refers to die #3
17463
17464      Thus, when processing die #4, we have to pretend that we're in
17465      the context of its DW_AT_specification, namely the contex of die
17466      #3.  */
17467   spec_cu = cu;
17468   spec_die = die_specification (die, &spec_cu);
17469   if (spec_die == NULL)
17470     parent = die->parent;
17471   else
17472     {
17473       parent = spec_die->parent;
17474       cu = spec_cu;
17475     }
17476
17477   if (parent == NULL)
17478     return "";
17479   else if (parent->building_fullname)
17480     {
17481       const char *name;
17482       const char *parent_name;
17483
17484       /* It has been seen on RealView 2.2 built binaries,
17485          DW_TAG_template_type_param types actually _defined_ as
17486          children of the parent class:
17487
17488          enum E {};
17489          template class <class Enum> Class{};
17490          Class<enum E> class_e;
17491
17492          1: DW_TAG_class_type (Class)
17493            2: DW_TAG_enumeration_type (E)
17494              3: DW_TAG_enumerator (enum1:0)
17495              3: DW_TAG_enumerator (enum2:1)
17496              ...
17497            2: DW_TAG_template_type_param
17498               DW_AT_type  DW_FORM_ref_udata (E)
17499
17500          Besides being broken debug info, it can put GDB into an
17501          infinite loop.  Consider:
17502
17503          When we're building the full name for Class<E>, we'll start
17504          at Class, and go look over its template type parameters,
17505          finding E.  We'll then try to build the full name of E, and
17506          reach here.  We're now trying to build the full name of E,
17507          and look over the parent DIE for containing scope.  In the
17508          broken case, if we followed the parent DIE of E, we'd again
17509          find Class, and once again go look at its template type
17510          arguments, etc., etc.  Simply don't consider such parent die
17511          as source-level parent of this die (it can't be, the language
17512          doesn't allow it), and break the loop here.  */
17513       name = dwarf2_name (die, cu);
17514       parent_name = dwarf2_name (parent, cu);
17515       complaint (&symfile_complaints,
17516                  _("template param type '%s' defined within parent '%s'"),
17517                  name ? name : "<unknown>",
17518                  parent_name ? parent_name : "<unknown>");
17519       return "";
17520     }
17521   else
17522     switch (parent->tag)
17523       {
17524       case DW_TAG_namespace:
17525         parent_type = read_type_die (parent, cu);
17526         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17527            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17528            Work around this problem here.  */
17529         if (cu->language == language_cplus
17530             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17531           return "";
17532         /* We give a name to even anonymous namespaces.  */
17533         return TYPE_TAG_NAME (parent_type);
17534       case DW_TAG_class_type:
17535       case DW_TAG_interface_type:
17536       case DW_TAG_structure_type:
17537       case DW_TAG_union_type:
17538       case DW_TAG_module:
17539         parent_type = read_type_die (parent, cu);
17540         if (TYPE_TAG_NAME (parent_type) != NULL)
17541           return TYPE_TAG_NAME (parent_type);
17542         else
17543           /* An anonymous structure is only allowed non-static data
17544              members; no typedefs, no member functions, et cetera.
17545              So it does not need a prefix.  */
17546           return "";
17547       case DW_TAG_compile_unit:
17548       case DW_TAG_partial_unit:
17549         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17550         if (cu->language == language_cplus
17551             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17552             && die->child != NULL
17553             && (die->tag == DW_TAG_class_type
17554                 || die->tag == DW_TAG_structure_type
17555                 || die->tag == DW_TAG_union_type))
17556           {
17557             char *name = guess_full_die_structure_name (die, cu);
17558             if (name != NULL)
17559               return name;
17560           }
17561         return "";
17562       default:
17563         return determine_prefix (parent, cu);
17564       }
17565 }
17566
17567 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17568    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17569    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17570    an obconcat, otherwise allocate storage for the result.  The CU argument is
17571    used to determine the language and hence, the appropriate separator.  */
17572
17573 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17574
17575 static char *
17576 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17577                  int physname, struct dwarf2_cu *cu)
17578 {
17579   const char *lead = "";
17580   const char *sep;
17581
17582   if (suffix == NULL || suffix[0] == '\0'
17583       || prefix == NULL || prefix[0] == '\0')
17584     sep = "";
17585   else if (cu->language == language_java)
17586     sep = ".";
17587   else if (cu->language == language_fortran && physname)
17588     {
17589       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17590          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17591
17592       lead = "__";
17593       sep = "_MOD_";
17594     }
17595   else
17596     sep = "::";
17597
17598   if (prefix == NULL)
17599     prefix = "";
17600   if (suffix == NULL)
17601     suffix = "";
17602
17603   if (obs == NULL)
17604     {
17605       char *retval
17606         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17607
17608       strcpy (retval, lead);
17609       strcat (retval, prefix);
17610       strcat (retval, sep);
17611       strcat (retval, suffix);
17612       return retval;
17613     }
17614   else
17615     {
17616       /* We have an obstack.  */
17617       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17618     }
17619 }
17620
17621 /* Return sibling of die, NULL if no sibling.  */
17622
17623 static struct die_info *
17624 sibling_die (struct die_info *die)
17625 {
17626   return die->sibling;
17627 }
17628
17629 /* Get name of a die, return NULL if not found.  */
17630
17631 static const char *
17632 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17633                           struct obstack *obstack)
17634 {
17635   if (name && cu->language == language_cplus)
17636     {
17637       char *canon_name = cp_canonicalize_string (name);
17638
17639       if (canon_name != NULL)
17640         {
17641           if (strcmp (canon_name, name) != 0)
17642             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17643           xfree (canon_name);
17644         }
17645     }
17646
17647   return name;
17648 }
17649
17650 /* Get name of a die, return NULL if not found.  */
17651
17652 static const char *
17653 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17654 {
17655   struct attribute *attr;
17656
17657   attr = dwarf2_attr (die, DW_AT_name, cu);
17658   if ((!attr || !DW_STRING (attr))
17659       && die->tag != DW_TAG_class_type
17660       && die->tag != DW_TAG_interface_type
17661       && die->tag != DW_TAG_structure_type
17662       && die->tag != DW_TAG_union_type)
17663     return NULL;
17664
17665   switch (die->tag)
17666     {
17667     case DW_TAG_compile_unit:
17668     case DW_TAG_partial_unit:
17669       /* Compilation units have a DW_AT_name that is a filename, not
17670          a source language identifier.  */
17671     case DW_TAG_enumeration_type:
17672     case DW_TAG_enumerator:
17673       /* These tags always have simple identifiers already; no need
17674          to canonicalize them.  */
17675       return DW_STRING (attr);
17676
17677     case DW_TAG_subprogram:
17678       /* Java constructors will all be named "<init>", so return
17679          the class name when we see this special case.  */
17680       if (cu->language == language_java
17681           && DW_STRING (attr) != NULL
17682           && strcmp (DW_STRING (attr), "<init>") == 0)
17683         {
17684           struct dwarf2_cu *spec_cu = cu;
17685           struct die_info *spec_die;
17686
17687           /* GCJ will output '<init>' for Java constructor names.
17688              For this special case, return the name of the parent class.  */
17689
17690           /* GCJ may output suprogram DIEs with AT_specification set.
17691              If so, use the name of the specified DIE.  */
17692           spec_die = die_specification (die, &spec_cu);
17693           if (spec_die != NULL)
17694             return dwarf2_name (spec_die, spec_cu);
17695
17696           do
17697             {
17698               die = die->parent;
17699               if (die->tag == DW_TAG_class_type)
17700                 return dwarf2_name (die, cu);
17701             }
17702           while (die->tag != DW_TAG_compile_unit
17703                  && die->tag != DW_TAG_partial_unit);
17704         }
17705       break;
17706
17707     case DW_TAG_class_type:
17708     case DW_TAG_interface_type:
17709     case DW_TAG_structure_type:
17710     case DW_TAG_union_type:
17711       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17712          structures or unions.  These were of the form "._%d" in GCC 4.1,
17713          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17714          and GCC 4.4.  We work around this problem by ignoring these.  */
17715       if (attr && DW_STRING (attr)
17716           && (strncmp (DW_STRING (attr), "._", 2) == 0
17717               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17718         return NULL;
17719
17720       /* GCC might emit a nameless typedef that has a linkage name.  See
17721          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17722       if (!attr || DW_STRING (attr) == NULL)
17723         {
17724           char *demangled = NULL;
17725
17726           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17727           if (attr == NULL)
17728             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17729
17730           if (attr == NULL || DW_STRING (attr) == NULL)
17731             return NULL;
17732
17733           /* Avoid demangling DW_STRING (attr) the second time on a second
17734              call for the same DIE.  */
17735           if (!DW_STRING_IS_CANONICAL (attr))
17736             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17737
17738           if (demangled)
17739             {
17740               char *base;
17741
17742               /* FIXME: we already did this for the partial symbol... */
17743               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17744                                                 demangled, strlen (demangled));
17745               DW_STRING_IS_CANONICAL (attr) = 1;
17746               xfree (demangled);
17747
17748               /* Strip any leading namespaces/classes, keep only the base name.
17749                  DW_AT_name for named DIEs does not contain the prefixes.  */
17750               base = strrchr (DW_STRING (attr), ':');
17751               if (base && base > DW_STRING (attr) && base[-1] == ':')
17752                 return &base[1];
17753               else
17754                 return DW_STRING (attr);
17755             }
17756         }
17757       break;
17758
17759     default:
17760       break;
17761     }
17762
17763   if (!DW_STRING_IS_CANONICAL (attr))
17764     {
17765       DW_STRING (attr)
17766         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17767                                     &cu->objfile->objfile_obstack);
17768       DW_STRING_IS_CANONICAL (attr) = 1;
17769     }
17770   return DW_STRING (attr);
17771 }
17772
17773 /* Return the die that this die in an extension of, or NULL if there
17774    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17775    containing the return value on output.  */
17776
17777 static struct die_info *
17778 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17779 {
17780   struct attribute *attr;
17781
17782   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17783   if (attr == NULL)
17784     return NULL;
17785
17786   return follow_die_ref (die, attr, ext_cu);
17787 }
17788
17789 /* Convert a DIE tag into its string name.  */
17790
17791 static const char *
17792 dwarf_tag_name (unsigned tag)
17793 {
17794   const char *name = get_DW_TAG_name (tag);
17795
17796   if (name == NULL)
17797     return "DW_TAG_<unknown>";
17798
17799   return name;
17800 }
17801
17802 /* Convert a DWARF attribute code into its string name.  */
17803
17804 static const char *
17805 dwarf_attr_name (unsigned attr)
17806 {
17807   const char *name;
17808
17809 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17810   if (attr == DW_AT_MIPS_fde)
17811     return "DW_AT_MIPS_fde";
17812 #else
17813   if (attr == DW_AT_HP_block_index)
17814     return "DW_AT_HP_block_index";
17815 #endif
17816
17817   name = get_DW_AT_name (attr);
17818
17819   if (name == NULL)
17820     return "DW_AT_<unknown>";
17821
17822   return name;
17823 }
17824
17825 /* Convert a DWARF value form code into its string name.  */
17826
17827 static const char *
17828 dwarf_form_name (unsigned form)
17829 {
17830   const char *name = get_DW_FORM_name (form);
17831
17832   if (name == NULL)
17833     return "DW_FORM_<unknown>";
17834
17835   return name;
17836 }
17837
17838 static char *
17839 dwarf_bool_name (unsigned mybool)
17840 {
17841   if (mybool)
17842     return "TRUE";
17843   else
17844     return "FALSE";
17845 }
17846
17847 /* Convert a DWARF type code into its string name.  */
17848
17849 static const char *
17850 dwarf_type_encoding_name (unsigned enc)
17851 {
17852   const char *name = get_DW_ATE_name (enc);
17853
17854   if (name == NULL)
17855     return "DW_ATE_<unknown>";
17856
17857   return name;
17858 }
17859
17860 static void
17861 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17862 {
17863   unsigned int i;
17864
17865   print_spaces (indent, f);
17866   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17867            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17868
17869   if (die->parent != NULL)
17870     {
17871       print_spaces (indent, f);
17872       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17873                           die->parent->offset.sect_off);
17874     }
17875
17876   print_spaces (indent, f);
17877   fprintf_unfiltered (f, "  has children: %s\n",
17878            dwarf_bool_name (die->child != NULL));
17879
17880   print_spaces (indent, f);
17881   fprintf_unfiltered (f, "  attributes:\n");
17882
17883   for (i = 0; i < die->num_attrs; ++i)
17884     {
17885       print_spaces (indent, f);
17886       fprintf_unfiltered (f, "    %s (%s) ",
17887                dwarf_attr_name (die->attrs[i].name),
17888                dwarf_form_name (die->attrs[i].form));
17889
17890       switch (die->attrs[i].form)
17891         {
17892         case DW_FORM_addr:
17893         case DW_FORM_GNU_addr_index:
17894           fprintf_unfiltered (f, "address: ");
17895           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17896           break;
17897         case DW_FORM_block2:
17898         case DW_FORM_block4:
17899         case DW_FORM_block:
17900         case DW_FORM_block1:
17901           fprintf_unfiltered (f, "block: size %s",
17902                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17903           break;
17904         case DW_FORM_exprloc:
17905           fprintf_unfiltered (f, "expression: size %s",
17906                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17907           break;
17908         case DW_FORM_ref_addr:
17909           fprintf_unfiltered (f, "ref address: ");
17910           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17911           break;
17912         case DW_FORM_GNU_ref_alt:
17913           fprintf_unfiltered (f, "alt ref address: ");
17914           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17915           break;
17916         case DW_FORM_ref1:
17917         case DW_FORM_ref2:
17918         case DW_FORM_ref4:
17919         case DW_FORM_ref8:
17920         case DW_FORM_ref_udata:
17921           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17922                               (long) (DW_UNSND (&die->attrs[i])));
17923           break;
17924         case DW_FORM_data1:
17925         case DW_FORM_data2:
17926         case DW_FORM_data4:
17927         case DW_FORM_data8:
17928         case DW_FORM_udata:
17929         case DW_FORM_sdata:
17930           fprintf_unfiltered (f, "constant: %s",
17931                               pulongest (DW_UNSND (&die->attrs[i])));
17932           break;
17933         case DW_FORM_sec_offset:
17934           fprintf_unfiltered (f, "section offset: %s",
17935                               pulongest (DW_UNSND (&die->attrs[i])));
17936           break;
17937         case DW_FORM_ref_sig8:
17938           fprintf_unfiltered (f, "signature: %s",
17939                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17940           break;
17941         case DW_FORM_string:
17942         case DW_FORM_strp:
17943         case DW_FORM_GNU_str_index:
17944         case DW_FORM_GNU_strp_alt:
17945           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17946                    DW_STRING (&die->attrs[i])
17947                    ? DW_STRING (&die->attrs[i]) : "",
17948                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17949           break;
17950         case DW_FORM_flag:
17951           if (DW_UNSND (&die->attrs[i]))
17952             fprintf_unfiltered (f, "flag: TRUE");
17953           else
17954             fprintf_unfiltered (f, "flag: FALSE");
17955           break;
17956         case DW_FORM_flag_present:
17957           fprintf_unfiltered (f, "flag: TRUE");
17958           break;
17959         case DW_FORM_indirect:
17960           /* The reader will have reduced the indirect form to
17961              the "base form" so this form should not occur.  */
17962           fprintf_unfiltered (f, 
17963                               "unexpected attribute form: DW_FORM_indirect");
17964           break;
17965         default:
17966           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17967                    die->attrs[i].form);
17968           break;
17969         }
17970       fprintf_unfiltered (f, "\n");
17971     }
17972 }
17973
17974 static void
17975 dump_die_for_error (struct die_info *die)
17976 {
17977   dump_die_shallow (gdb_stderr, 0, die);
17978 }
17979
17980 static void
17981 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17982 {
17983   int indent = level * 4;
17984
17985   gdb_assert (die != NULL);
17986
17987   if (level >= max_level)
17988     return;
17989
17990   dump_die_shallow (f, indent, die);
17991
17992   if (die->child != NULL)
17993     {
17994       print_spaces (indent, f);
17995       fprintf_unfiltered (f, "  Children:");
17996       if (level + 1 < max_level)
17997         {
17998           fprintf_unfiltered (f, "\n");
17999           dump_die_1 (f, level + 1, max_level, die->child);
18000         }
18001       else
18002         {
18003           fprintf_unfiltered (f,
18004                               " [not printed, max nesting level reached]\n");
18005         }
18006     }
18007
18008   if (die->sibling != NULL && level > 0)
18009     {
18010       dump_die_1 (f, level, max_level, die->sibling);
18011     }
18012 }
18013
18014 /* This is called from the pdie macro in gdbinit.in.
18015    It's not static so gcc will keep a copy callable from gdb.  */
18016
18017 void
18018 dump_die (struct die_info *die, int max_level)
18019 {
18020   dump_die_1 (gdb_stdlog, 0, max_level, die);
18021 }
18022
18023 static void
18024 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18025 {
18026   void **slot;
18027
18028   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18029                                    INSERT);
18030
18031   *slot = die;
18032 }
18033
18034 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18035    required kind.  */
18036
18037 static sect_offset
18038 dwarf2_get_ref_die_offset (const struct attribute *attr)
18039 {
18040   sect_offset retval = { DW_UNSND (attr) };
18041
18042   if (attr_form_is_ref (attr))
18043     return retval;
18044
18045   retval.sect_off = 0;
18046   complaint (&symfile_complaints,
18047              _("unsupported die ref attribute form: '%s'"),
18048              dwarf_form_name (attr->form));
18049   return retval;
18050 }
18051
18052 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18053  * the value held by the attribute is not constant.  */
18054
18055 static LONGEST
18056 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18057 {
18058   if (attr->form == DW_FORM_sdata)
18059     return DW_SND (attr);
18060   else if (attr->form == DW_FORM_udata
18061            || attr->form == DW_FORM_data1
18062            || attr->form == DW_FORM_data2
18063            || attr->form == DW_FORM_data4
18064            || attr->form == DW_FORM_data8)
18065     return DW_UNSND (attr);
18066   else
18067     {
18068       complaint (&symfile_complaints,
18069                  _("Attribute value is not a constant (%s)"),
18070                  dwarf_form_name (attr->form));
18071       return default_value;
18072     }
18073 }
18074
18075 /* Follow reference or signature attribute ATTR of SRC_DIE.
18076    On entry *REF_CU is the CU of SRC_DIE.
18077    On exit *REF_CU is the CU of the result.  */
18078
18079 static struct die_info *
18080 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18081                        struct dwarf2_cu **ref_cu)
18082 {
18083   struct die_info *die;
18084
18085   if (attr_form_is_ref (attr))
18086     die = follow_die_ref (src_die, attr, ref_cu);
18087   else if (attr->form == DW_FORM_ref_sig8)
18088     die = follow_die_sig (src_die, attr, ref_cu);
18089   else
18090     {
18091       dump_die_for_error (src_die);
18092       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18093              (*ref_cu)->objfile->name);
18094     }
18095
18096   return die;
18097 }
18098
18099 /* Follow reference OFFSET.
18100    On entry *REF_CU is the CU of the source die referencing OFFSET.
18101    On exit *REF_CU is the CU of the result.
18102    Returns NULL if OFFSET is invalid.  */
18103
18104 static struct die_info *
18105 follow_die_offset (sect_offset offset, int offset_in_dwz,
18106                    struct dwarf2_cu **ref_cu)
18107 {
18108   struct die_info temp_die;
18109   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18110
18111   gdb_assert (cu->per_cu != NULL);
18112
18113   target_cu = cu;
18114
18115   if (cu->per_cu->is_debug_types)
18116     {
18117       /* .debug_types CUs cannot reference anything outside their CU.
18118          If they need to, they have to reference a signatured type via
18119          DW_FORM_ref_sig8.  */
18120       if (! offset_in_cu_p (&cu->header, offset))
18121         return NULL;
18122     }
18123   else if (offset_in_dwz != cu->per_cu->is_dwz
18124            || ! offset_in_cu_p (&cu->header, offset))
18125     {
18126       struct dwarf2_per_cu_data *per_cu;
18127
18128       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18129                                                  cu->objfile);
18130
18131       /* If necessary, add it to the queue and load its DIEs.  */
18132       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18133         load_full_comp_unit (per_cu, cu->language);
18134
18135       target_cu = per_cu->cu;
18136     }
18137   else if (cu->dies == NULL)
18138     {
18139       /* We're loading full DIEs during partial symbol reading.  */
18140       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18141       load_full_comp_unit (cu->per_cu, language_minimal);
18142     }
18143
18144   *ref_cu = target_cu;
18145   temp_die.offset = offset;
18146   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18147 }
18148
18149 /* Follow reference attribute ATTR of SRC_DIE.
18150    On entry *REF_CU is the CU of SRC_DIE.
18151    On exit *REF_CU is the CU of the result.  */
18152
18153 static struct die_info *
18154 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18155                 struct dwarf2_cu **ref_cu)
18156 {
18157   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18158   struct dwarf2_cu *cu = *ref_cu;
18159   struct die_info *die;
18160
18161   die = follow_die_offset (offset,
18162                            (attr->form == DW_FORM_GNU_ref_alt
18163                             || cu->per_cu->is_dwz),
18164                            ref_cu);
18165   if (!die)
18166     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18167            "at 0x%x [in module %s]"),
18168            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
18169
18170   return die;
18171 }
18172
18173 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18174    Returned value is intended for DW_OP_call*.  Returned
18175    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18176
18177 struct dwarf2_locexpr_baton
18178 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18179                                struct dwarf2_per_cu_data *per_cu,
18180                                CORE_ADDR (*get_frame_pc) (void *baton),
18181                                void *baton)
18182 {
18183   struct dwarf2_cu *cu;
18184   struct die_info *die;
18185   struct attribute *attr;
18186   struct dwarf2_locexpr_baton retval;
18187
18188   dw2_setup (per_cu->objfile);
18189
18190   if (per_cu->cu == NULL)
18191     load_cu (per_cu);
18192   cu = per_cu->cu;
18193
18194   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18195   if (!die)
18196     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18197            offset.sect_off, per_cu->objfile->name);
18198
18199   attr = dwarf2_attr (die, DW_AT_location, cu);
18200   if (!attr)
18201     {
18202       /* DWARF: "If there is no such attribute, then there is no effect.".
18203          DATA is ignored if SIZE is 0.  */
18204
18205       retval.data = NULL;
18206       retval.size = 0;
18207     }
18208   else if (attr_form_is_section_offset (attr))
18209     {
18210       struct dwarf2_loclist_baton loclist_baton;
18211       CORE_ADDR pc = (*get_frame_pc) (baton);
18212       size_t size;
18213
18214       fill_in_loclist_baton (cu, &loclist_baton, attr);
18215
18216       retval.data = dwarf2_find_location_expression (&loclist_baton,
18217                                                      &size, pc);
18218       retval.size = size;
18219     }
18220   else
18221     {
18222       if (!attr_form_is_block (attr))
18223         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18224                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18225                offset.sect_off, per_cu->objfile->name);
18226
18227       retval.data = DW_BLOCK (attr)->data;
18228       retval.size = DW_BLOCK (attr)->size;
18229     }
18230   retval.per_cu = cu->per_cu;
18231
18232   age_cached_comp_units ();
18233
18234   return retval;
18235 }
18236
18237 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18238    offset.  */
18239
18240 struct dwarf2_locexpr_baton
18241 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18242                              struct dwarf2_per_cu_data *per_cu,
18243                              CORE_ADDR (*get_frame_pc) (void *baton),
18244                              void *baton)
18245 {
18246   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18247
18248   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18249 }
18250
18251 /* Write a constant of a given type as target-ordered bytes into
18252    OBSTACK.  */
18253
18254 static const gdb_byte *
18255 write_constant_as_bytes (struct obstack *obstack,
18256                          enum bfd_endian byte_order,
18257                          struct type *type,
18258                          ULONGEST value,
18259                          LONGEST *len)
18260 {
18261   gdb_byte *result;
18262
18263   *len = TYPE_LENGTH (type);
18264   result = obstack_alloc (obstack, *len);
18265   store_unsigned_integer (result, *len, byte_order, value);
18266
18267   return result;
18268 }
18269
18270 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18271    pointer to the constant bytes and set LEN to the length of the
18272    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18273    does not have a DW_AT_const_value, return NULL.  */
18274
18275 const gdb_byte *
18276 dwarf2_fetch_constant_bytes (sect_offset offset,
18277                              struct dwarf2_per_cu_data *per_cu,
18278                              struct obstack *obstack,
18279                              LONGEST *len)
18280 {
18281   struct dwarf2_cu *cu;
18282   struct die_info *die;
18283   struct attribute *attr;
18284   const gdb_byte *result = NULL;
18285   struct type *type;
18286   LONGEST value;
18287   enum bfd_endian byte_order;
18288
18289   dw2_setup (per_cu->objfile);
18290
18291   if (per_cu->cu == NULL)
18292     load_cu (per_cu);
18293   cu = per_cu->cu;
18294
18295   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18296   if (!die)
18297     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18298            offset.sect_off, per_cu->objfile->name);
18299
18300
18301   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18302   if (attr == NULL)
18303     return NULL;
18304
18305   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18306                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18307
18308   switch (attr->form)
18309     {
18310     case DW_FORM_addr:
18311     case DW_FORM_GNU_addr_index:
18312       {
18313         gdb_byte *tem;
18314
18315         *len = cu->header.addr_size;
18316         tem = obstack_alloc (obstack, *len);
18317         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18318         result = tem;
18319       }
18320       break;
18321     case DW_FORM_string:
18322     case DW_FORM_strp:
18323     case DW_FORM_GNU_str_index:
18324     case DW_FORM_GNU_strp_alt:
18325       /* DW_STRING is already allocated on the objfile obstack, point
18326          directly to it.  */
18327       result = (const gdb_byte *) DW_STRING (attr);
18328       *len = strlen (DW_STRING (attr));
18329       break;
18330     case DW_FORM_block1:
18331     case DW_FORM_block2:
18332     case DW_FORM_block4:
18333     case DW_FORM_block:
18334     case DW_FORM_exprloc:
18335       result = DW_BLOCK (attr)->data;
18336       *len = DW_BLOCK (attr)->size;
18337       break;
18338
18339       /* The DW_AT_const_value attributes are supposed to carry the
18340          symbol's value "represented as it would be on the target
18341          architecture."  By the time we get here, it's already been
18342          converted to host endianness, so we just need to sign- or
18343          zero-extend it as appropriate.  */
18344     case DW_FORM_data1:
18345       type = die_type (die, cu);
18346       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18347       if (result == NULL)
18348         result = write_constant_as_bytes (obstack, byte_order,
18349                                           type, value, len);
18350       break;
18351     case DW_FORM_data2:
18352       type = die_type (die, cu);
18353       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18354       if (result == NULL)
18355         result = write_constant_as_bytes (obstack, byte_order,
18356                                           type, value, len);
18357       break;
18358     case DW_FORM_data4:
18359       type = die_type (die, cu);
18360       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18361       if (result == NULL)
18362         result = write_constant_as_bytes (obstack, byte_order,
18363                                           type, value, len);
18364       break;
18365     case DW_FORM_data8:
18366       type = die_type (die, cu);
18367       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18368       if (result == NULL)
18369         result = write_constant_as_bytes (obstack, byte_order,
18370                                           type, value, len);
18371       break;
18372
18373     case DW_FORM_sdata:
18374       type = die_type (die, cu);
18375       result = write_constant_as_bytes (obstack, byte_order,
18376                                         type, DW_SND (attr), len);
18377       break;
18378
18379     case DW_FORM_udata:
18380       type = die_type (die, cu);
18381       result = write_constant_as_bytes (obstack, byte_order,
18382                                         type, DW_UNSND (attr), len);
18383       break;
18384
18385     default:
18386       complaint (&symfile_complaints,
18387                  _("unsupported const value attribute form: '%s'"),
18388                  dwarf_form_name (attr->form));
18389       break;
18390     }
18391
18392   return result;
18393 }
18394
18395 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18396    PER_CU.  */
18397
18398 struct type *
18399 dwarf2_get_die_type (cu_offset die_offset,
18400                      struct dwarf2_per_cu_data *per_cu)
18401 {
18402   sect_offset die_offset_sect;
18403
18404   dw2_setup (per_cu->objfile);
18405
18406   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18407   return get_die_type_at_offset (die_offset_sect, per_cu);
18408 }
18409
18410 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18411    On entry *REF_CU is the CU of SRC_DIE.
18412    On exit *REF_CU is the CU of the result.
18413    Returns NULL if the referenced DIE isn't found.  */
18414
18415 static struct die_info *
18416 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18417                   struct dwarf2_cu **ref_cu)
18418 {
18419   struct objfile *objfile = (*ref_cu)->objfile;
18420   struct die_info temp_die;
18421   struct dwarf2_cu *sig_cu;
18422   struct die_info *die;
18423
18424   /* While it might be nice to assert sig_type->type == NULL here,
18425      we can get here for DW_AT_imported_declaration where we need
18426      the DIE not the type.  */
18427
18428   /* If necessary, add it to the queue and load its DIEs.  */
18429
18430   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18431     read_signatured_type (sig_type);
18432
18433   sig_cu = sig_type->per_cu.cu;
18434   gdb_assert (sig_cu != NULL);
18435   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18436   temp_die.offset = sig_type->type_offset_in_section;
18437   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18438                              temp_die.offset.sect_off);
18439   if (die)
18440     {
18441       /* For .gdb_index version 7 keep track of included TUs.
18442          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18443       if (dwarf2_per_objfile->index_table != NULL
18444           && dwarf2_per_objfile->index_table->version <= 7)
18445         {
18446           VEC_safe_push (dwarf2_per_cu_ptr,
18447                          (*ref_cu)->per_cu->imported_symtabs,
18448                          sig_cu->per_cu);
18449         }
18450
18451       *ref_cu = sig_cu;
18452       return die;
18453     }
18454
18455   return NULL;
18456 }
18457
18458 /* Follow signatured type referenced by ATTR in SRC_DIE.
18459    On entry *REF_CU is the CU of SRC_DIE.
18460    On exit *REF_CU is the CU of the result.
18461    The result is the DIE of the type.
18462    If the referenced type cannot be found an error is thrown.  */
18463
18464 static struct die_info *
18465 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
18466                 struct dwarf2_cu **ref_cu)
18467 {
18468   ULONGEST signature = DW_SIGNATURE (attr);
18469   struct signatured_type *sig_type;
18470   struct die_info *die;
18471
18472   gdb_assert (attr->form == DW_FORM_ref_sig8);
18473
18474   sig_type = lookup_signatured_type (*ref_cu, signature);
18475   /* sig_type will be NULL if the signatured type is missing from
18476      the debug info.  */
18477   if (sig_type == NULL)
18478     {
18479       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18480                " from DIE at 0x%x [in module %s]"),
18481              hex_string (signature), src_die->offset.sect_off,
18482              (*ref_cu)->objfile->name);
18483     }
18484
18485   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18486   if (die == NULL)
18487     {
18488       dump_die_for_error (src_die);
18489       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18490                " from DIE at 0x%x [in module %s]"),
18491              hex_string (signature), src_die->offset.sect_off,
18492              (*ref_cu)->objfile->name);
18493     }
18494
18495   return die;
18496 }
18497
18498 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18499    reading in and processing the type unit if necessary.  */
18500
18501 static struct type *
18502 get_signatured_type (struct die_info *die, ULONGEST signature,
18503                      struct dwarf2_cu *cu)
18504 {
18505   struct signatured_type *sig_type;
18506   struct dwarf2_cu *type_cu;
18507   struct die_info *type_die;
18508   struct type *type;
18509
18510   sig_type = lookup_signatured_type (cu, signature);
18511   /* sig_type will be NULL if the signatured type is missing from
18512      the debug info.  */
18513   if (sig_type == NULL)
18514     {
18515       complaint (&symfile_complaints,
18516                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18517                    " from DIE at 0x%x [in module %s]"),
18518                  hex_string (signature), die->offset.sect_off,
18519                  dwarf2_per_objfile->objfile->name);
18520       return build_error_marker_type (cu, die);
18521     }
18522
18523   /* If we already know the type we're done.  */
18524   if (sig_type->type != NULL)
18525     return sig_type->type;
18526
18527   type_cu = cu;
18528   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18529   if (type_die != NULL)
18530     {
18531       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18532          is created.  This is important, for example, because for c++ classes
18533          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18534       type = read_type_die (type_die, type_cu);
18535       if (type == NULL)
18536         {
18537           complaint (&symfile_complaints,
18538                      _("Dwarf Error: Cannot build signatured type %s"
18539                        " referenced from DIE at 0x%x [in module %s]"),
18540                      hex_string (signature), die->offset.sect_off,
18541                      dwarf2_per_objfile->objfile->name);
18542           type = build_error_marker_type (cu, die);
18543         }
18544     }
18545   else
18546     {
18547       complaint (&symfile_complaints,
18548                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18549                    " from DIE at 0x%x [in module %s]"),
18550                  hex_string (signature), die->offset.sect_off,
18551                  dwarf2_per_objfile->objfile->name);
18552       type = build_error_marker_type (cu, die);
18553     }
18554   sig_type->type = type;
18555
18556   return type;
18557 }
18558
18559 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18560    reading in and processing the type unit if necessary.  */
18561
18562 static struct type *
18563 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
18564                           struct dwarf2_cu *cu) /* ARI: editCase function */
18565 {
18566   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18567   if (attr_form_is_ref (attr))
18568     {
18569       struct dwarf2_cu *type_cu = cu;
18570       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18571
18572       return read_type_die (type_die, type_cu);
18573     }
18574   else if (attr->form == DW_FORM_ref_sig8)
18575     {
18576       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18577     }
18578   else
18579     {
18580       complaint (&symfile_complaints,
18581                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18582                    " at 0x%x [in module %s]"),
18583                  dwarf_form_name (attr->form), die->offset.sect_off,
18584                  dwarf2_per_objfile->objfile->name);
18585       return build_error_marker_type (cu, die);
18586     }
18587 }
18588
18589 /* Load the DIEs associated with type unit PER_CU into memory.  */
18590
18591 static void
18592 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18593 {
18594   struct signatured_type *sig_type;
18595
18596   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18597   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18598
18599   /* We have the per_cu, but we need the signatured_type.
18600      Fortunately this is an easy translation.  */
18601   gdb_assert (per_cu->is_debug_types);
18602   sig_type = (struct signatured_type *) per_cu;
18603
18604   gdb_assert (per_cu->cu == NULL);
18605
18606   read_signatured_type (sig_type);
18607
18608   gdb_assert (per_cu->cu != NULL);
18609 }
18610
18611 /* die_reader_func for read_signatured_type.
18612    This is identical to load_full_comp_unit_reader,
18613    but is kept separate for now.  */
18614
18615 static void
18616 read_signatured_type_reader (const struct die_reader_specs *reader,
18617                              const gdb_byte *info_ptr,
18618                              struct die_info *comp_unit_die,
18619                              int has_children,
18620                              void *data)
18621 {
18622   struct dwarf2_cu *cu = reader->cu;
18623
18624   gdb_assert (cu->die_hash == NULL);
18625   cu->die_hash =
18626     htab_create_alloc_ex (cu->header.length / 12,
18627                           die_hash,
18628                           die_eq,
18629                           NULL,
18630                           &cu->comp_unit_obstack,
18631                           hashtab_obstack_allocate,
18632                           dummy_obstack_deallocate);
18633
18634   if (has_children)
18635     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18636                                                   &info_ptr, comp_unit_die);
18637   cu->dies = comp_unit_die;
18638   /* comp_unit_die is not stored in die_hash, no need.  */
18639
18640   /* We try not to read any attributes in this function, because not
18641      all CUs needed for references have been loaded yet, and symbol
18642      table processing isn't initialized.  But we have to set the CU language,
18643      or we won't be able to build types correctly.
18644      Similarly, if we do not read the producer, we can not apply
18645      producer-specific interpretation.  */
18646   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18647 }
18648
18649 /* Read in a signatured type and build its CU and DIEs.
18650    If the type is a stub for the real type in a DWO file,
18651    read in the real type from the DWO file as well.  */
18652
18653 static void
18654 read_signatured_type (struct signatured_type *sig_type)
18655 {
18656   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18657
18658   gdb_assert (per_cu->is_debug_types);
18659   gdb_assert (per_cu->cu == NULL);
18660
18661   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18662                            read_signatured_type_reader, NULL);
18663   sig_type->per_cu.tu_read = 1;
18664 }
18665
18666 /* Decode simple location descriptions.
18667    Given a pointer to a dwarf block that defines a location, compute
18668    the location and return the value.
18669
18670    NOTE drow/2003-11-18: This function is called in two situations
18671    now: for the address of static or global variables (partial symbols
18672    only) and for offsets into structures which are expected to be
18673    (more or less) constant.  The partial symbol case should go away,
18674    and only the constant case should remain.  That will let this
18675    function complain more accurately.  A few special modes are allowed
18676    without complaint for global variables (for instance, global
18677    register values and thread-local values).
18678
18679    A location description containing no operations indicates that the
18680    object is optimized out.  The return value is 0 for that case.
18681    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18682    callers will only want a very basic result and this can become a
18683    complaint.
18684
18685    Note that stack[0] is unused except as a default error return.  */
18686
18687 static CORE_ADDR
18688 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18689 {
18690   struct objfile *objfile = cu->objfile;
18691   size_t i;
18692   size_t size = blk->size;
18693   const gdb_byte *data = blk->data;
18694   CORE_ADDR stack[64];
18695   int stacki;
18696   unsigned int bytes_read, unsnd;
18697   gdb_byte op;
18698
18699   i = 0;
18700   stacki = 0;
18701   stack[stacki] = 0;
18702   stack[++stacki] = 0;
18703
18704   while (i < size)
18705     {
18706       op = data[i++];
18707       switch (op)
18708         {
18709         case DW_OP_lit0:
18710         case DW_OP_lit1:
18711         case DW_OP_lit2:
18712         case DW_OP_lit3:
18713         case DW_OP_lit4:
18714         case DW_OP_lit5:
18715         case DW_OP_lit6:
18716         case DW_OP_lit7:
18717         case DW_OP_lit8:
18718         case DW_OP_lit9:
18719         case DW_OP_lit10:
18720         case DW_OP_lit11:
18721         case DW_OP_lit12:
18722         case DW_OP_lit13:
18723         case DW_OP_lit14:
18724         case DW_OP_lit15:
18725         case DW_OP_lit16:
18726         case DW_OP_lit17:
18727         case DW_OP_lit18:
18728         case DW_OP_lit19:
18729         case DW_OP_lit20:
18730         case DW_OP_lit21:
18731         case DW_OP_lit22:
18732         case DW_OP_lit23:
18733         case DW_OP_lit24:
18734         case DW_OP_lit25:
18735         case DW_OP_lit26:
18736         case DW_OP_lit27:
18737         case DW_OP_lit28:
18738         case DW_OP_lit29:
18739         case DW_OP_lit30:
18740         case DW_OP_lit31:
18741           stack[++stacki] = op - DW_OP_lit0;
18742           break;
18743
18744         case DW_OP_reg0:
18745         case DW_OP_reg1:
18746         case DW_OP_reg2:
18747         case DW_OP_reg3:
18748         case DW_OP_reg4:
18749         case DW_OP_reg5:
18750         case DW_OP_reg6:
18751         case DW_OP_reg7:
18752         case DW_OP_reg8:
18753         case DW_OP_reg9:
18754         case DW_OP_reg10:
18755         case DW_OP_reg11:
18756         case DW_OP_reg12:
18757         case DW_OP_reg13:
18758         case DW_OP_reg14:
18759         case DW_OP_reg15:
18760         case DW_OP_reg16:
18761         case DW_OP_reg17:
18762         case DW_OP_reg18:
18763         case DW_OP_reg19:
18764         case DW_OP_reg20:
18765         case DW_OP_reg21:
18766         case DW_OP_reg22:
18767         case DW_OP_reg23:
18768         case DW_OP_reg24:
18769         case DW_OP_reg25:
18770         case DW_OP_reg26:
18771         case DW_OP_reg27:
18772         case DW_OP_reg28:
18773         case DW_OP_reg29:
18774         case DW_OP_reg30:
18775         case DW_OP_reg31:
18776           stack[++stacki] = op - DW_OP_reg0;
18777           if (i < size)
18778             dwarf2_complex_location_expr_complaint ();
18779           break;
18780
18781         case DW_OP_regx:
18782           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18783           i += bytes_read;
18784           stack[++stacki] = unsnd;
18785           if (i < size)
18786             dwarf2_complex_location_expr_complaint ();
18787           break;
18788
18789         case DW_OP_addr:
18790           stack[++stacki] = read_address (objfile->obfd, &data[i],
18791                                           cu, &bytes_read);
18792           i += bytes_read;
18793           break;
18794
18795         case DW_OP_const1u:
18796           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18797           i += 1;
18798           break;
18799
18800         case DW_OP_const1s:
18801           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18802           i += 1;
18803           break;
18804
18805         case DW_OP_const2u:
18806           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18807           i += 2;
18808           break;
18809
18810         case DW_OP_const2s:
18811           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18812           i += 2;
18813           break;
18814
18815         case DW_OP_const4u:
18816           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18817           i += 4;
18818           break;
18819
18820         case DW_OP_const4s:
18821           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18822           i += 4;
18823           break;
18824
18825         case DW_OP_const8u:
18826           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18827           i += 8;
18828           break;
18829
18830         case DW_OP_constu:
18831           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18832                                                   &bytes_read);
18833           i += bytes_read;
18834           break;
18835
18836         case DW_OP_consts:
18837           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18838           i += bytes_read;
18839           break;
18840
18841         case DW_OP_dup:
18842           stack[stacki + 1] = stack[stacki];
18843           stacki++;
18844           break;
18845
18846         case DW_OP_plus:
18847           stack[stacki - 1] += stack[stacki];
18848           stacki--;
18849           break;
18850
18851         case DW_OP_plus_uconst:
18852           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18853                                                  &bytes_read);
18854           i += bytes_read;
18855           break;
18856
18857         case DW_OP_minus:
18858           stack[stacki - 1] -= stack[stacki];
18859           stacki--;
18860           break;
18861
18862         case DW_OP_deref:
18863           /* If we're not the last op, then we definitely can't encode
18864              this using GDB's address_class enum.  This is valid for partial
18865              global symbols, although the variable's address will be bogus
18866              in the psymtab.  */
18867           if (i < size)
18868             dwarf2_complex_location_expr_complaint ();
18869           break;
18870
18871         case DW_OP_GNU_push_tls_address:
18872           /* The top of the stack has the offset from the beginning
18873              of the thread control block at which the variable is located.  */
18874           /* Nothing should follow this operator, so the top of stack would
18875              be returned.  */
18876           /* This is valid for partial global symbols, but the variable's
18877              address will be bogus in the psymtab.  Make it always at least
18878              non-zero to not look as a variable garbage collected by linker
18879              which have DW_OP_addr 0.  */
18880           if (i < size)
18881             dwarf2_complex_location_expr_complaint ();
18882           stack[stacki]++;
18883           break;
18884
18885         case DW_OP_GNU_uninit:
18886           break;
18887
18888         case DW_OP_GNU_addr_index:
18889         case DW_OP_GNU_const_index:
18890           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18891                                                          &bytes_read);
18892           i += bytes_read;
18893           break;
18894
18895         default:
18896           {
18897             const char *name = get_DW_OP_name (op);
18898
18899             if (name)
18900               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18901                          name);
18902             else
18903               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18904                          op);
18905           }
18906
18907           return (stack[stacki]);
18908         }
18909
18910       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18911          outside of the allocated space.  Also enforce minimum>0.  */
18912       if (stacki >= ARRAY_SIZE (stack) - 1)
18913         {
18914           complaint (&symfile_complaints,
18915                      _("location description stack overflow"));
18916           return 0;
18917         }
18918
18919       if (stacki <= 0)
18920         {
18921           complaint (&symfile_complaints,
18922                      _("location description stack underflow"));
18923           return 0;
18924         }
18925     }
18926   return (stack[stacki]);
18927 }
18928
18929 /* memory allocation interface */
18930
18931 static struct dwarf_block *
18932 dwarf_alloc_block (struct dwarf2_cu *cu)
18933 {
18934   struct dwarf_block *blk;
18935
18936   blk = (struct dwarf_block *)
18937     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18938   return (blk);
18939 }
18940
18941 static struct die_info *
18942 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18943 {
18944   struct die_info *die;
18945   size_t size = sizeof (struct die_info);
18946
18947   if (num_attrs > 1)
18948     size += (num_attrs - 1) * sizeof (struct attribute);
18949
18950   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18951   memset (die, 0, sizeof (struct die_info));
18952   return (die);
18953 }
18954
18955 \f
18956 /* Macro support.  */
18957
18958 /* Return file name relative to the compilation directory of file number I in
18959    *LH's file name table.  The result is allocated using xmalloc; the caller is
18960    responsible for freeing it.  */
18961
18962 static char *
18963 file_file_name (int file, struct line_header *lh)
18964 {
18965   /* Is the file number a valid index into the line header's file name
18966      table?  Remember that file numbers start with one, not zero.  */
18967   if (1 <= file && file <= lh->num_file_names)
18968     {
18969       struct file_entry *fe = &lh->file_names[file - 1];
18970
18971       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18972         return xstrdup (fe->name);
18973       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18974                      fe->name, NULL);
18975     }
18976   else
18977     {
18978       /* The compiler produced a bogus file number.  We can at least
18979          record the macro definitions made in the file, even if we
18980          won't be able to find the file by name.  */
18981       char fake_name[80];
18982
18983       xsnprintf (fake_name, sizeof (fake_name),
18984                  "<bad macro file number %d>", file);
18985
18986       complaint (&symfile_complaints,
18987                  _("bad file number in macro information (%d)"),
18988                  file);
18989
18990       return xstrdup (fake_name);
18991     }
18992 }
18993
18994 /* Return the full name of file number I in *LH's file name table.
18995    Use COMP_DIR as the name of the current directory of the
18996    compilation.  The result is allocated using xmalloc; the caller is
18997    responsible for freeing it.  */
18998 static char *
18999 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19000 {
19001   /* Is the file number a valid index into the line header's file name
19002      table?  Remember that file numbers start with one, not zero.  */
19003   if (1 <= file && file <= lh->num_file_names)
19004     {
19005       char *relative = file_file_name (file, lh);
19006
19007       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19008         return relative;
19009       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19010     }
19011   else
19012     return file_file_name (file, lh);
19013 }
19014
19015
19016 static struct macro_source_file *
19017 macro_start_file (int file, int line,
19018                   struct macro_source_file *current_file,
19019                   const char *comp_dir,
19020                   struct line_header *lh, struct objfile *objfile)
19021 {
19022   /* File name relative to the compilation directory of this source file.  */
19023   char *file_name = file_file_name (file, lh);
19024
19025   if (! current_file)
19026     {
19027       /* Note: We don't create a macro table for this compilation unit
19028          at all until we actually get a filename.  */
19029       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19030
19031       /* If we have no current file, then this must be the start_file
19032          directive for the compilation unit's main source file.  */
19033       current_file = macro_set_main (macro_table, file_name);
19034       macro_define_special (macro_table);
19035     }
19036   else
19037     current_file = macro_include (current_file, line, file_name);
19038
19039   xfree (file_name);
19040
19041   return current_file;
19042 }
19043
19044
19045 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19046    followed by a null byte.  */
19047 static char *
19048 copy_string (const char *buf, int len)
19049 {
19050   char *s = xmalloc (len + 1);
19051
19052   memcpy (s, buf, len);
19053   s[len] = '\0';
19054   return s;
19055 }
19056
19057
19058 static const char *
19059 consume_improper_spaces (const char *p, const char *body)
19060 {
19061   if (*p == ' ')
19062     {
19063       complaint (&symfile_complaints,
19064                  _("macro definition contains spaces "
19065                    "in formal argument list:\n`%s'"),
19066                  body);
19067
19068       while (*p == ' ')
19069         p++;
19070     }
19071
19072   return p;
19073 }
19074
19075
19076 static void
19077 parse_macro_definition (struct macro_source_file *file, int line,
19078                         const char *body)
19079 {
19080   const char *p;
19081
19082   /* The body string takes one of two forms.  For object-like macro
19083      definitions, it should be:
19084
19085         <macro name> " " <definition>
19086
19087      For function-like macro definitions, it should be:
19088
19089         <macro name> "() " <definition>
19090      or
19091         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19092
19093      Spaces may appear only where explicitly indicated, and in the
19094      <definition>.
19095
19096      The Dwarf 2 spec says that an object-like macro's name is always
19097      followed by a space, but versions of GCC around March 2002 omit
19098      the space when the macro's definition is the empty string.
19099
19100      The Dwarf 2 spec says that there should be no spaces between the
19101      formal arguments in a function-like macro's formal argument list,
19102      but versions of GCC around March 2002 include spaces after the
19103      commas.  */
19104
19105
19106   /* Find the extent of the macro name.  The macro name is terminated
19107      by either a space or null character (for an object-like macro) or
19108      an opening paren (for a function-like macro).  */
19109   for (p = body; *p; p++)
19110     if (*p == ' ' || *p == '(')
19111       break;
19112
19113   if (*p == ' ' || *p == '\0')
19114     {
19115       /* It's an object-like macro.  */
19116       int name_len = p - body;
19117       char *name = copy_string (body, name_len);
19118       const char *replacement;
19119
19120       if (*p == ' ')
19121         replacement = body + name_len + 1;
19122       else
19123         {
19124           dwarf2_macro_malformed_definition_complaint (body);
19125           replacement = body + name_len;
19126         }
19127
19128       macro_define_object (file, line, name, replacement);
19129
19130       xfree (name);
19131     }
19132   else if (*p == '(')
19133     {
19134       /* It's a function-like macro.  */
19135       char *name = copy_string (body, p - body);
19136       int argc = 0;
19137       int argv_size = 1;
19138       char **argv = xmalloc (argv_size * sizeof (*argv));
19139
19140       p++;
19141
19142       p = consume_improper_spaces (p, body);
19143
19144       /* Parse the formal argument list.  */
19145       while (*p && *p != ')')
19146         {
19147           /* Find the extent of the current argument name.  */
19148           const char *arg_start = p;
19149
19150           while (*p && *p != ',' && *p != ')' && *p != ' ')
19151             p++;
19152
19153           if (! *p || p == arg_start)
19154             dwarf2_macro_malformed_definition_complaint (body);
19155           else
19156             {
19157               /* Make sure argv has room for the new argument.  */
19158               if (argc >= argv_size)
19159                 {
19160                   argv_size *= 2;
19161                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19162                 }
19163
19164               argv[argc++] = copy_string (arg_start, p - arg_start);
19165             }
19166
19167           p = consume_improper_spaces (p, body);
19168
19169           /* Consume the comma, if present.  */
19170           if (*p == ',')
19171             {
19172               p++;
19173
19174               p = consume_improper_spaces (p, body);
19175             }
19176         }
19177
19178       if (*p == ')')
19179         {
19180           p++;
19181
19182           if (*p == ' ')
19183             /* Perfectly formed definition, no complaints.  */
19184             macro_define_function (file, line, name,
19185                                    argc, (const char **) argv,
19186                                    p + 1);
19187           else if (*p == '\0')
19188             {
19189               /* Complain, but do define it.  */
19190               dwarf2_macro_malformed_definition_complaint (body);
19191               macro_define_function (file, line, name,
19192                                      argc, (const char **) argv,
19193                                      p);
19194             }
19195           else
19196             /* Just complain.  */
19197             dwarf2_macro_malformed_definition_complaint (body);
19198         }
19199       else
19200         /* Just complain.  */
19201         dwarf2_macro_malformed_definition_complaint (body);
19202
19203       xfree (name);
19204       {
19205         int i;
19206
19207         for (i = 0; i < argc; i++)
19208           xfree (argv[i]);
19209       }
19210       xfree (argv);
19211     }
19212   else
19213     dwarf2_macro_malformed_definition_complaint (body);
19214 }
19215
19216 /* Skip some bytes from BYTES according to the form given in FORM.
19217    Returns the new pointer.  */
19218
19219 static const gdb_byte *
19220 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19221                  enum dwarf_form form,
19222                  unsigned int offset_size,
19223                  struct dwarf2_section_info *section)
19224 {
19225   unsigned int bytes_read;
19226
19227   switch (form)
19228     {
19229     case DW_FORM_data1:
19230     case DW_FORM_flag:
19231       ++bytes;
19232       break;
19233
19234     case DW_FORM_data2:
19235       bytes += 2;
19236       break;
19237
19238     case DW_FORM_data4:
19239       bytes += 4;
19240       break;
19241
19242     case DW_FORM_data8:
19243       bytes += 8;
19244       break;
19245
19246     case DW_FORM_string:
19247       read_direct_string (abfd, bytes, &bytes_read);
19248       bytes += bytes_read;
19249       break;
19250
19251     case DW_FORM_sec_offset:
19252     case DW_FORM_strp:
19253     case DW_FORM_GNU_strp_alt:
19254       bytes += offset_size;
19255       break;
19256
19257     case DW_FORM_block:
19258       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19259       bytes += bytes_read;
19260       break;
19261
19262     case DW_FORM_block1:
19263       bytes += 1 + read_1_byte (abfd, bytes);
19264       break;
19265     case DW_FORM_block2:
19266       bytes += 2 + read_2_bytes (abfd, bytes);
19267       break;
19268     case DW_FORM_block4:
19269       bytes += 4 + read_4_bytes (abfd, bytes);
19270       break;
19271
19272     case DW_FORM_sdata:
19273     case DW_FORM_udata:
19274     case DW_FORM_GNU_addr_index:
19275     case DW_FORM_GNU_str_index:
19276       bytes = gdb_skip_leb128 (bytes, buffer_end);
19277       if (bytes == NULL)
19278         {
19279           dwarf2_section_buffer_overflow_complaint (section);
19280           return NULL;
19281         }
19282       break;
19283
19284     default:
19285       {
19286       complain:
19287         complaint (&symfile_complaints,
19288                    _("invalid form 0x%x in `%s'"),
19289                    form,
19290                    section->asection->name);
19291         return NULL;
19292       }
19293     }
19294
19295   return bytes;
19296 }
19297
19298 /* A helper for dwarf_decode_macros that handles skipping an unknown
19299    opcode.  Returns an updated pointer to the macro data buffer; or,
19300    on error, issues a complaint and returns NULL.  */
19301
19302 static const gdb_byte *
19303 skip_unknown_opcode (unsigned int opcode,
19304                      const gdb_byte **opcode_definitions,
19305                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19306                      bfd *abfd,
19307                      unsigned int offset_size,
19308                      struct dwarf2_section_info *section)
19309 {
19310   unsigned int bytes_read, i;
19311   unsigned long arg;
19312   const gdb_byte *defn;
19313
19314   if (opcode_definitions[opcode] == NULL)
19315     {
19316       complaint (&symfile_complaints,
19317                  _("unrecognized DW_MACFINO opcode 0x%x"),
19318                  opcode);
19319       return NULL;
19320     }
19321
19322   defn = opcode_definitions[opcode];
19323   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19324   defn += bytes_read;
19325
19326   for (i = 0; i < arg; ++i)
19327     {
19328       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19329                                  section);
19330       if (mac_ptr == NULL)
19331         {
19332           /* skip_form_bytes already issued the complaint.  */
19333           return NULL;
19334         }
19335     }
19336
19337   return mac_ptr;
19338 }
19339
19340 /* A helper function which parses the header of a macro section.
19341    If the macro section is the extended (for now called "GNU") type,
19342    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19343    the header, or issues a complaint and returns NULL on error.  */
19344
19345 static const gdb_byte *
19346 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19347                           bfd *abfd,
19348                           const gdb_byte *mac_ptr,
19349                           unsigned int *offset_size,
19350                           int section_is_gnu)
19351 {
19352   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19353
19354   if (section_is_gnu)
19355     {
19356       unsigned int version, flags;
19357
19358       version = read_2_bytes (abfd, mac_ptr);
19359       if (version != 4)
19360         {
19361           complaint (&symfile_complaints,
19362                      _("unrecognized version `%d' in .debug_macro section"),
19363                      version);
19364           return NULL;
19365         }
19366       mac_ptr += 2;
19367
19368       flags = read_1_byte (abfd, mac_ptr);
19369       ++mac_ptr;
19370       *offset_size = (flags & 1) ? 8 : 4;
19371
19372       if ((flags & 2) != 0)
19373         /* We don't need the line table offset.  */
19374         mac_ptr += *offset_size;
19375
19376       /* Vendor opcode descriptions.  */
19377       if ((flags & 4) != 0)
19378         {
19379           unsigned int i, count;
19380
19381           count = read_1_byte (abfd, mac_ptr);
19382           ++mac_ptr;
19383           for (i = 0; i < count; ++i)
19384             {
19385               unsigned int opcode, bytes_read;
19386               unsigned long arg;
19387
19388               opcode = read_1_byte (abfd, mac_ptr);
19389               ++mac_ptr;
19390               opcode_definitions[opcode] = mac_ptr;
19391               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19392               mac_ptr += bytes_read;
19393               mac_ptr += arg;
19394             }
19395         }
19396     }
19397
19398   return mac_ptr;
19399 }
19400
19401 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19402    including DW_MACRO_GNU_transparent_include.  */
19403
19404 static void
19405 dwarf_decode_macro_bytes (bfd *abfd,
19406                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19407                           struct macro_source_file *current_file,
19408                           struct line_header *lh, const char *comp_dir,
19409                           struct dwarf2_section_info *section,
19410                           int section_is_gnu, int section_is_dwz,
19411                           unsigned int offset_size,
19412                           struct objfile *objfile,
19413                           htab_t include_hash)
19414 {
19415   enum dwarf_macro_record_type macinfo_type;
19416   int at_commandline;
19417   const gdb_byte *opcode_definitions[256];
19418
19419   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19420                                       &offset_size, section_is_gnu);
19421   if (mac_ptr == NULL)
19422     {
19423       /* We already issued a complaint.  */
19424       return;
19425     }
19426
19427   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19428      GDB is still reading the definitions from command line.  First
19429      DW_MACINFO_start_file will need to be ignored as it was already executed
19430      to create CURRENT_FILE for the main source holding also the command line
19431      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19432      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19433
19434   at_commandline = 1;
19435
19436   do
19437     {
19438       /* Do we at least have room for a macinfo type byte?  */
19439       if (mac_ptr >= mac_end)
19440         {
19441           dwarf2_section_buffer_overflow_complaint (section);
19442           break;
19443         }
19444
19445       macinfo_type = read_1_byte (abfd, mac_ptr);
19446       mac_ptr++;
19447
19448       /* Note that we rely on the fact that the corresponding GNU and
19449          DWARF constants are the same.  */
19450       switch (macinfo_type)
19451         {
19452           /* A zero macinfo type indicates the end of the macro
19453              information.  */
19454         case 0:
19455           break;
19456
19457         case DW_MACRO_GNU_define:
19458         case DW_MACRO_GNU_undef:
19459         case DW_MACRO_GNU_define_indirect:
19460         case DW_MACRO_GNU_undef_indirect:
19461         case DW_MACRO_GNU_define_indirect_alt:
19462         case DW_MACRO_GNU_undef_indirect_alt:
19463           {
19464             unsigned int bytes_read;
19465             int line;
19466             const char *body;
19467             int is_define;
19468
19469             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19470             mac_ptr += bytes_read;
19471
19472             if (macinfo_type == DW_MACRO_GNU_define
19473                 || macinfo_type == DW_MACRO_GNU_undef)
19474               {
19475                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19476                 mac_ptr += bytes_read;
19477               }
19478             else
19479               {
19480                 LONGEST str_offset;
19481
19482                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19483                 mac_ptr += offset_size;
19484
19485                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19486                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19487                     || section_is_dwz)
19488                   {
19489                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19490
19491                     body = read_indirect_string_from_dwz (dwz, str_offset);
19492                   }
19493                 else
19494                   body = read_indirect_string_at_offset (abfd, str_offset);
19495               }
19496
19497             is_define = (macinfo_type == DW_MACRO_GNU_define
19498                          || macinfo_type == DW_MACRO_GNU_define_indirect
19499                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19500             if (! current_file)
19501               {
19502                 /* DWARF violation as no main source is present.  */
19503                 complaint (&symfile_complaints,
19504                            _("debug info with no main source gives macro %s "
19505                              "on line %d: %s"),
19506                            is_define ? _("definition") : _("undefinition"),
19507                            line, body);
19508                 break;
19509               }
19510             if ((line == 0 && !at_commandline)
19511                 || (line != 0 && at_commandline))
19512               complaint (&symfile_complaints,
19513                          _("debug info gives %s macro %s with %s line %d: %s"),
19514                          at_commandline ? _("command-line") : _("in-file"),
19515                          is_define ? _("definition") : _("undefinition"),
19516                          line == 0 ? _("zero") : _("non-zero"), line, body);
19517
19518             if (is_define)
19519               parse_macro_definition (current_file, line, body);
19520             else
19521               {
19522                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19523                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19524                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19525                 macro_undef (current_file, line, body);
19526               }
19527           }
19528           break;
19529
19530         case DW_MACRO_GNU_start_file:
19531           {
19532             unsigned int bytes_read;
19533             int line, file;
19534
19535             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19536             mac_ptr += bytes_read;
19537             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19538             mac_ptr += bytes_read;
19539
19540             if ((line == 0 && !at_commandline)
19541                 || (line != 0 && at_commandline))
19542               complaint (&symfile_complaints,
19543                          _("debug info gives source %d included "
19544                            "from %s at %s line %d"),
19545                          file, at_commandline ? _("command-line") : _("file"),
19546                          line == 0 ? _("zero") : _("non-zero"), line);
19547
19548             if (at_commandline)
19549               {
19550                 /* This DW_MACRO_GNU_start_file was executed in the
19551                    pass one.  */
19552                 at_commandline = 0;
19553               }
19554             else
19555               current_file = macro_start_file (file, line,
19556                                                current_file, comp_dir,
19557                                                lh, objfile);
19558           }
19559           break;
19560
19561         case DW_MACRO_GNU_end_file:
19562           if (! current_file)
19563             complaint (&symfile_complaints,
19564                        _("macro debug info has an unmatched "
19565                          "`close_file' directive"));
19566           else
19567             {
19568               current_file = current_file->included_by;
19569               if (! current_file)
19570                 {
19571                   enum dwarf_macro_record_type next_type;
19572
19573                   /* GCC circa March 2002 doesn't produce the zero
19574                      type byte marking the end of the compilation
19575                      unit.  Complain if it's not there, but exit no
19576                      matter what.  */
19577
19578                   /* Do we at least have room for a macinfo type byte?  */
19579                   if (mac_ptr >= mac_end)
19580                     {
19581                       dwarf2_section_buffer_overflow_complaint (section);
19582                       return;
19583                     }
19584
19585                   /* We don't increment mac_ptr here, so this is just
19586                      a look-ahead.  */
19587                   next_type = read_1_byte (abfd, mac_ptr);
19588                   if (next_type != 0)
19589                     complaint (&symfile_complaints,
19590                                _("no terminating 0-type entry for "
19591                                  "macros in `.debug_macinfo' section"));
19592
19593                   return;
19594                 }
19595             }
19596           break;
19597
19598         case DW_MACRO_GNU_transparent_include:
19599         case DW_MACRO_GNU_transparent_include_alt:
19600           {
19601             LONGEST offset;
19602             void **slot;
19603             bfd *include_bfd = abfd;
19604             struct dwarf2_section_info *include_section = section;
19605             struct dwarf2_section_info alt_section;
19606             const gdb_byte *include_mac_end = mac_end;
19607             int is_dwz = section_is_dwz;
19608             const gdb_byte *new_mac_ptr;
19609
19610             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19611             mac_ptr += offset_size;
19612
19613             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19614               {
19615                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19616
19617                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19618                                      &dwz->macro);
19619
19620                 include_bfd = dwz->macro.asection->owner;
19621                 include_section = &dwz->macro;
19622                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19623                 is_dwz = 1;
19624               }
19625
19626             new_mac_ptr = include_section->buffer + offset;
19627             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19628
19629             if (*slot != NULL)
19630               {
19631                 /* This has actually happened; see
19632                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19633                 complaint (&symfile_complaints,
19634                            _("recursive DW_MACRO_GNU_transparent_include in "
19635                              ".debug_macro section"));
19636               }
19637             else
19638               {
19639                 *slot = (void *) new_mac_ptr;
19640
19641                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19642                                           include_mac_end, current_file,
19643                                           lh, comp_dir,
19644                                           section, section_is_gnu, is_dwz,
19645                                           offset_size, objfile, include_hash);
19646
19647                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19648               }
19649           }
19650           break;
19651
19652         case DW_MACINFO_vendor_ext:
19653           if (!section_is_gnu)
19654             {
19655               unsigned int bytes_read;
19656               int constant;
19657
19658               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19659               mac_ptr += bytes_read;
19660               read_direct_string (abfd, mac_ptr, &bytes_read);
19661               mac_ptr += bytes_read;
19662
19663               /* We don't recognize any vendor extensions.  */
19664               break;
19665             }
19666           /* FALLTHROUGH */
19667
19668         default:
19669           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19670                                          mac_ptr, mac_end, abfd, offset_size,
19671                                          section);
19672           if (mac_ptr == NULL)
19673             return;
19674           break;
19675         }
19676     } while (macinfo_type != 0);
19677 }
19678
19679 static void
19680 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19681                      const char *comp_dir, int section_is_gnu)
19682 {
19683   struct objfile *objfile = dwarf2_per_objfile->objfile;
19684   struct line_header *lh = cu->line_header;
19685   bfd *abfd;
19686   const gdb_byte *mac_ptr, *mac_end;
19687   struct macro_source_file *current_file = 0;
19688   enum dwarf_macro_record_type macinfo_type;
19689   unsigned int offset_size = cu->header.offset_size;
19690   const gdb_byte *opcode_definitions[256];
19691   struct cleanup *cleanup;
19692   htab_t include_hash;
19693   void **slot;
19694   struct dwarf2_section_info *section;
19695   const char *section_name;
19696
19697   if (cu->dwo_unit != NULL)
19698     {
19699       if (section_is_gnu)
19700         {
19701           section = &cu->dwo_unit->dwo_file->sections.macro;
19702           section_name = ".debug_macro.dwo";
19703         }
19704       else
19705         {
19706           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19707           section_name = ".debug_macinfo.dwo";
19708         }
19709     }
19710   else
19711     {
19712       if (section_is_gnu)
19713         {
19714           section = &dwarf2_per_objfile->macro;
19715           section_name = ".debug_macro";
19716         }
19717       else
19718         {
19719           section = &dwarf2_per_objfile->macinfo;
19720           section_name = ".debug_macinfo";
19721         }
19722     }
19723
19724   dwarf2_read_section (objfile, section);
19725   if (section->buffer == NULL)
19726     {
19727       complaint (&symfile_complaints, _("missing %s section"), section_name);
19728       return;
19729     }
19730   abfd = section->asection->owner;
19731
19732   /* First pass: Find the name of the base filename.
19733      This filename is needed in order to process all macros whose definition
19734      (or undefinition) comes from the command line.  These macros are defined
19735      before the first DW_MACINFO_start_file entry, and yet still need to be
19736      associated to the base file.
19737
19738      To determine the base file name, we scan the macro definitions until we
19739      reach the first DW_MACINFO_start_file entry.  We then initialize
19740      CURRENT_FILE accordingly so that any macro definition found before the
19741      first DW_MACINFO_start_file can still be associated to the base file.  */
19742
19743   mac_ptr = section->buffer + offset;
19744   mac_end = section->buffer + section->size;
19745
19746   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19747                                       &offset_size, section_is_gnu);
19748   if (mac_ptr == NULL)
19749     {
19750       /* We already issued a complaint.  */
19751       return;
19752     }
19753
19754   do
19755     {
19756       /* Do we at least have room for a macinfo type byte?  */
19757       if (mac_ptr >= mac_end)
19758         {
19759           /* Complaint is printed during the second pass as GDB will probably
19760              stop the first pass earlier upon finding
19761              DW_MACINFO_start_file.  */
19762           break;
19763         }
19764
19765       macinfo_type = read_1_byte (abfd, mac_ptr);
19766       mac_ptr++;
19767
19768       /* Note that we rely on the fact that the corresponding GNU and
19769          DWARF constants are the same.  */
19770       switch (macinfo_type)
19771         {
19772           /* A zero macinfo type indicates the end of the macro
19773              information.  */
19774         case 0:
19775           break;
19776
19777         case DW_MACRO_GNU_define:
19778         case DW_MACRO_GNU_undef:
19779           /* Only skip the data by MAC_PTR.  */
19780           {
19781             unsigned int bytes_read;
19782
19783             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19784             mac_ptr += bytes_read;
19785             read_direct_string (abfd, mac_ptr, &bytes_read);
19786             mac_ptr += bytes_read;
19787           }
19788           break;
19789
19790         case DW_MACRO_GNU_start_file:
19791           {
19792             unsigned int bytes_read;
19793             int line, file;
19794
19795             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19796             mac_ptr += bytes_read;
19797             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19798             mac_ptr += bytes_read;
19799
19800             current_file = macro_start_file (file, line, current_file,
19801                                              comp_dir, lh, objfile);
19802           }
19803           break;
19804
19805         case DW_MACRO_GNU_end_file:
19806           /* No data to skip by MAC_PTR.  */
19807           break;
19808
19809         case DW_MACRO_GNU_define_indirect:
19810         case DW_MACRO_GNU_undef_indirect:
19811         case DW_MACRO_GNU_define_indirect_alt:
19812         case DW_MACRO_GNU_undef_indirect_alt:
19813           {
19814             unsigned int bytes_read;
19815
19816             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19817             mac_ptr += bytes_read;
19818             mac_ptr += offset_size;
19819           }
19820           break;
19821
19822         case DW_MACRO_GNU_transparent_include:
19823         case DW_MACRO_GNU_transparent_include_alt:
19824           /* Note that, according to the spec, a transparent include
19825              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19826              skip this opcode.  */
19827           mac_ptr += offset_size;
19828           break;
19829
19830         case DW_MACINFO_vendor_ext:
19831           /* Only skip the data by MAC_PTR.  */
19832           if (!section_is_gnu)
19833             {
19834               unsigned int bytes_read;
19835
19836               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19837               mac_ptr += bytes_read;
19838               read_direct_string (abfd, mac_ptr, &bytes_read);
19839               mac_ptr += bytes_read;
19840             }
19841           /* FALLTHROUGH */
19842
19843         default:
19844           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19845                                          mac_ptr, mac_end, abfd, offset_size,
19846                                          section);
19847           if (mac_ptr == NULL)
19848             return;
19849           break;
19850         }
19851     } while (macinfo_type != 0 && current_file == NULL);
19852
19853   /* Second pass: Process all entries.
19854
19855      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19856      command-line macro definitions/undefinitions.  This flag is unset when we
19857      reach the first DW_MACINFO_start_file entry.  */
19858
19859   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19860                                     NULL, xcalloc, xfree);
19861   cleanup = make_cleanup_htab_delete (include_hash);
19862   mac_ptr = section->buffer + offset;
19863   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19864   *slot = (void *) mac_ptr;
19865   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19866                             current_file, lh, comp_dir, section,
19867                             section_is_gnu, 0,
19868                             offset_size, objfile, include_hash);
19869   do_cleanups (cleanup);
19870 }
19871
19872 /* Check if the attribute's form is a DW_FORM_block*
19873    if so return true else false.  */
19874
19875 static int
19876 attr_form_is_block (const struct attribute *attr)
19877 {
19878   return (attr == NULL ? 0 :
19879       attr->form == DW_FORM_block1
19880       || attr->form == DW_FORM_block2
19881       || attr->form == DW_FORM_block4
19882       || attr->form == DW_FORM_block
19883       || attr->form == DW_FORM_exprloc);
19884 }
19885
19886 /* Return non-zero if ATTR's value is a section offset --- classes
19887    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19888    You may use DW_UNSND (attr) to retrieve such offsets.
19889
19890    Section 7.5.4, "Attribute Encodings", explains that no attribute
19891    may have a value that belongs to more than one of these classes; it
19892    would be ambiguous if we did, because we use the same forms for all
19893    of them.  */
19894
19895 static int
19896 attr_form_is_section_offset (const struct attribute *attr)
19897 {
19898   return (attr->form == DW_FORM_data4
19899           || attr->form == DW_FORM_data8
19900           || attr->form == DW_FORM_sec_offset);
19901 }
19902
19903 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19904    zero otherwise.  When this function returns true, you can apply
19905    dwarf2_get_attr_constant_value to it.
19906
19907    However, note that for some attributes you must check
19908    attr_form_is_section_offset before using this test.  DW_FORM_data4
19909    and DW_FORM_data8 are members of both the constant class, and of
19910    the classes that contain offsets into other debug sections
19911    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19912    that, if an attribute's can be either a constant or one of the
19913    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19914    taken as section offsets, not constants.  */
19915
19916 static int
19917 attr_form_is_constant (const struct attribute *attr)
19918 {
19919   switch (attr->form)
19920     {
19921     case DW_FORM_sdata:
19922     case DW_FORM_udata:
19923     case DW_FORM_data1:
19924     case DW_FORM_data2:
19925     case DW_FORM_data4:
19926     case DW_FORM_data8:
19927       return 1;
19928     default:
19929       return 0;
19930     }
19931 }
19932
19933
19934 /* DW_ADDR is always stored already as sect_offset; despite for the forms
19935    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
19936
19937 static int
19938 attr_form_is_ref (const struct attribute *attr)
19939 {
19940   switch (attr->form)
19941     {
19942     case DW_FORM_ref_addr:
19943     case DW_FORM_ref1:
19944     case DW_FORM_ref2:
19945     case DW_FORM_ref4:
19946     case DW_FORM_ref8:
19947     case DW_FORM_ref_udata:
19948     case DW_FORM_GNU_ref_alt:
19949       return 1;
19950     default:
19951       return 0;
19952     }
19953 }
19954
19955 /* Return the .debug_loc section to use for CU.
19956    For DWO files use .debug_loc.dwo.  */
19957
19958 static struct dwarf2_section_info *
19959 cu_debug_loc_section (struct dwarf2_cu *cu)
19960 {
19961   if (cu->dwo_unit)
19962     return &cu->dwo_unit->dwo_file->sections.loc;
19963   return &dwarf2_per_objfile->loc;
19964 }
19965
19966 /* A helper function that fills in a dwarf2_loclist_baton.  */
19967
19968 static void
19969 fill_in_loclist_baton (struct dwarf2_cu *cu,
19970                        struct dwarf2_loclist_baton *baton,
19971                        const struct attribute *attr)
19972 {
19973   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19974
19975   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19976
19977   baton->per_cu = cu->per_cu;
19978   gdb_assert (baton->per_cu);
19979   /* We don't know how long the location list is, but make sure we
19980      don't run off the edge of the section.  */
19981   baton->size = section->size - DW_UNSND (attr);
19982   baton->data = section->buffer + DW_UNSND (attr);
19983   baton->base_address = cu->base_address;
19984   baton->from_dwo = cu->dwo_unit != NULL;
19985 }
19986
19987 static void
19988 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
19989                              struct dwarf2_cu *cu, int is_block)
19990 {
19991   struct objfile *objfile = dwarf2_per_objfile->objfile;
19992   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19993
19994   if (attr_form_is_section_offset (attr)
19995       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19996          the section.  If so, fall through to the complaint in the
19997          other branch.  */
19998       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19999     {
20000       struct dwarf2_loclist_baton *baton;
20001
20002       baton = obstack_alloc (&objfile->objfile_obstack,
20003                              sizeof (struct dwarf2_loclist_baton));
20004
20005       fill_in_loclist_baton (cu, baton, attr);
20006
20007       if (cu->base_known == 0)
20008         complaint (&symfile_complaints,
20009                    _("Location list used without "
20010                      "specifying the CU base address."));
20011
20012       SYMBOL_ACLASS_INDEX (sym) = (is_block
20013                                    ? dwarf2_loclist_block_index
20014                                    : dwarf2_loclist_index);
20015       SYMBOL_LOCATION_BATON (sym) = baton;
20016     }
20017   else
20018     {
20019       struct dwarf2_locexpr_baton *baton;
20020
20021       baton = obstack_alloc (&objfile->objfile_obstack,
20022                              sizeof (struct dwarf2_locexpr_baton));
20023       baton->per_cu = cu->per_cu;
20024       gdb_assert (baton->per_cu);
20025
20026       if (attr_form_is_block (attr))
20027         {
20028           /* Note that we're just copying the block's data pointer
20029              here, not the actual data.  We're still pointing into the
20030              info_buffer for SYM's objfile; right now we never release
20031              that buffer, but when we do clean up properly this may
20032              need to change.  */
20033           baton->size = DW_BLOCK (attr)->size;
20034           baton->data = DW_BLOCK (attr)->data;
20035         }
20036       else
20037         {
20038           dwarf2_invalid_attrib_class_complaint ("location description",
20039                                                  SYMBOL_NATURAL_NAME (sym));
20040           baton->size = 0;
20041         }
20042
20043       SYMBOL_ACLASS_INDEX (sym) = (is_block
20044                                    ? dwarf2_locexpr_block_index
20045                                    : dwarf2_locexpr_index);
20046       SYMBOL_LOCATION_BATON (sym) = baton;
20047     }
20048 }
20049
20050 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20051    came from a separate debuginfo file, then the master objfile is
20052    returned.  */
20053
20054 struct objfile *
20055 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20056 {
20057   struct objfile *objfile = per_cu->objfile;
20058
20059   /* Return the master objfile, so that we can report and look up the
20060      correct file containing this variable.  */
20061   if (objfile->separate_debug_objfile_backlink)
20062     objfile = objfile->separate_debug_objfile_backlink;
20063
20064   return objfile;
20065 }
20066
20067 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20068    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20069    CU_HEADERP first.  */
20070
20071 static const struct comp_unit_head *
20072 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20073                        struct dwarf2_per_cu_data *per_cu)
20074 {
20075   const gdb_byte *info_ptr;
20076
20077   if (per_cu->cu)
20078     return &per_cu->cu->header;
20079
20080   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20081
20082   memset (cu_headerp, 0, sizeof (*cu_headerp));
20083   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20084
20085   return cu_headerp;
20086 }
20087
20088 /* Return the address size given in the compilation unit header for CU.  */
20089
20090 int
20091 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20092 {
20093   struct comp_unit_head cu_header_local;
20094   const struct comp_unit_head *cu_headerp;
20095
20096   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20097
20098   return cu_headerp->addr_size;
20099 }
20100
20101 /* Return the offset size given in the compilation unit header for CU.  */
20102
20103 int
20104 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20105 {
20106   struct comp_unit_head cu_header_local;
20107   const struct comp_unit_head *cu_headerp;
20108
20109   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20110
20111   return cu_headerp->offset_size;
20112 }
20113
20114 /* See its dwarf2loc.h declaration.  */
20115
20116 int
20117 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20118 {
20119   struct comp_unit_head cu_header_local;
20120   const struct comp_unit_head *cu_headerp;
20121
20122   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20123
20124   if (cu_headerp->version == 2)
20125     return cu_headerp->addr_size;
20126   else
20127     return cu_headerp->offset_size;
20128 }
20129
20130 /* Return the text offset of the CU.  The returned offset comes from
20131    this CU's objfile.  If this objfile came from a separate debuginfo
20132    file, then the offset may be different from the corresponding
20133    offset in the parent objfile.  */
20134
20135 CORE_ADDR
20136 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20137 {
20138   struct objfile *objfile = per_cu->objfile;
20139
20140   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20141 }
20142
20143 /* Locate the .debug_info compilation unit from CU's objfile which contains
20144    the DIE at OFFSET.  Raises an error on failure.  */
20145
20146 static struct dwarf2_per_cu_data *
20147 dwarf2_find_containing_comp_unit (sect_offset offset,
20148                                   unsigned int offset_in_dwz,
20149                                   struct objfile *objfile)
20150 {
20151   struct dwarf2_per_cu_data *this_cu;
20152   int low, high;
20153   const sect_offset *cu_off;
20154
20155   low = 0;
20156   high = dwarf2_per_objfile->n_comp_units - 1;
20157   while (high > low)
20158     {
20159       struct dwarf2_per_cu_data *mid_cu;
20160       int mid = low + (high - low) / 2;
20161
20162       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20163       cu_off = &mid_cu->offset;
20164       if (mid_cu->is_dwz > offset_in_dwz
20165           || (mid_cu->is_dwz == offset_in_dwz
20166               && cu_off->sect_off >= offset.sect_off))
20167         high = mid;
20168       else
20169         low = mid + 1;
20170     }
20171   gdb_assert (low == high);
20172   this_cu = dwarf2_per_objfile->all_comp_units[low];
20173   cu_off = &this_cu->offset;
20174   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20175     {
20176       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20177         error (_("Dwarf Error: could not find partial DIE containing "
20178                "offset 0x%lx [in module %s]"),
20179                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20180
20181       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20182                   <= offset.sect_off);
20183       return dwarf2_per_objfile->all_comp_units[low-1];
20184     }
20185   else
20186     {
20187       this_cu = dwarf2_per_objfile->all_comp_units[low];
20188       if (low == dwarf2_per_objfile->n_comp_units - 1
20189           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20190         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20191       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20192       return this_cu;
20193     }
20194 }
20195
20196 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20197
20198 static void
20199 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20200 {
20201   memset (cu, 0, sizeof (*cu));
20202   per_cu->cu = cu;
20203   cu->per_cu = per_cu;
20204   cu->objfile = per_cu->objfile;
20205   obstack_init (&cu->comp_unit_obstack);
20206 }
20207
20208 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20209
20210 static void
20211 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20212                        enum language pretend_language)
20213 {
20214   struct attribute *attr;
20215
20216   /* Set the language we're debugging.  */
20217   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20218   if (attr)
20219     set_cu_language (DW_UNSND (attr), cu);
20220   else
20221     {
20222       cu->language = pretend_language;
20223       cu->language_defn = language_def (cu->language);
20224     }
20225
20226   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20227   if (attr)
20228     cu->producer = DW_STRING (attr);
20229 }
20230
20231 /* Release one cached compilation unit, CU.  We unlink it from the tree
20232    of compilation units, but we don't remove it from the read_in_chain;
20233    the caller is responsible for that.
20234    NOTE: DATA is a void * because this function is also used as a
20235    cleanup routine.  */
20236
20237 static void
20238 free_heap_comp_unit (void *data)
20239 {
20240   struct dwarf2_cu *cu = data;
20241
20242   gdb_assert (cu->per_cu != NULL);
20243   cu->per_cu->cu = NULL;
20244   cu->per_cu = NULL;
20245
20246   obstack_free (&cu->comp_unit_obstack, NULL);
20247
20248   xfree (cu);
20249 }
20250
20251 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20252    when we're finished with it.  We can't free the pointer itself, but be
20253    sure to unlink it from the cache.  Also release any associated storage.  */
20254
20255 static void
20256 free_stack_comp_unit (void *data)
20257 {
20258   struct dwarf2_cu *cu = data;
20259
20260   gdb_assert (cu->per_cu != NULL);
20261   cu->per_cu->cu = NULL;
20262   cu->per_cu = NULL;
20263
20264   obstack_free (&cu->comp_unit_obstack, NULL);
20265   cu->partial_dies = NULL;
20266 }
20267
20268 /* Free all cached compilation units.  */
20269
20270 static void
20271 free_cached_comp_units (void *data)
20272 {
20273   struct dwarf2_per_cu_data *per_cu, **last_chain;
20274
20275   per_cu = dwarf2_per_objfile->read_in_chain;
20276   last_chain = &dwarf2_per_objfile->read_in_chain;
20277   while (per_cu != NULL)
20278     {
20279       struct dwarf2_per_cu_data *next_cu;
20280
20281       next_cu = per_cu->cu->read_in_chain;
20282
20283       free_heap_comp_unit (per_cu->cu);
20284       *last_chain = next_cu;
20285
20286       per_cu = next_cu;
20287     }
20288 }
20289
20290 /* Increase the age counter on each cached compilation unit, and free
20291    any that are too old.  */
20292
20293 static void
20294 age_cached_comp_units (void)
20295 {
20296   struct dwarf2_per_cu_data *per_cu, **last_chain;
20297
20298   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20299   per_cu = dwarf2_per_objfile->read_in_chain;
20300   while (per_cu != NULL)
20301     {
20302       per_cu->cu->last_used ++;
20303       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20304         dwarf2_mark (per_cu->cu);
20305       per_cu = per_cu->cu->read_in_chain;
20306     }
20307
20308   per_cu = dwarf2_per_objfile->read_in_chain;
20309   last_chain = &dwarf2_per_objfile->read_in_chain;
20310   while (per_cu != NULL)
20311     {
20312       struct dwarf2_per_cu_data *next_cu;
20313
20314       next_cu = per_cu->cu->read_in_chain;
20315
20316       if (!per_cu->cu->mark)
20317         {
20318           free_heap_comp_unit (per_cu->cu);
20319           *last_chain = next_cu;
20320         }
20321       else
20322         last_chain = &per_cu->cu->read_in_chain;
20323
20324       per_cu = next_cu;
20325     }
20326 }
20327
20328 /* Remove a single compilation unit from the cache.  */
20329
20330 static void
20331 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20332 {
20333   struct dwarf2_per_cu_data *per_cu, **last_chain;
20334
20335   per_cu = dwarf2_per_objfile->read_in_chain;
20336   last_chain = &dwarf2_per_objfile->read_in_chain;
20337   while (per_cu != NULL)
20338     {
20339       struct dwarf2_per_cu_data *next_cu;
20340
20341       next_cu = per_cu->cu->read_in_chain;
20342
20343       if (per_cu == target_per_cu)
20344         {
20345           free_heap_comp_unit (per_cu->cu);
20346           per_cu->cu = NULL;
20347           *last_chain = next_cu;
20348           break;
20349         }
20350       else
20351         last_chain = &per_cu->cu->read_in_chain;
20352
20353       per_cu = next_cu;
20354     }
20355 }
20356
20357 /* Release all extra memory associated with OBJFILE.  */
20358
20359 void
20360 dwarf2_free_objfile (struct objfile *objfile)
20361 {
20362   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20363
20364   if (dwarf2_per_objfile == NULL)
20365     return;
20366
20367   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20368   free_cached_comp_units (NULL);
20369
20370   if (dwarf2_per_objfile->quick_file_names_table)
20371     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20372
20373   /* Everything else should be on the objfile obstack.  */
20374 }
20375
20376 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20377    We store these in a hash table separate from the DIEs, and preserve them
20378    when the DIEs are flushed out of cache.
20379
20380    The CU "per_cu" pointer is needed because offset alone is not enough to
20381    uniquely identify the type.  A file may have multiple .debug_types sections,
20382    or the type may come from a DWO file.  Furthermore, while it's more logical
20383    to use per_cu->section+offset, with Fission the section with the data is in
20384    the DWO file but we don't know that section at the point we need it.
20385    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20386    because we can enter the lookup routine, get_die_type_at_offset, from
20387    outside this file, and thus won't necessarily have PER_CU->cu.
20388    Fortunately, PER_CU is stable for the life of the objfile.  */
20389
20390 struct dwarf2_per_cu_offset_and_type
20391 {
20392   const struct dwarf2_per_cu_data *per_cu;
20393   sect_offset offset;
20394   struct type *type;
20395 };
20396
20397 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20398
20399 static hashval_t
20400 per_cu_offset_and_type_hash (const void *item)
20401 {
20402   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20403
20404   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20405 }
20406
20407 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20408
20409 static int
20410 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20411 {
20412   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20413   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20414
20415   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20416           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20417 }
20418
20419 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20420    table if necessary.  For convenience, return TYPE.
20421
20422    The DIEs reading must have careful ordering to:
20423     * Not cause infite loops trying to read in DIEs as a prerequisite for
20424       reading current DIE.
20425     * Not trying to dereference contents of still incompletely read in types
20426       while reading in other DIEs.
20427     * Enable referencing still incompletely read in types just by a pointer to
20428       the type without accessing its fields.
20429
20430    Therefore caller should follow these rules:
20431      * Try to fetch any prerequisite types we may need to build this DIE type
20432        before building the type and calling set_die_type.
20433      * After building type call set_die_type for current DIE as soon as
20434        possible before fetching more types to complete the current type.
20435      * Make the type as complete as possible before fetching more types.  */
20436
20437 static struct type *
20438 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20439 {
20440   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20441   struct objfile *objfile = cu->objfile;
20442
20443   /* For Ada types, make sure that the gnat-specific data is always
20444      initialized (if not already set).  There are a few types where
20445      we should not be doing so, because the type-specific area is
20446      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20447      where the type-specific area is used to store the floatformat).
20448      But this is not a problem, because the gnat-specific information
20449      is actually not needed for these types.  */
20450   if (need_gnat_info (cu)
20451       && TYPE_CODE (type) != TYPE_CODE_FUNC
20452       && TYPE_CODE (type) != TYPE_CODE_FLT
20453       && !HAVE_GNAT_AUX_INFO (type))
20454     INIT_GNAT_SPECIFIC (type);
20455
20456   if (dwarf2_per_objfile->die_type_hash == NULL)
20457     {
20458       dwarf2_per_objfile->die_type_hash =
20459         htab_create_alloc_ex (127,
20460                               per_cu_offset_and_type_hash,
20461                               per_cu_offset_and_type_eq,
20462                               NULL,
20463                               &objfile->objfile_obstack,
20464                               hashtab_obstack_allocate,
20465                               dummy_obstack_deallocate);
20466     }
20467
20468   ofs.per_cu = cu->per_cu;
20469   ofs.offset = die->offset;
20470   ofs.type = type;
20471   slot = (struct dwarf2_per_cu_offset_and_type **)
20472     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20473   if (*slot)
20474     complaint (&symfile_complaints,
20475                _("A problem internal to GDB: DIE 0x%x has type already set"),
20476                die->offset.sect_off);
20477   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20478   **slot = ofs;
20479   return type;
20480 }
20481
20482 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20483    or return NULL if the die does not have a saved type.  */
20484
20485 static struct type *
20486 get_die_type_at_offset (sect_offset offset,
20487                         struct dwarf2_per_cu_data *per_cu)
20488 {
20489   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20490
20491   if (dwarf2_per_objfile->die_type_hash == NULL)
20492     return NULL;
20493
20494   ofs.per_cu = per_cu;
20495   ofs.offset = offset;
20496   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20497   if (slot)
20498     return slot->type;
20499   else
20500     return NULL;
20501 }
20502
20503 /* Look up the type for DIE in CU in die_type_hash,
20504    or return NULL if DIE does not have a saved type.  */
20505
20506 static struct type *
20507 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20508 {
20509   return get_die_type_at_offset (die->offset, cu->per_cu);
20510 }
20511
20512 /* Add a dependence relationship from CU to REF_PER_CU.  */
20513
20514 static void
20515 dwarf2_add_dependence (struct dwarf2_cu *cu,
20516                        struct dwarf2_per_cu_data *ref_per_cu)
20517 {
20518   void **slot;
20519
20520   if (cu->dependencies == NULL)
20521     cu->dependencies
20522       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20523                               NULL, &cu->comp_unit_obstack,
20524                               hashtab_obstack_allocate,
20525                               dummy_obstack_deallocate);
20526
20527   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20528   if (*slot == NULL)
20529     *slot = ref_per_cu;
20530 }
20531
20532 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20533    Set the mark field in every compilation unit in the
20534    cache that we must keep because we are keeping CU.  */
20535
20536 static int
20537 dwarf2_mark_helper (void **slot, void *data)
20538 {
20539   struct dwarf2_per_cu_data *per_cu;
20540
20541   per_cu = (struct dwarf2_per_cu_data *) *slot;
20542
20543   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20544      reading of the chain.  As such dependencies remain valid it is not much
20545      useful to track and undo them during QUIT cleanups.  */
20546   if (per_cu->cu == NULL)
20547     return 1;
20548
20549   if (per_cu->cu->mark)
20550     return 1;
20551   per_cu->cu->mark = 1;
20552
20553   if (per_cu->cu->dependencies != NULL)
20554     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20555
20556   return 1;
20557 }
20558
20559 /* Set the mark field in CU and in every other compilation unit in the
20560    cache that we must keep because we are keeping CU.  */
20561
20562 static void
20563 dwarf2_mark (struct dwarf2_cu *cu)
20564 {
20565   if (cu->mark)
20566     return;
20567   cu->mark = 1;
20568   if (cu->dependencies != NULL)
20569     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20570 }
20571
20572 static void
20573 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20574 {
20575   while (per_cu)
20576     {
20577       per_cu->cu->mark = 0;
20578       per_cu = per_cu->cu->read_in_chain;
20579     }
20580 }
20581
20582 /* Trivial hash function for partial_die_info: the hash value of a DIE
20583    is its offset in .debug_info for this objfile.  */
20584
20585 static hashval_t
20586 partial_die_hash (const void *item)
20587 {
20588   const struct partial_die_info *part_die = item;
20589
20590   return part_die->offset.sect_off;
20591 }
20592
20593 /* Trivial comparison function for partial_die_info structures: two DIEs
20594    are equal if they have the same offset.  */
20595
20596 static int
20597 partial_die_eq (const void *item_lhs, const void *item_rhs)
20598 {
20599   const struct partial_die_info *part_die_lhs = item_lhs;
20600   const struct partial_die_info *part_die_rhs = item_rhs;
20601
20602   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20603 }
20604
20605 static struct cmd_list_element *set_dwarf2_cmdlist;
20606 static struct cmd_list_element *show_dwarf2_cmdlist;
20607
20608 static void
20609 set_dwarf2_cmd (char *args, int from_tty)
20610 {
20611   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20612 }
20613
20614 static void
20615 show_dwarf2_cmd (char *args, int from_tty)
20616 {
20617   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20618 }
20619
20620 /* Free data associated with OBJFILE, if necessary.  */
20621
20622 static void
20623 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20624 {
20625   struct dwarf2_per_objfile *data = d;
20626   int ix;
20627
20628   /* Make sure we don't accidentally use dwarf2_per_objfile while
20629      cleaning up.  */
20630   dwarf2_per_objfile = NULL;
20631
20632   for (ix = 0; ix < data->n_comp_units; ++ix)
20633    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20634
20635   for (ix = 0; ix < data->n_type_units; ++ix)
20636     VEC_free (dwarf2_per_cu_ptr,
20637               data->all_type_units[ix]->per_cu.imported_symtabs);
20638   xfree (data->all_type_units);
20639
20640   VEC_free (dwarf2_section_info_def, data->types);
20641
20642   if (data->dwo_files)
20643     free_dwo_files (data->dwo_files, objfile);
20644   if (data->dwp_file)
20645     gdb_bfd_unref (data->dwp_file->dbfd);
20646
20647   if (data->dwz_file && data->dwz_file->dwz_bfd)
20648     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20649 }
20650
20651 \f
20652 /* The "save gdb-index" command.  */
20653
20654 /* The contents of the hash table we create when building the string
20655    table.  */
20656 struct strtab_entry
20657 {
20658   offset_type offset;
20659   const char *str;
20660 };
20661
20662 /* Hash function for a strtab_entry.
20663
20664    Function is used only during write_hash_table so no index format backward
20665    compatibility is needed.  */
20666
20667 static hashval_t
20668 hash_strtab_entry (const void *e)
20669 {
20670   const struct strtab_entry *entry = e;
20671   return mapped_index_string_hash (INT_MAX, entry->str);
20672 }
20673
20674 /* Equality function for a strtab_entry.  */
20675
20676 static int
20677 eq_strtab_entry (const void *a, const void *b)
20678 {
20679   const struct strtab_entry *ea = a;
20680   const struct strtab_entry *eb = b;
20681   return !strcmp (ea->str, eb->str);
20682 }
20683
20684 /* Create a strtab_entry hash table.  */
20685
20686 static htab_t
20687 create_strtab (void)
20688 {
20689   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20690                             xfree, xcalloc, xfree);
20691 }
20692
20693 /* Add a string to the constant pool.  Return the string's offset in
20694    host order.  */
20695
20696 static offset_type
20697 add_string (htab_t table, struct obstack *cpool, const char *str)
20698 {
20699   void **slot;
20700   struct strtab_entry entry;
20701   struct strtab_entry *result;
20702
20703   entry.str = str;
20704   slot = htab_find_slot (table, &entry, INSERT);
20705   if (*slot)
20706     result = *slot;
20707   else
20708     {
20709       result = XNEW (struct strtab_entry);
20710       result->offset = obstack_object_size (cpool);
20711       result->str = str;
20712       obstack_grow_str0 (cpool, str);
20713       *slot = result;
20714     }
20715   return result->offset;
20716 }
20717
20718 /* An entry in the symbol table.  */
20719 struct symtab_index_entry
20720 {
20721   /* The name of the symbol.  */
20722   const char *name;
20723   /* The offset of the name in the constant pool.  */
20724   offset_type index_offset;
20725   /* A sorted vector of the indices of all the CUs that hold an object
20726      of this name.  */
20727   VEC (offset_type) *cu_indices;
20728 };
20729
20730 /* The symbol table.  This is a power-of-2-sized hash table.  */
20731 struct mapped_symtab
20732 {
20733   offset_type n_elements;
20734   offset_type size;
20735   struct symtab_index_entry **data;
20736 };
20737
20738 /* Hash function for a symtab_index_entry.  */
20739
20740 static hashval_t
20741 hash_symtab_entry (const void *e)
20742 {
20743   const struct symtab_index_entry *entry = e;
20744   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20745                          sizeof (offset_type) * VEC_length (offset_type,
20746                                                             entry->cu_indices),
20747                          0);
20748 }
20749
20750 /* Equality function for a symtab_index_entry.  */
20751
20752 static int
20753 eq_symtab_entry (const void *a, const void *b)
20754 {
20755   const struct symtab_index_entry *ea = a;
20756   const struct symtab_index_entry *eb = b;
20757   int len = VEC_length (offset_type, ea->cu_indices);
20758   if (len != VEC_length (offset_type, eb->cu_indices))
20759     return 0;
20760   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20761                   VEC_address (offset_type, eb->cu_indices),
20762                   sizeof (offset_type) * len);
20763 }
20764
20765 /* Destroy a symtab_index_entry.  */
20766
20767 static void
20768 delete_symtab_entry (void *p)
20769 {
20770   struct symtab_index_entry *entry = p;
20771   VEC_free (offset_type, entry->cu_indices);
20772   xfree (entry);
20773 }
20774
20775 /* Create a hash table holding symtab_index_entry objects.  */
20776
20777 static htab_t
20778 create_symbol_hash_table (void)
20779 {
20780   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20781                             delete_symtab_entry, xcalloc, xfree);
20782 }
20783
20784 /* Create a new mapped symtab object.  */
20785
20786 static struct mapped_symtab *
20787 create_mapped_symtab (void)
20788 {
20789   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20790   symtab->n_elements = 0;
20791   symtab->size = 1024;
20792   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20793   return symtab;
20794 }
20795
20796 /* Destroy a mapped_symtab.  */
20797
20798 static void
20799 cleanup_mapped_symtab (void *p)
20800 {
20801   struct mapped_symtab *symtab = p;
20802   /* The contents of the array are freed when the other hash table is
20803      destroyed.  */
20804   xfree (symtab->data);
20805   xfree (symtab);
20806 }
20807
20808 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20809    the slot.
20810    
20811    Function is used only during write_hash_table so no index format backward
20812    compatibility is needed.  */
20813
20814 static struct symtab_index_entry **
20815 find_slot (struct mapped_symtab *symtab, const char *name)
20816 {
20817   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20818
20819   index = hash & (symtab->size - 1);
20820   step = ((hash * 17) & (symtab->size - 1)) | 1;
20821
20822   for (;;)
20823     {
20824       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20825         return &symtab->data[index];
20826       index = (index + step) & (symtab->size - 1);
20827     }
20828 }
20829
20830 /* Expand SYMTAB's hash table.  */
20831
20832 static void
20833 hash_expand (struct mapped_symtab *symtab)
20834 {
20835   offset_type old_size = symtab->size;
20836   offset_type i;
20837   struct symtab_index_entry **old_entries = symtab->data;
20838
20839   symtab->size *= 2;
20840   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20841
20842   for (i = 0; i < old_size; ++i)
20843     {
20844       if (old_entries[i])
20845         {
20846           struct symtab_index_entry **slot = find_slot (symtab,
20847                                                         old_entries[i]->name);
20848           *slot = old_entries[i];
20849         }
20850     }
20851
20852   xfree (old_entries);
20853 }
20854
20855 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20856    CU_INDEX is the index of the CU in which the symbol appears.
20857    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20858
20859 static void
20860 add_index_entry (struct mapped_symtab *symtab, const char *name,
20861                  int is_static, gdb_index_symbol_kind kind,
20862                  offset_type cu_index)
20863 {
20864   struct symtab_index_entry **slot;
20865   offset_type cu_index_and_attrs;
20866
20867   ++symtab->n_elements;
20868   if (4 * symtab->n_elements / 3 >= symtab->size)
20869     hash_expand (symtab);
20870
20871   slot = find_slot (symtab, name);
20872   if (!*slot)
20873     {
20874       *slot = XNEW (struct symtab_index_entry);
20875       (*slot)->name = name;
20876       /* index_offset is set later.  */
20877       (*slot)->cu_indices = NULL;
20878     }
20879
20880   cu_index_and_attrs = 0;
20881   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20882   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20883   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20884
20885   /* We don't want to record an index value twice as we want to avoid the
20886      duplication.
20887      We process all global symbols and then all static symbols
20888      (which would allow us to avoid the duplication by only having to check
20889      the last entry pushed), but a symbol could have multiple kinds in one CU.
20890      To keep things simple we don't worry about the duplication here and
20891      sort and uniqufy the list after we've processed all symbols.  */
20892   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20893 }
20894
20895 /* qsort helper routine for uniquify_cu_indices.  */
20896
20897 static int
20898 offset_type_compare (const void *ap, const void *bp)
20899 {
20900   offset_type a = *(offset_type *) ap;
20901   offset_type b = *(offset_type *) bp;
20902
20903   return (a > b) - (b > a);
20904 }
20905
20906 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20907
20908 static void
20909 uniquify_cu_indices (struct mapped_symtab *symtab)
20910 {
20911   int i;
20912
20913   for (i = 0; i < symtab->size; ++i)
20914     {
20915       struct symtab_index_entry *entry = symtab->data[i];
20916
20917       if (entry
20918           && entry->cu_indices != NULL)
20919         {
20920           unsigned int next_to_insert, next_to_check;
20921           offset_type last_value;
20922
20923           qsort (VEC_address (offset_type, entry->cu_indices),
20924                  VEC_length (offset_type, entry->cu_indices),
20925                  sizeof (offset_type), offset_type_compare);
20926
20927           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20928           next_to_insert = 1;
20929           for (next_to_check = 1;
20930                next_to_check < VEC_length (offset_type, entry->cu_indices);
20931                ++next_to_check)
20932             {
20933               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20934                   != last_value)
20935                 {
20936                   last_value = VEC_index (offset_type, entry->cu_indices,
20937                                           next_to_check);
20938                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20939                                last_value);
20940                   ++next_to_insert;
20941                 }
20942             }
20943           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20944         }
20945     }
20946 }
20947
20948 /* Add a vector of indices to the constant pool.  */
20949
20950 static offset_type
20951 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20952                       struct symtab_index_entry *entry)
20953 {
20954   void **slot;
20955
20956   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20957   if (!*slot)
20958     {
20959       offset_type len = VEC_length (offset_type, entry->cu_indices);
20960       offset_type val = MAYBE_SWAP (len);
20961       offset_type iter;
20962       int i;
20963
20964       *slot = entry;
20965       entry->index_offset = obstack_object_size (cpool);
20966
20967       obstack_grow (cpool, &val, sizeof (val));
20968       for (i = 0;
20969            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20970            ++i)
20971         {
20972           val = MAYBE_SWAP (iter);
20973           obstack_grow (cpool, &val, sizeof (val));
20974         }
20975     }
20976   else
20977     {
20978       struct symtab_index_entry *old_entry = *slot;
20979       entry->index_offset = old_entry->index_offset;
20980       entry = old_entry;
20981     }
20982   return entry->index_offset;
20983 }
20984
20985 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20986    constant pool entries going into the obstack CPOOL.  */
20987
20988 static void
20989 write_hash_table (struct mapped_symtab *symtab,
20990                   struct obstack *output, struct obstack *cpool)
20991 {
20992   offset_type i;
20993   htab_t symbol_hash_table;
20994   htab_t str_table;
20995
20996   symbol_hash_table = create_symbol_hash_table ();
20997   str_table = create_strtab ();
20998
20999   /* We add all the index vectors to the constant pool first, to
21000      ensure alignment is ok.  */
21001   for (i = 0; i < symtab->size; ++i)
21002     {
21003       if (symtab->data[i])
21004         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21005     }
21006
21007   /* Now write out the hash table.  */
21008   for (i = 0; i < symtab->size; ++i)
21009     {
21010       offset_type str_off, vec_off;
21011
21012       if (symtab->data[i])
21013         {
21014           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21015           vec_off = symtab->data[i]->index_offset;
21016         }
21017       else
21018         {
21019           /* While 0 is a valid constant pool index, it is not valid
21020              to have 0 for both offsets.  */
21021           str_off = 0;
21022           vec_off = 0;
21023         }
21024
21025       str_off = MAYBE_SWAP (str_off);
21026       vec_off = MAYBE_SWAP (vec_off);
21027
21028       obstack_grow (output, &str_off, sizeof (str_off));
21029       obstack_grow (output, &vec_off, sizeof (vec_off));
21030     }
21031
21032   htab_delete (str_table);
21033   htab_delete (symbol_hash_table);
21034 }
21035
21036 /* Struct to map psymtab to CU index in the index file.  */
21037 struct psymtab_cu_index_map
21038 {
21039   struct partial_symtab *psymtab;
21040   unsigned int cu_index;
21041 };
21042
21043 static hashval_t
21044 hash_psymtab_cu_index (const void *item)
21045 {
21046   const struct psymtab_cu_index_map *map = item;
21047
21048   return htab_hash_pointer (map->psymtab);
21049 }
21050
21051 static int
21052 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21053 {
21054   const struct psymtab_cu_index_map *lhs = item_lhs;
21055   const struct psymtab_cu_index_map *rhs = item_rhs;
21056
21057   return lhs->psymtab == rhs->psymtab;
21058 }
21059
21060 /* Helper struct for building the address table.  */
21061 struct addrmap_index_data
21062 {
21063   struct objfile *objfile;
21064   struct obstack *addr_obstack;
21065   htab_t cu_index_htab;
21066
21067   /* Non-zero if the previous_* fields are valid.
21068      We can't write an entry until we see the next entry (since it is only then
21069      that we know the end of the entry).  */
21070   int previous_valid;
21071   /* Index of the CU in the table of all CUs in the index file.  */
21072   unsigned int previous_cu_index;
21073   /* Start address of the CU.  */
21074   CORE_ADDR previous_cu_start;
21075 };
21076
21077 /* Write an address entry to OBSTACK.  */
21078
21079 static void
21080 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21081                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21082 {
21083   offset_type cu_index_to_write;
21084   gdb_byte addr[8];
21085   CORE_ADDR baseaddr;
21086
21087   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21088
21089   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21090   obstack_grow (obstack, addr, 8);
21091   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21092   obstack_grow (obstack, addr, 8);
21093   cu_index_to_write = MAYBE_SWAP (cu_index);
21094   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21095 }
21096
21097 /* Worker function for traversing an addrmap to build the address table.  */
21098
21099 static int
21100 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21101 {
21102   struct addrmap_index_data *data = datap;
21103   struct partial_symtab *pst = obj;
21104
21105   if (data->previous_valid)
21106     add_address_entry (data->objfile, data->addr_obstack,
21107                        data->previous_cu_start, start_addr,
21108                        data->previous_cu_index);
21109
21110   data->previous_cu_start = start_addr;
21111   if (pst != NULL)
21112     {
21113       struct psymtab_cu_index_map find_map, *map;
21114       find_map.psymtab = pst;
21115       map = htab_find (data->cu_index_htab, &find_map);
21116       gdb_assert (map != NULL);
21117       data->previous_cu_index = map->cu_index;
21118       data->previous_valid = 1;
21119     }
21120   else
21121       data->previous_valid = 0;
21122
21123   return 0;
21124 }
21125
21126 /* Write OBJFILE's address map to OBSTACK.
21127    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21128    in the index file.  */
21129
21130 static void
21131 write_address_map (struct objfile *objfile, struct obstack *obstack,
21132                    htab_t cu_index_htab)
21133 {
21134   struct addrmap_index_data addrmap_index_data;
21135
21136   /* When writing the address table, we have to cope with the fact that
21137      the addrmap iterator only provides the start of a region; we have to
21138      wait until the next invocation to get the start of the next region.  */
21139
21140   addrmap_index_data.objfile = objfile;
21141   addrmap_index_data.addr_obstack = obstack;
21142   addrmap_index_data.cu_index_htab = cu_index_htab;
21143   addrmap_index_data.previous_valid = 0;
21144
21145   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21146                    &addrmap_index_data);
21147
21148   /* It's highly unlikely the last entry (end address = 0xff...ff)
21149      is valid, but we should still handle it.
21150      The end address is recorded as the start of the next region, but that
21151      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21152      anyway.  */
21153   if (addrmap_index_data.previous_valid)
21154     add_address_entry (objfile, obstack,
21155                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21156                        addrmap_index_data.previous_cu_index);
21157 }
21158
21159 /* Return the symbol kind of PSYM.  */
21160
21161 static gdb_index_symbol_kind
21162 symbol_kind (struct partial_symbol *psym)
21163 {
21164   domain_enum domain = PSYMBOL_DOMAIN (psym);
21165   enum address_class aclass = PSYMBOL_CLASS (psym);
21166
21167   switch (domain)
21168     {
21169     case VAR_DOMAIN:
21170       switch (aclass)
21171         {
21172         case LOC_BLOCK:
21173           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21174         case LOC_TYPEDEF:
21175           return GDB_INDEX_SYMBOL_KIND_TYPE;
21176         case LOC_COMPUTED:
21177         case LOC_CONST_BYTES:
21178         case LOC_OPTIMIZED_OUT:
21179         case LOC_STATIC:
21180           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21181         case LOC_CONST:
21182           /* Note: It's currently impossible to recognize psyms as enum values
21183              short of reading the type info.  For now punt.  */
21184           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21185         default:
21186           /* There are other LOC_FOO values that one might want to classify
21187              as variables, but dwarf2read.c doesn't currently use them.  */
21188           return GDB_INDEX_SYMBOL_KIND_OTHER;
21189         }
21190     case STRUCT_DOMAIN:
21191       return GDB_INDEX_SYMBOL_KIND_TYPE;
21192     default:
21193       return GDB_INDEX_SYMBOL_KIND_OTHER;
21194     }
21195 }
21196
21197 /* Add a list of partial symbols to SYMTAB.  */
21198
21199 static void
21200 write_psymbols (struct mapped_symtab *symtab,
21201                 htab_t psyms_seen,
21202                 struct partial_symbol **psymp,
21203                 int count,
21204                 offset_type cu_index,
21205                 int is_static)
21206 {
21207   for (; count-- > 0; ++psymp)
21208     {
21209       struct partial_symbol *psym = *psymp;
21210       void **slot;
21211
21212       if (SYMBOL_LANGUAGE (psym) == language_ada)
21213         error (_("Ada is not currently supported by the index"));
21214
21215       /* Only add a given psymbol once.  */
21216       slot = htab_find_slot (psyms_seen, psym, INSERT);
21217       if (!*slot)
21218         {
21219           gdb_index_symbol_kind kind = symbol_kind (psym);
21220
21221           *slot = psym;
21222           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21223                            is_static, kind, cu_index);
21224         }
21225     }
21226 }
21227
21228 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21229    exception if there is an error.  */
21230
21231 static void
21232 write_obstack (FILE *file, struct obstack *obstack)
21233 {
21234   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21235               file)
21236       != obstack_object_size (obstack))
21237     error (_("couldn't data write to file"));
21238 }
21239
21240 /* Unlink a file if the argument is not NULL.  */
21241
21242 static void
21243 unlink_if_set (void *p)
21244 {
21245   char **filename = p;
21246   if (*filename)
21247     unlink (*filename);
21248 }
21249
21250 /* A helper struct used when iterating over debug_types.  */
21251 struct signatured_type_index_data
21252 {
21253   struct objfile *objfile;
21254   struct mapped_symtab *symtab;
21255   struct obstack *types_list;
21256   htab_t psyms_seen;
21257   int cu_index;
21258 };
21259
21260 /* A helper function that writes a single signatured_type to an
21261    obstack.  */
21262
21263 static int
21264 write_one_signatured_type (void **slot, void *d)
21265 {
21266   struct signatured_type_index_data *info = d;
21267   struct signatured_type *entry = (struct signatured_type *) *slot;
21268   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21269   gdb_byte val[8];
21270
21271   write_psymbols (info->symtab,
21272                   info->psyms_seen,
21273                   info->objfile->global_psymbols.list
21274                   + psymtab->globals_offset,
21275                   psymtab->n_global_syms, info->cu_index,
21276                   0);
21277   write_psymbols (info->symtab,
21278                   info->psyms_seen,
21279                   info->objfile->static_psymbols.list
21280                   + psymtab->statics_offset,
21281                   psymtab->n_static_syms, info->cu_index,
21282                   1);
21283
21284   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21285                           entry->per_cu.offset.sect_off);
21286   obstack_grow (info->types_list, val, 8);
21287   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21288                           entry->type_offset_in_tu.cu_off);
21289   obstack_grow (info->types_list, val, 8);
21290   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21291   obstack_grow (info->types_list, val, 8);
21292
21293   ++info->cu_index;
21294
21295   return 1;
21296 }
21297
21298 /* Recurse into all "included" dependencies and write their symbols as
21299    if they appeared in this psymtab.  */
21300
21301 static void
21302 recursively_write_psymbols (struct objfile *objfile,
21303                             struct partial_symtab *psymtab,
21304                             struct mapped_symtab *symtab,
21305                             htab_t psyms_seen,
21306                             offset_type cu_index)
21307 {
21308   int i;
21309
21310   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21311     if (psymtab->dependencies[i]->user != NULL)
21312       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21313                                   symtab, psyms_seen, cu_index);
21314
21315   write_psymbols (symtab,
21316                   psyms_seen,
21317                   objfile->global_psymbols.list + psymtab->globals_offset,
21318                   psymtab->n_global_syms, cu_index,
21319                   0);
21320   write_psymbols (symtab,
21321                   psyms_seen,
21322                   objfile->static_psymbols.list + psymtab->statics_offset,
21323                   psymtab->n_static_syms, cu_index,
21324                   1);
21325 }
21326
21327 /* Create an index file for OBJFILE in the directory DIR.  */
21328
21329 static void
21330 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21331 {
21332   struct cleanup *cleanup;
21333   char *filename, *cleanup_filename;
21334   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21335   struct obstack cu_list, types_cu_list;
21336   int i;
21337   FILE *out_file;
21338   struct mapped_symtab *symtab;
21339   offset_type val, size_of_contents, total_len;
21340   struct stat st;
21341   htab_t psyms_seen;
21342   htab_t cu_index_htab;
21343   struct psymtab_cu_index_map *psymtab_cu_index_map;
21344
21345   if (dwarf2_per_objfile->using_index)
21346     error (_("Cannot use an index to create the index"));
21347
21348   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21349     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21350
21351   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21352     return;
21353
21354   if (stat (objfile->name, &st) < 0)
21355     perror_with_name (objfile->name);
21356
21357   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
21358                      INDEX_SUFFIX, (char *) NULL);
21359   cleanup = make_cleanup (xfree, filename);
21360
21361   out_file = gdb_fopen_cloexec (filename, "wb");
21362   if (!out_file)
21363     error (_("Can't open `%s' for writing"), filename);
21364
21365   cleanup_filename = filename;
21366   make_cleanup (unlink_if_set, &cleanup_filename);
21367
21368   symtab = create_mapped_symtab ();
21369   make_cleanup (cleanup_mapped_symtab, symtab);
21370
21371   obstack_init (&addr_obstack);
21372   make_cleanup_obstack_free (&addr_obstack);
21373
21374   obstack_init (&cu_list);
21375   make_cleanup_obstack_free (&cu_list);
21376
21377   obstack_init (&types_cu_list);
21378   make_cleanup_obstack_free (&types_cu_list);
21379
21380   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21381                                   NULL, xcalloc, xfree);
21382   make_cleanup_htab_delete (psyms_seen);
21383
21384   /* While we're scanning CU's create a table that maps a psymtab pointer
21385      (which is what addrmap records) to its index (which is what is recorded
21386      in the index file).  This will later be needed to write the address
21387      table.  */
21388   cu_index_htab = htab_create_alloc (100,
21389                                      hash_psymtab_cu_index,
21390                                      eq_psymtab_cu_index,
21391                                      NULL, xcalloc, xfree);
21392   make_cleanup_htab_delete (cu_index_htab);
21393   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21394     xmalloc (sizeof (struct psymtab_cu_index_map)
21395              * dwarf2_per_objfile->n_comp_units);
21396   make_cleanup (xfree, psymtab_cu_index_map);
21397
21398   /* The CU list is already sorted, so we don't need to do additional
21399      work here.  Also, the debug_types entries do not appear in
21400      all_comp_units, but only in their own hash table.  */
21401   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21402     {
21403       struct dwarf2_per_cu_data *per_cu
21404         = dwarf2_per_objfile->all_comp_units[i];
21405       struct partial_symtab *psymtab = per_cu->v.psymtab;
21406       gdb_byte val[8];
21407       struct psymtab_cu_index_map *map;
21408       void **slot;
21409
21410       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21411          It may be referenced from a local scope but in such case it does not
21412          need to be present in .gdb_index.  */
21413       if (psymtab == NULL)
21414         continue;
21415
21416       if (psymtab->user == NULL)
21417         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21418
21419       map = &psymtab_cu_index_map[i];
21420       map->psymtab = psymtab;
21421       map->cu_index = i;
21422       slot = htab_find_slot (cu_index_htab, map, INSERT);
21423       gdb_assert (slot != NULL);
21424       gdb_assert (*slot == NULL);
21425       *slot = map;
21426
21427       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21428                               per_cu->offset.sect_off);
21429       obstack_grow (&cu_list, val, 8);
21430       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21431       obstack_grow (&cu_list, val, 8);
21432     }
21433
21434   /* Dump the address map.  */
21435   write_address_map (objfile, &addr_obstack, cu_index_htab);
21436
21437   /* Write out the .debug_type entries, if any.  */
21438   if (dwarf2_per_objfile->signatured_types)
21439     {
21440       struct signatured_type_index_data sig_data;
21441
21442       sig_data.objfile = objfile;
21443       sig_data.symtab = symtab;
21444       sig_data.types_list = &types_cu_list;
21445       sig_data.psyms_seen = psyms_seen;
21446       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21447       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21448                               write_one_signatured_type, &sig_data);
21449     }
21450
21451   /* Now that we've processed all symbols we can shrink their cu_indices
21452      lists.  */
21453   uniquify_cu_indices (symtab);
21454
21455   obstack_init (&constant_pool);
21456   make_cleanup_obstack_free (&constant_pool);
21457   obstack_init (&symtab_obstack);
21458   make_cleanup_obstack_free (&symtab_obstack);
21459   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21460
21461   obstack_init (&contents);
21462   make_cleanup_obstack_free (&contents);
21463   size_of_contents = 6 * sizeof (offset_type);
21464   total_len = size_of_contents;
21465
21466   /* The version number.  */
21467   val = MAYBE_SWAP (8);
21468   obstack_grow (&contents, &val, sizeof (val));
21469
21470   /* The offset of the CU list from the start of the file.  */
21471   val = MAYBE_SWAP (total_len);
21472   obstack_grow (&contents, &val, sizeof (val));
21473   total_len += obstack_object_size (&cu_list);
21474
21475   /* The offset of the types CU list from the start of the file.  */
21476   val = MAYBE_SWAP (total_len);
21477   obstack_grow (&contents, &val, sizeof (val));
21478   total_len += obstack_object_size (&types_cu_list);
21479
21480   /* The offset of the address table from the start of the file.  */
21481   val = MAYBE_SWAP (total_len);
21482   obstack_grow (&contents, &val, sizeof (val));
21483   total_len += obstack_object_size (&addr_obstack);
21484
21485   /* The offset of the symbol table from the start of the file.  */
21486   val = MAYBE_SWAP (total_len);
21487   obstack_grow (&contents, &val, sizeof (val));
21488   total_len += obstack_object_size (&symtab_obstack);
21489
21490   /* The offset of the constant pool from the start of the file.  */
21491   val = MAYBE_SWAP (total_len);
21492   obstack_grow (&contents, &val, sizeof (val));
21493   total_len += obstack_object_size (&constant_pool);
21494
21495   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21496
21497   write_obstack (out_file, &contents);
21498   write_obstack (out_file, &cu_list);
21499   write_obstack (out_file, &types_cu_list);
21500   write_obstack (out_file, &addr_obstack);
21501   write_obstack (out_file, &symtab_obstack);
21502   write_obstack (out_file, &constant_pool);
21503
21504   fclose (out_file);
21505
21506   /* We want to keep the file, so we set cleanup_filename to NULL
21507      here.  See unlink_if_set.  */
21508   cleanup_filename = NULL;
21509
21510   do_cleanups (cleanup);
21511 }
21512
21513 /* Implementation of the `save gdb-index' command.
21514    
21515    Note that the file format used by this command is documented in the
21516    GDB manual.  Any changes here must be documented there.  */
21517
21518 static void
21519 save_gdb_index_command (char *arg, int from_tty)
21520 {
21521   struct objfile *objfile;
21522
21523   if (!arg || !*arg)
21524     error (_("usage: save gdb-index DIRECTORY"));
21525
21526   ALL_OBJFILES (objfile)
21527   {
21528     struct stat st;
21529
21530     /* If the objfile does not correspond to an actual file, skip it.  */
21531     if (stat (objfile->name, &st) < 0)
21532       continue;
21533
21534     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21535     if (dwarf2_per_objfile)
21536       {
21537         volatile struct gdb_exception except;
21538
21539         TRY_CATCH (except, RETURN_MASK_ERROR)
21540           {
21541             write_psymtabs_to_index (objfile, arg);
21542           }
21543         if (except.reason < 0)
21544           exception_fprintf (gdb_stderr, except,
21545                              _("Error while writing index for `%s': "),
21546                              objfile->name);
21547       }
21548   }
21549 }
21550
21551 \f
21552
21553 int dwarf2_always_disassemble;
21554
21555 static void
21556 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21557                                 struct cmd_list_element *c, const char *value)
21558 {
21559   fprintf_filtered (file,
21560                     _("Whether to always disassemble "
21561                       "DWARF expressions is %s.\n"),
21562                     value);
21563 }
21564
21565 static void
21566 show_check_physname (struct ui_file *file, int from_tty,
21567                      struct cmd_list_element *c, const char *value)
21568 {
21569   fprintf_filtered (file,
21570                     _("Whether to check \"physname\" is %s.\n"),
21571                     value);
21572 }
21573
21574 void _initialize_dwarf2_read (void);
21575
21576 void
21577 _initialize_dwarf2_read (void)
21578 {
21579   struct cmd_list_element *c;
21580
21581   dwarf2_objfile_data_key
21582     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21583
21584   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21585 Set DWARF 2 specific variables.\n\
21586 Configure DWARF 2 variables such as the cache size"),
21587                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21588                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21589
21590   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21591 Show DWARF 2 specific variables\n\
21592 Show DWARF 2 variables such as the cache size"),
21593                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21594                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21595
21596   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21597                             &dwarf2_max_cache_age, _("\
21598 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21599 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21600 A higher limit means that cached compilation units will be stored\n\
21601 in memory longer, and more total memory will be used.  Zero disables\n\
21602 caching, which can slow down startup."),
21603                             NULL,
21604                             show_dwarf2_max_cache_age,
21605                             &set_dwarf2_cmdlist,
21606                             &show_dwarf2_cmdlist);
21607
21608   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21609                            &dwarf2_always_disassemble, _("\
21610 Set whether `info address' always disassembles DWARF expressions."), _("\
21611 Show whether `info address' always disassembles DWARF expressions."), _("\
21612 When enabled, DWARF expressions are always printed in an assembly-like\n\
21613 syntax.  When disabled, expressions will be printed in a more\n\
21614 conversational style, when possible."),
21615                            NULL,
21616                            show_dwarf2_always_disassemble,
21617                            &set_dwarf2_cmdlist,
21618                            &show_dwarf2_cmdlist);
21619
21620   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21621 Set debugging of the dwarf2 reader."), _("\
21622 Show debugging of the dwarf2 reader."), _("\
21623 When enabled, debugging messages are printed during dwarf2 reading\n\
21624 and symtab expansion."),
21625                             NULL,
21626                             NULL,
21627                             &setdebuglist, &showdebuglist);
21628
21629   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21630 Set debugging of the dwarf2 DIE reader."), _("\
21631 Show debugging of the dwarf2 DIE reader."), _("\
21632 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21633 The value is the maximum depth to print."),
21634                              NULL,
21635                              NULL,
21636                              &setdebuglist, &showdebuglist);
21637
21638   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21639 Set cross-checking of \"physname\" code against demangler."), _("\
21640 Show cross-checking of \"physname\" code against demangler."), _("\
21641 When enabled, GDB's internal \"physname\" code is checked against\n\
21642 the demangler."),
21643                            NULL, show_check_physname,
21644                            &setdebuglist, &showdebuglist);
21645
21646   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21647                            no_class, &use_deprecated_index_sections, _("\
21648 Set whether to use deprecated gdb_index sections."), _("\
21649 Show whether to use deprecated gdb_index sections."), _("\
21650 When enabled, deprecated .gdb_index sections are used anyway.\n\
21651 Normally they are ignored either because of a missing feature or\n\
21652 performance issue.\n\
21653 Warning: This option must be enabled before gdb reads the file."),
21654                            NULL,
21655                            NULL,
21656                            &setlist, &showlist);
21657
21658   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21659                _("\
21660 Save a gdb-index file.\n\
21661 Usage: save gdb-index DIRECTORY"),
21662                &save_cmdlist);
21663   set_cmd_completer (c, filename_completer);
21664
21665   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21666                                                         &dwarf2_locexpr_funcs);
21667   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21668                                                         &dwarf2_loclist_funcs);
21669
21670   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21671                                         &dwarf2_block_frame_base_locexpr_funcs);
21672   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21673                                         &dwarf2_block_frame_base_loclist_funcs);
21674 }