* dwarf2read.c (struct dwp_file): Fix comment.
[platform/upstream/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72
73 #include <fcntl.h>
74 #include "gdb_string.h"
75 #include "gdb_assert.h"
76 #include <sys/types.h>
77
78 typedef struct symbol *symbolp;
79 DEF_VEC_P (symbolp);
80
81 /* When non-zero, print basic high level tracing messages.
82    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
83 static int dwarf2_read_debug = 0;
84
85 /* When non-zero, dump DIEs after they are read in.  */
86 static unsigned int dwarf2_die_debug = 0;
87
88 /* When non-zero, cross-check physname against demangler.  */
89 static int check_physname = 0;
90
91 /* When non-zero, do not reject deprecated .gdb_index sections.  */
92 static int use_deprecated_index_sections = 0;
93
94 static const struct objfile_data *dwarf2_objfile_data_key;
95
96 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
97
98 static int dwarf2_locexpr_index;
99 static int dwarf2_loclist_index;
100 static int dwarf2_locexpr_block_index;
101 static int dwarf2_loclist_block_index;
102
103 struct dwarf2_section_info
104 {
105   asection *asection;
106   const gdb_byte *buffer;
107   bfd_size_type size;
108   /* True if we have tried to read this section.  */
109   int readin;
110 };
111
112 typedef struct dwarf2_section_info dwarf2_section_info_def;
113 DEF_VEC_O (dwarf2_section_info_def);
114
115 /* All offsets in the index are of this type.  It must be
116    architecture-independent.  */
117 typedef uint32_t offset_type;
118
119 DEF_VEC_I (offset_type);
120
121 /* Ensure only legit values are used.  */
122 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
123   do { \
124     gdb_assert ((unsigned int) (value) <= 1); \
125     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
126   } while (0)
127
128 /* Ensure only legit values are used.  */
129 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
130   do { \
131     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
132                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
133     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
134   } while (0)
135
136 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
137 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
138   do { \
139     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
140     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
141   } while (0)
142
143 /* A description of the mapped index.  The file format is described in
144    a comment by the code that writes the index.  */
145 struct mapped_index
146 {
147   /* Index data format version.  */
148   int version;
149
150   /* The total length of the buffer.  */
151   off_t total_size;
152
153   /* A pointer to the address table data.  */
154   const gdb_byte *address_table;
155
156   /* Size of the address table data in bytes.  */
157   offset_type address_table_size;
158
159   /* The symbol table, implemented as a hash table.  */
160   const offset_type *symbol_table;
161
162   /* Size in slots, each slot is 2 offset_types.  */
163   offset_type symbol_table_slots;
164
165   /* A pointer to the constant pool.  */
166   const char *constant_pool;
167 };
168
169 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
170 DEF_VEC_P (dwarf2_per_cu_ptr);
171
172 /* Collection of data recorded per objfile.
173    This hangs off of dwarf2_objfile_data_key.  */
174
175 struct dwarf2_per_objfile
176 {
177   struct dwarf2_section_info info;
178   struct dwarf2_section_info abbrev;
179   struct dwarf2_section_info line;
180   struct dwarf2_section_info loc;
181   struct dwarf2_section_info macinfo;
182   struct dwarf2_section_info macro;
183   struct dwarf2_section_info str;
184   struct dwarf2_section_info ranges;
185   struct dwarf2_section_info addr;
186   struct dwarf2_section_info frame;
187   struct dwarf2_section_info eh_frame;
188   struct dwarf2_section_info gdb_index;
189
190   VEC (dwarf2_section_info_def) *types;
191
192   /* Back link.  */
193   struct objfile *objfile;
194
195   /* Table of all the compilation units.  This is used to locate
196      the target compilation unit of a particular reference.  */
197   struct dwarf2_per_cu_data **all_comp_units;
198
199   /* The number of compilation units in ALL_COMP_UNITS.  */
200   int n_comp_units;
201
202   /* The number of .debug_types-related CUs.  */
203   int n_type_units;
204
205   /* The .debug_types-related CUs (TUs).
206      This is stored in malloc space because we may realloc it.  */
207   struct signatured_type **all_type_units;
208
209   /* The number of entries in all_type_unit_groups.  */
210   int n_type_unit_groups;
211
212   /* Table of type unit groups.
213      This exists to make it easy to iterate over all CUs and TU groups.  */
214   struct type_unit_group **all_type_unit_groups;
215
216   /* Table of struct type_unit_group objects.
217      The hash key is the DW_AT_stmt_list value.  */
218   htab_t type_unit_groups;
219
220   /* A table mapping .debug_types signatures to its signatured_type entry.
221      This is NULL if the .debug_types section hasn't been read in yet.  */
222   htab_t signatured_types;
223
224   /* Type unit statistics, to see how well the scaling improvements
225      are doing.  */
226   struct tu_stats
227   {
228     int nr_uniq_abbrev_tables;
229     int nr_symtabs;
230     int nr_symtab_sharers;
231     int nr_stmt_less_type_units;
232   } tu_stats;
233
234   /* A chain of compilation units that are currently read in, so that
235      they can be freed later.  */
236   struct dwarf2_per_cu_data *read_in_chain;
237
238   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
239      This is NULL if the table hasn't been allocated yet.  */
240   htab_t dwo_files;
241
242   /* Non-zero if we've check for whether there is a DWP file.  */
243   int dwp_checked;
244
245   /* The DWP file if there is one, or NULL.  */
246   struct dwp_file *dwp_file;
247
248   /* The shared '.dwz' file, if one exists.  This is used when the
249      original data was compressed using 'dwz -m'.  */
250   struct dwz_file *dwz_file;
251
252   /* A flag indicating wether this objfile has a section loaded at a
253      VMA of 0.  */
254   int has_section_at_zero;
255
256   /* True if we are using the mapped index,
257      or we are faking it for OBJF_READNOW's sake.  */
258   unsigned char using_index;
259
260   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
261   struct mapped_index *index_table;
262
263   /* When using index_table, this keeps track of all quick_file_names entries.
264      TUs typically share line table entries with a CU, so we maintain a
265      separate table of all line table entries to support the sharing.
266      Note that while there can be way more TUs than CUs, we've already
267      sorted all the TUs into "type unit groups", grouped by their
268      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
269      CU and its associated TU group if there is one.  */
270   htab_t quick_file_names_table;
271
272   /* Set during partial symbol reading, to prevent queueing of full
273      symbols.  */
274   int reading_partial_symbols;
275
276   /* Table mapping type DIEs to their struct type *.
277      This is NULL if not allocated yet.
278      The mapping is done via (CU/TU + DIE offset) -> type.  */
279   htab_t die_type_hash;
280
281   /* The CUs we recently read.  */
282   VEC (dwarf2_per_cu_ptr) *just_read_cus;
283 };
284
285 static struct dwarf2_per_objfile *dwarf2_per_objfile;
286
287 /* Default names of the debugging sections.  */
288
289 /* Note that if the debugging section has been compressed, it might
290    have a name like .zdebug_info.  */
291
292 static const struct dwarf2_debug_sections dwarf2_elf_names =
293 {
294   { ".debug_info", ".zdebug_info" },
295   { ".debug_abbrev", ".zdebug_abbrev" },
296   { ".debug_line", ".zdebug_line" },
297   { ".debug_loc", ".zdebug_loc" },
298   { ".debug_macinfo", ".zdebug_macinfo" },
299   { ".debug_macro", ".zdebug_macro" },
300   { ".debug_str", ".zdebug_str" },
301   { ".debug_ranges", ".zdebug_ranges" },
302   { ".debug_types", ".zdebug_types" },
303   { ".debug_addr", ".zdebug_addr" },
304   { ".debug_frame", ".zdebug_frame" },
305   { ".eh_frame", NULL },
306   { ".gdb_index", ".zgdb_index" },
307   23
308 };
309
310 /* List of DWO/DWP sections.  */
311
312 static const struct dwop_section_names
313 {
314   struct dwarf2_section_names abbrev_dwo;
315   struct dwarf2_section_names info_dwo;
316   struct dwarf2_section_names line_dwo;
317   struct dwarf2_section_names loc_dwo;
318   struct dwarf2_section_names macinfo_dwo;
319   struct dwarf2_section_names macro_dwo;
320   struct dwarf2_section_names str_dwo;
321   struct dwarf2_section_names str_offsets_dwo;
322   struct dwarf2_section_names types_dwo;
323   struct dwarf2_section_names cu_index;
324   struct dwarf2_section_names tu_index;
325 }
326 dwop_section_names =
327 {
328   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
329   { ".debug_info.dwo", ".zdebug_info.dwo" },
330   { ".debug_line.dwo", ".zdebug_line.dwo" },
331   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
332   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
333   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
334   { ".debug_str.dwo", ".zdebug_str.dwo" },
335   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
336   { ".debug_types.dwo", ".zdebug_types.dwo" },
337   { ".debug_cu_index", ".zdebug_cu_index" },
338   { ".debug_tu_index", ".zdebug_tu_index" },
339 };
340
341 /* local data types */
342
343 /* The data in a compilation unit header, after target2host
344    translation, looks like this.  */
345 struct comp_unit_head
346 {
347   unsigned int length;
348   short version;
349   unsigned char addr_size;
350   unsigned char signed_addr_p;
351   sect_offset abbrev_offset;
352
353   /* Size of file offsets; either 4 or 8.  */
354   unsigned int offset_size;
355
356   /* Size of the length field; either 4 or 12.  */
357   unsigned int initial_length_size;
358
359   /* Offset to the first byte of this compilation unit header in the
360      .debug_info section, for resolving relative reference dies.  */
361   sect_offset offset;
362
363   /* Offset to first die in this cu from the start of the cu.
364      This will be the first byte following the compilation unit header.  */
365   cu_offset first_die_offset;
366 };
367
368 /* Type used for delaying computation of method physnames.
369    See comments for compute_delayed_physnames.  */
370 struct delayed_method_info
371 {
372   /* The type to which the method is attached, i.e., its parent class.  */
373   struct type *type;
374
375   /* The index of the method in the type's function fieldlists.  */
376   int fnfield_index;
377
378   /* The index of the method in the fieldlist.  */
379   int index;
380
381   /* The name of the DIE.  */
382   const char *name;
383
384   /*  The DIE associated with this method.  */
385   struct die_info *die;
386 };
387
388 typedef struct delayed_method_info delayed_method_info;
389 DEF_VEC_O (delayed_method_info);
390
391 /* Internal state when decoding a particular compilation unit.  */
392 struct dwarf2_cu
393 {
394   /* The objfile containing this compilation unit.  */
395   struct objfile *objfile;
396
397   /* The header of the compilation unit.  */
398   struct comp_unit_head header;
399
400   /* Base address of this compilation unit.  */
401   CORE_ADDR base_address;
402
403   /* Non-zero if base_address has been set.  */
404   int base_known;
405
406   /* The language we are debugging.  */
407   enum language language;
408   const struct language_defn *language_defn;
409
410   const char *producer;
411
412   /* The generic symbol table building routines have separate lists for
413      file scope symbols and all all other scopes (local scopes).  So
414      we need to select the right one to pass to add_symbol_to_list().
415      We do it by keeping a pointer to the correct list in list_in_scope.
416
417      FIXME: The original dwarf code just treated the file scope as the
418      first local scope, and all other local scopes as nested local
419      scopes, and worked fine.  Check to see if we really need to
420      distinguish these in buildsym.c.  */
421   struct pending **list_in_scope;
422
423   /* The abbrev table for this CU.
424      Normally this points to the abbrev table in the objfile.
425      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
426   struct abbrev_table *abbrev_table;
427
428   /* Hash table holding all the loaded partial DIEs
429      with partial_die->offset.SECT_OFF as hash.  */
430   htab_t partial_dies;
431
432   /* Storage for things with the same lifetime as this read-in compilation
433      unit, including partial DIEs.  */
434   struct obstack comp_unit_obstack;
435
436   /* When multiple dwarf2_cu structures are living in memory, this field
437      chains them all together, so that they can be released efficiently.
438      We will probably also want a generation counter so that most-recently-used
439      compilation units are cached...  */
440   struct dwarf2_per_cu_data *read_in_chain;
441
442   /* Backchain to our per_cu entry if the tree has been built.  */
443   struct dwarf2_per_cu_data *per_cu;
444
445   /* How many compilation units ago was this CU last referenced?  */
446   int last_used;
447
448   /* A hash table of DIE cu_offset for following references with
449      die_info->offset.sect_off as hash.  */
450   htab_t die_hash;
451
452   /* Full DIEs if read in.  */
453   struct die_info *dies;
454
455   /* A set of pointers to dwarf2_per_cu_data objects for compilation
456      units referenced by this one.  Only set during full symbol processing;
457      partial symbol tables do not have dependencies.  */
458   htab_t dependencies;
459
460   /* Header data from the line table, during full symbol processing.  */
461   struct line_header *line_header;
462
463   /* A list of methods which need to have physnames computed
464      after all type information has been read.  */
465   VEC (delayed_method_info) *method_list;
466
467   /* To be copied to symtab->call_site_htab.  */
468   htab_t call_site_htab;
469
470   /* Non-NULL if this CU came from a DWO file.
471      There is an invariant here that is important to remember:
472      Except for attributes copied from the top level DIE in the "main"
473      (or "stub") file in preparation for reading the DWO file
474      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
475      Either there isn't a DWO file (in which case this is NULL and the point
476      is moot), or there is and either we're not going to read it (in which
477      case this is NULL) or there is and we are reading it (in which case this
478      is non-NULL).  */
479   struct dwo_unit *dwo_unit;
480
481   /* The DW_AT_addr_base attribute if present, zero otherwise
482      (zero is a valid value though).
483      Note this value comes from the stub CU/TU's DIE.  */
484   ULONGEST addr_base;
485
486   /* The DW_AT_ranges_base attribute if present, zero otherwise
487      (zero is a valid value though).
488      Note this value comes from the stub CU/TU's DIE.
489      Also note that the value is zero in the non-DWO case so this value can
490      be used without needing to know whether DWO files are in use or not.
491      N.B. This does not apply to DW_AT_ranges appearing in
492      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
493      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
494      DW_AT_ranges_base *would* have to be applied, and we'd have to care
495      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
496   ULONGEST ranges_base;
497
498   /* Mark used when releasing cached dies.  */
499   unsigned int mark : 1;
500
501   /* This CU references .debug_loc.  See the symtab->locations_valid field.
502      This test is imperfect as there may exist optimized debug code not using
503      any location list and still facing inlining issues if handled as
504      unoptimized code.  For a future better test see GCC PR other/32998.  */
505   unsigned int has_loclist : 1;
506
507   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
508      if all the producer_is_* fields are valid.  This information is cached
509      because profiling CU expansion showed excessive time spent in
510      producer_is_gxx_lt_4_6.  */
511   unsigned int checked_producer : 1;
512   unsigned int producer_is_gxx_lt_4_6 : 1;
513   unsigned int producer_is_gcc_lt_4_3 : 1;
514   unsigned int producer_is_icc : 1;
515
516   /* When set, the file that we're processing is known to have
517      debugging info for C++ namespaces.  GCC 3.3.x did not produce
518      this information, but later versions do.  */
519
520   unsigned int processing_has_namespace_info : 1;
521 };
522
523 /* Persistent data held for a compilation unit, even when not
524    processing it.  We put a pointer to this structure in the
525    read_symtab_private field of the psymtab.  */
526
527 struct dwarf2_per_cu_data
528 {
529   /* The start offset and length of this compilation unit.
530      NOTE: Unlike comp_unit_head.length, this length includes
531      initial_length_size.
532      If the DIE refers to a DWO file, this is always of the original die,
533      not the DWO file.  */
534   sect_offset offset;
535   unsigned int length;
536
537   /* Flag indicating this compilation unit will be read in before
538      any of the current compilation units are processed.  */
539   unsigned int queued : 1;
540
541   /* This flag will be set when reading partial DIEs if we need to load
542      absolutely all DIEs for this compilation unit, instead of just the ones
543      we think are interesting.  It gets set if we look for a DIE in the
544      hash table and don't find it.  */
545   unsigned int load_all_dies : 1;
546
547   /* Non-zero if this CU is from .debug_types.
548      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
549      this is non-zero.  */
550   unsigned int is_debug_types : 1;
551
552   /* Non-zero if this CU is from the .dwz file.  */
553   unsigned int is_dwz : 1;
554
555   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
556      This flag is only valid if is_debug_types is true.
557      We can't read a CU directly from a DWO file: There are required
558      attributes in the stub.  */
559   unsigned int reading_dwo_directly : 1;
560
561   /* The section this CU/TU lives in.
562      If the DIE refers to a DWO file, this is always the original die,
563      not the DWO file.  */
564   struct dwarf2_section_info *section;
565
566   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
567      of the CU cache it gets reset to NULL again.  */
568   struct dwarf2_cu *cu;
569
570   /* The corresponding objfile.
571      Normally we can get the objfile from dwarf2_per_objfile.
572      However we can enter this file with just a "per_cu" handle.  */
573   struct objfile *objfile;
574
575   /* When using partial symbol tables, the 'psymtab' field is active.
576      Otherwise the 'quick' field is active.  */
577   union
578   {
579     /* The partial symbol table associated with this compilation unit,
580        or NULL for unread partial units.  */
581     struct partial_symtab *psymtab;
582
583     /* Data needed by the "quick" functions.  */
584     struct dwarf2_per_cu_quick_data *quick;
585   } v;
586
587   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
588      while reading psymtabs, used to compute the psymtab dependencies,
589      and then cleared.  Then it is filled in again while reading full
590      symbols, and only deleted when the objfile is destroyed.
591
592      This is also used to work around a difference between the way gold
593      generates .gdb_index version <=7 and the way gdb does.  Arguably this
594      is a gold bug.  For symbols coming from TUs, gold records in the index
595      the CU that includes the TU instead of the TU itself.  This breaks
596      dw2_lookup_symbol: It assumes that if the index says symbol X lives
597      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
598      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
599      we need to look in TU Z to find X.  Fortunately, this is akin to
600      DW_TAG_imported_unit, so we just use the same mechanism: For
601      .gdb_index version <=7 this also records the TUs that the CU referred
602      to.  Concurrently with this change gdb was modified to emit version 8
603      indices so we only pay a price for gold generated indices.  */
604   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
605 };
606
607 /* Entry in the signatured_types hash table.  */
608
609 struct signatured_type
610 {
611   /* The "per_cu" object of this type.
612      This struct is used iff per_cu.is_debug_types.
613      N.B.: This is the first member so that it's easy to convert pointers
614      between them.  */
615   struct dwarf2_per_cu_data per_cu;
616
617   /* The type's signature.  */
618   ULONGEST signature;
619
620   /* Offset in the TU of the type's DIE, as read from the TU header.
621      If this TU is a DWO stub and the definition lives in a DWO file
622      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
623   cu_offset type_offset_in_tu;
624
625   /* Offset in the section of the type's DIE.
626      If the definition lives in a DWO file, this is the offset in the
627      .debug_types.dwo section.
628      The value is zero until the actual value is known.
629      Zero is otherwise not a valid section offset.  */
630   sect_offset type_offset_in_section;
631
632   /* Type units are grouped by their DW_AT_stmt_list entry so that they
633      can share them.  This points to the containing symtab.  */
634   struct type_unit_group *type_unit_group;
635
636   /* The type.
637      The first time we encounter this type we fully read it in and install it
638      in the symbol tables.  Subsequent times we only need the type.  */
639   struct type *type;
640
641   /* Containing DWO unit.
642      This field is valid iff per_cu.reading_dwo_directly.  */
643   struct dwo_unit *dwo_unit;
644 };
645
646 typedef struct signatured_type *sig_type_ptr;
647 DEF_VEC_P (sig_type_ptr);
648
649 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
650    This includes type_unit_group and quick_file_names.  */
651
652 struct stmt_list_hash
653 {
654   /* The DWO unit this table is from or NULL if there is none.  */
655   struct dwo_unit *dwo_unit;
656
657   /* Offset in .debug_line or .debug_line.dwo.  */
658   sect_offset line_offset;
659 };
660
661 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
662    an object of this type.  */
663
664 struct type_unit_group
665 {
666   /* dwarf2read.c's main "handle" on a TU symtab.
667      To simplify things we create an artificial CU that "includes" all the
668      type units using this stmt_list so that the rest of the code still has
669      a "per_cu" handle on the symtab.
670      This PER_CU is recognized by having no section.  */
671 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
672   struct dwarf2_per_cu_data per_cu;
673
674   /* The TUs that share this DW_AT_stmt_list entry.
675      This is added to while parsing type units to build partial symtabs,
676      and is deleted afterwards and not used again.  */
677   VEC (sig_type_ptr) *tus;
678
679   /* The primary symtab.
680      Type units in a group needn't all be defined in the same source file,
681      so we create an essentially anonymous symtab as the primary symtab.  */
682   struct symtab *primary_symtab;
683
684   /* The data used to construct the hash key.  */
685   struct stmt_list_hash hash;
686
687   /* The number of symtabs from the line header.
688      The value here must match line_header.num_file_names.  */
689   unsigned int num_symtabs;
690
691   /* The symbol tables for this TU (obtained from the files listed in
692      DW_AT_stmt_list).
693      WARNING: The order of entries here must match the order of entries
694      in the line header.  After the first TU using this type_unit_group, the
695      line header for the subsequent TUs is recreated from this.  This is done
696      because we need to use the same symtabs for each TU using the same
697      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
698      there's no guarantee the line header doesn't have duplicate entries.  */
699   struct symtab **symtabs;
700 };
701
702 /* These sections are what may appear in a DWO file.  */
703
704 struct dwo_sections
705 {
706   struct dwarf2_section_info abbrev;
707   struct dwarf2_section_info line;
708   struct dwarf2_section_info loc;
709   struct dwarf2_section_info macinfo;
710   struct dwarf2_section_info macro;
711   struct dwarf2_section_info str;
712   struct dwarf2_section_info str_offsets;
713   /* In the case of a virtual DWO file, these two are unused.  */
714   struct dwarf2_section_info info;
715   VEC (dwarf2_section_info_def) *types;
716 };
717
718 /* CUs/TUs in DWP/DWO files.  */
719
720 struct dwo_unit
721 {
722   /* Backlink to the containing struct dwo_file.  */
723   struct dwo_file *dwo_file;
724
725   /* The "id" that distinguishes this CU/TU.
726      .debug_info calls this "dwo_id", .debug_types calls this "signature".
727      Since signatures came first, we stick with it for consistency.  */
728   ULONGEST signature;
729
730   /* The section this CU/TU lives in, in the DWO file.  */
731   struct dwarf2_section_info *section;
732
733   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
734   sect_offset offset;
735   unsigned int length;
736
737   /* For types, offset in the type's DIE of the type defined by this TU.  */
738   cu_offset type_offset_in_tu;
739 };
740
741 /* Data for one DWO file.
742    This includes virtual DWO files that have been packaged into a
743    DWP file.  */
744
745 struct dwo_file
746 {
747   /* The DW_AT_GNU_dwo_name attribute.
748      For virtual DWO files the name is constructed from the section offsets
749      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
750      from related CU+TUs.  */
751   const char *dwo_name;
752
753   /* The DW_AT_comp_dir attribute.  */
754   const char *comp_dir;
755
756   /* The bfd, when the file is open.  Otherwise this is NULL.
757      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
758   bfd *dbfd;
759
760   /* Section info for this file.  */
761   struct dwo_sections sections;
762
763   /* The CU in the file.
764      We only support one because having more than one requires hacking the
765      dwo_name of each to match, which is highly unlikely to happen.
766      Doing this means all TUs can share comp_dir: We also assume that
767      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
768   struct dwo_unit *cu;
769
770   /* Table of TUs in the file.
771      Each element is a struct dwo_unit.  */
772   htab_t tus;
773 };
774
775 /* These sections are what may appear in a DWP file.  */
776
777 struct dwp_sections
778 {
779   struct dwarf2_section_info str;
780   struct dwarf2_section_info cu_index;
781   struct dwarf2_section_info tu_index;
782   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
783      by section number.  We don't need to record them here.  */
784 };
785
786 /* These sections are what may appear in a virtual DWO file.  */
787
788 struct virtual_dwo_sections
789 {
790   struct dwarf2_section_info abbrev;
791   struct dwarf2_section_info line;
792   struct dwarf2_section_info loc;
793   struct dwarf2_section_info macinfo;
794   struct dwarf2_section_info macro;
795   struct dwarf2_section_info str_offsets;
796   /* Each DWP hash table entry records one CU or one TU.
797      That is recorded here, and copied to dwo_unit.section.  */
798   struct dwarf2_section_info info_or_types;
799 };
800
801 /* Contents of DWP hash tables.  */
802
803 struct dwp_hash_table
804 {
805   uint32_t nr_units, nr_slots;
806   const gdb_byte *hash_table, *unit_table, *section_pool;
807 };
808
809 /* Data for one DWP file.  */
810
811 struct dwp_file
812 {
813   /* Name of the file.  */
814   const char *name;
815
816   /* The bfd.  */
817   bfd *dbfd;
818
819   /* Section info for this file.  */
820   struct dwp_sections sections;
821
822   /* Table of CUs in the file. */
823   const struct dwp_hash_table *cus;
824
825   /* Table of TUs in the file.  */
826   const struct dwp_hash_table *tus;
827
828   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
829   htab_t loaded_cutus;
830
831   /* Table to map ELF section numbers to their sections.  */
832   unsigned int num_sections;
833   asection **elf_sections;
834 };
835
836 /* This represents a '.dwz' file.  */
837
838 struct dwz_file
839 {
840   /* A dwz file can only contain a few sections.  */
841   struct dwarf2_section_info abbrev;
842   struct dwarf2_section_info info;
843   struct dwarf2_section_info str;
844   struct dwarf2_section_info line;
845   struct dwarf2_section_info macro;
846   struct dwarf2_section_info gdb_index;
847
848   /* The dwz's BFD.  */
849   bfd *dwz_bfd;
850 };
851
852 /* Struct used to pass misc. parameters to read_die_and_children, et
853    al.  which are used for both .debug_info and .debug_types dies.
854    All parameters here are unchanging for the life of the call.  This
855    struct exists to abstract away the constant parameters of die reading.  */
856
857 struct die_reader_specs
858 {
859   /* die_section->asection->owner.  */
860   bfd* abfd;
861
862   /* The CU of the DIE we are parsing.  */
863   struct dwarf2_cu *cu;
864
865   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
866   struct dwo_file *dwo_file;
867
868   /* The section the die comes from.
869      This is either .debug_info or .debug_types, or the .dwo variants.  */
870   struct dwarf2_section_info *die_section;
871
872   /* die_section->buffer.  */
873   const gdb_byte *buffer;
874
875   /* The end of the buffer.  */
876   const gdb_byte *buffer_end;
877
878   /* The value of the DW_AT_comp_dir attribute.  */
879   const char *comp_dir;
880 };
881
882 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
883 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
884                                       const gdb_byte *info_ptr,
885                                       struct die_info *comp_unit_die,
886                                       int has_children,
887                                       void *data);
888
889 /* The line number information for a compilation unit (found in the
890    .debug_line section) begins with a "statement program header",
891    which contains the following information.  */
892 struct line_header
893 {
894   unsigned int total_length;
895   unsigned short version;
896   unsigned int header_length;
897   unsigned char minimum_instruction_length;
898   unsigned char maximum_ops_per_instruction;
899   unsigned char default_is_stmt;
900   int line_base;
901   unsigned char line_range;
902   unsigned char opcode_base;
903
904   /* standard_opcode_lengths[i] is the number of operands for the
905      standard opcode whose value is i.  This means that
906      standard_opcode_lengths[0] is unused, and the last meaningful
907      element is standard_opcode_lengths[opcode_base - 1].  */
908   unsigned char *standard_opcode_lengths;
909
910   /* The include_directories table.  NOTE!  These strings are not
911      allocated with xmalloc; instead, they are pointers into
912      debug_line_buffer.  If you try to free them, `free' will get
913      indigestion.  */
914   unsigned int num_include_dirs, include_dirs_size;
915   const char **include_dirs;
916
917   /* The file_names table.  NOTE!  These strings are not allocated
918      with xmalloc; instead, they are pointers into debug_line_buffer.
919      Don't try to free them directly.  */
920   unsigned int num_file_names, file_names_size;
921   struct file_entry
922   {
923     const char *name;
924     unsigned int dir_index;
925     unsigned int mod_time;
926     unsigned int length;
927     int included_p; /* Non-zero if referenced by the Line Number Program.  */
928     struct symtab *symtab; /* The associated symbol table, if any.  */
929   } *file_names;
930
931   /* The start and end of the statement program following this
932      header.  These point into dwarf2_per_objfile->line_buffer.  */
933   const gdb_byte *statement_program_start, *statement_program_end;
934 };
935
936 /* When we construct a partial symbol table entry we only
937    need this much information.  */
938 struct partial_die_info
939   {
940     /* Offset of this DIE.  */
941     sect_offset offset;
942
943     /* DWARF-2 tag for this DIE.  */
944     ENUM_BITFIELD(dwarf_tag) tag : 16;
945
946     /* Assorted flags describing the data found in this DIE.  */
947     unsigned int has_children : 1;
948     unsigned int is_external : 1;
949     unsigned int is_declaration : 1;
950     unsigned int has_type : 1;
951     unsigned int has_specification : 1;
952     unsigned int has_pc_info : 1;
953     unsigned int may_be_inlined : 1;
954
955     /* Flag set if the SCOPE field of this structure has been
956        computed.  */
957     unsigned int scope_set : 1;
958
959     /* Flag set if the DIE has a byte_size attribute.  */
960     unsigned int has_byte_size : 1;
961
962     /* Flag set if any of the DIE's children are template arguments.  */
963     unsigned int has_template_arguments : 1;
964
965     /* Flag set if fixup_partial_die has been called on this die.  */
966     unsigned int fixup_called : 1;
967
968     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
969     unsigned int is_dwz : 1;
970
971     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
972     unsigned int spec_is_dwz : 1;
973
974     /* The name of this DIE.  Normally the value of DW_AT_name, but
975        sometimes a default name for unnamed DIEs.  */
976     const char *name;
977
978     /* The linkage name, if present.  */
979     const char *linkage_name;
980
981     /* The scope to prepend to our children.  This is generally
982        allocated on the comp_unit_obstack, so will disappear
983        when this compilation unit leaves the cache.  */
984     const char *scope;
985
986     /* Some data associated with the partial DIE.  The tag determines
987        which field is live.  */
988     union
989     {
990       /* The location description associated with this DIE, if any.  */
991       struct dwarf_block *locdesc;
992       /* The offset of an import, for DW_TAG_imported_unit.  */
993       sect_offset offset;
994     } d;
995
996     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
997     CORE_ADDR lowpc;
998     CORE_ADDR highpc;
999
1000     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1001        DW_AT_sibling, if any.  */
1002     /* NOTE: This member isn't strictly necessary, read_partial_die could
1003        return DW_AT_sibling values to its caller load_partial_dies.  */
1004     const gdb_byte *sibling;
1005
1006     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1007        DW_AT_specification (or DW_AT_abstract_origin or
1008        DW_AT_extension).  */
1009     sect_offset spec_offset;
1010
1011     /* Pointers to this DIE's parent, first child, and next sibling,
1012        if any.  */
1013     struct partial_die_info *die_parent, *die_child, *die_sibling;
1014   };
1015
1016 /* This data structure holds the information of an abbrev.  */
1017 struct abbrev_info
1018   {
1019     unsigned int number;        /* number identifying abbrev */
1020     enum dwarf_tag tag;         /* dwarf tag */
1021     unsigned short has_children;                /* boolean */
1022     unsigned short num_attrs;   /* number of attributes */
1023     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1024     struct abbrev_info *next;   /* next in chain */
1025   };
1026
1027 struct attr_abbrev
1028   {
1029     ENUM_BITFIELD(dwarf_attribute) name : 16;
1030     ENUM_BITFIELD(dwarf_form) form : 16;
1031   };
1032
1033 /* Size of abbrev_table.abbrev_hash_table.  */
1034 #define ABBREV_HASH_SIZE 121
1035
1036 /* Top level data structure to contain an abbreviation table.  */
1037
1038 struct abbrev_table
1039 {
1040   /* Where the abbrev table came from.
1041      This is used as a sanity check when the table is used.  */
1042   sect_offset offset;
1043
1044   /* Storage for the abbrev table.  */
1045   struct obstack abbrev_obstack;
1046
1047   /* Hash table of abbrevs.
1048      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1049      It could be statically allocated, but the previous code didn't so we
1050      don't either.  */
1051   struct abbrev_info **abbrevs;
1052 };
1053
1054 /* Attributes have a name and a value.  */
1055 struct attribute
1056   {
1057     ENUM_BITFIELD(dwarf_attribute) name : 16;
1058     ENUM_BITFIELD(dwarf_form) form : 15;
1059
1060     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1061        field should be in u.str (existing only for DW_STRING) but it is kept
1062        here for better struct attribute alignment.  */
1063     unsigned int string_is_canonical : 1;
1064
1065     union
1066       {
1067         const char *str;
1068         struct dwarf_block *blk;
1069         ULONGEST unsnd;
1070         LONGEST snd;
1071         CORE_ADDR addr;
1072         ULONGEST signature;
1073       }
1074     u;
1075   };
1076
1077 /* This data structure holds a complete die structure.  */
1078 struct die_info
1079   {
1080     /* DWARF-2 tag for this DIE.  */
1081     ENUM_BITFIELD(dwarf_tag) tag : 16;
1082
1083     /* Number of attributes */
1084     unsigned char num_attrs;
1085
1086     /* True if we're presently building the full type name for the
1087        type derived from this DIE.  */
1088     unsigned char building_fullname : 1;
1089
1090     /* Abbrev number */
1091     unsigned int abbrev;
1092
1093     /* Offset in .debug_info or .debug_types section.  */
1094     sect_offset offset;
1095
1096     /* The dies in a compilation unit form an n-ary tree.  PARENT
1097        points to this die's parent; CHILD points to the first child of
1098        this node; and all the children of a given node are chained
1099        together via their SIBLING fields.  */
1100     struct die_info *child;     /* Its first child, if any.  */
1101     struct die_info *sibling;   /* Its next sibling, if any.  */
1102     struct die_info *parent;    /* Its parent, if any.  */
1103
1104     /* An array of attributes, with NUM_ATTRS elements.  There may be
1105        zero, but it's not common and zero-sized arrays are not
1106        sufficiently portable C.  */
1107     struct attribute attrs[1];
1108   };
1109
1110 /* Get at parts of an attribute structure.  */
1111
1112 #define DW_STRING(attr)    ((attr)->u.str)
1113 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1114 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1115 #define DW_BLOCK(attr)     ((attr)->u.blk)
1116 #define DW_SND(attr)       ((attr)->u.snd)
1117 #define DW_ADDR(attr)      ((attr)->u.addr)
1118 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1119
1120 /* Blocks are a bunch of untyped bytes.  */
1121 struct dwarf_block
1122   {
1123     size_t size;
1124
1125     /* Valid only if SIZE is not zero.  */
1126     const gdb_byte *data;
1127   };
1128
1129 #ifndef ATTR_ALLOC_CHUNK
1130 #define ATTR_ALLOC_CHUNK 4
1131 #endif
1132
1133 /* Allocate fields for structs, unions and enums in this size.  */
1134 #ifndef DW_FIELD_ALLOC_CHUNK
1135 #define DW_FIELD_ALLOC_CHUNK 4
1136 #endif
1137
1138 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1139    but this would require a corresponding change in unpack_field_as_long
1140    and friends.  */
1141 static int bits_per_byte = 8;
1142
1143 /* The routines that read and process dies for a C struct or C++ class
1144    pass lists of data member fields and lists of member function fields
1145    in an instance of a field_info structure, as defined below.  */
1146 struct field_info
1147   {
1148     /* List of data member and baseclasses fields.  */
1149     struct nextfield
1150       {
1151         struct nextfield *next;
1152         int accessibility;
1153         int virtuality;
1154         struct field field;
1155       }
1156      *fields, *baseclasses;
1157
1158     /* Number of fields (including baseclasses).  */
1159     int nfields;
1160
1161     /* Number of baseclasses.  */
1162     int nbaseclasses;
1163
1164     /* Set if the accesibility of one of the fields is not public.  */
1165     int non_public_fields;
1166
1167     /* Member function fields array, entries are allocated in the order they
1168        are encountered in the object file.  */
1169     struct nextfnfield
1170       {
1171         struct nextfnfield *next;
1172         struct fn_field fnfield;
1173       }
1174      *fnfields;
1175
1176     /* Member function fieldlist array, contains name of possibly overloaded
1177        member function, number of overloaded member functions and a pointer
1178        to the head of the member function field chain.  */
1179     struct fnfieldlist
1180       {
1181         const char *name;
1182         int length;
1183         struct nextfnfield *head;
1184       }
1185      *fnfieldlists;
1186
1187     /* Number of entries in the fnfieldlists array.  */
1188     int nfnfields;
1189
1190     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1191        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1192     struct typedef_field_list
1193       {
1194         struct typedef_field field;
1195         struct typedef_field_list *next;
1196       }
1197     *typedef_field_list;
1198     unsigned typedef_field_list_count;
1199   };
1200
1201 /* One item on the queue of compilation units to read in full symbols
1202    for.  */
1203 struct dwarf2_queue_item
1204 {
1205   struct dwarf2_per_cu_data *per_cu;
1206   enum language pretend_language;
1207   struct dwarf2_queue_item *next;
1208 };
1209
1210 /* The current queue.  */
1211 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1212
1213 /* Loaded secondary compilation units are kept in memory until they
1214    have not been referenced for the processing of this many
1215    compilation units.  Set this to zero to disable caching.  Cache
1216    sizes of up to at least twenty will improve startup time for
1217    typical inter-CU-reference binaries, at an obvious memory cost.  */
1218 static int dwarf2_max_cache_age = 5;
1219 static void
1220 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1221                            struct cmd_list_element *c, const char *value)
1222 {
1223   fprintf_filtered (file, _("The upper bound on the age of cached "
1224                             "dwarf2 compilation units is %s.\n"),
1225                     value);
1226 }
1227
1228
1229 /* Various complaints about symbol reading that don't abort the process.  */
1230
1231 static void
1232 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1233 {
1234   complaint (&symfile_complaints,
1235              _("statement list doesn't fit in .debug_line section"));
1236 }
1237
1238 static void
1239 dwarf2_debug_line_missing_file_complaint (void)
1240 {
1241   complaint (&symfile_complaints,
1242              _(".debug_line section has line data without a file"));
1243 }
1244
1245 static void
1246 dwarf2_debug_line_missing_end_sequence_complaint (void)
1247 {
1248   complaint (&symfile_complaints,
1249              _(".debug_line section has line "
1250                "program sequence without an end"));
1251 }
1252
1253 static void
1254 dwarf2_complex_location_expr_complaint (void)
1255 {
1256   complaint (&symfile_complaints, _("location expression too complex"));
1257 }
1258
1259 static void
1260 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1261                                               int arg3)
1262 {
1263   complaint (&symfile_complaints,
1264              _("const value length mismatch for '%s', got %d, expected %d"),
1265              arg1, arg2, arg3);
1266 }
1267
1268 static void
1269 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1270 {
1271   complaint (&symfile_complaints,
1272              _("debug info runs off end of %s section"
1273                " [in module %s]"),
1274              section->asection->name,
1275              bfd_get_filename (section->asection->owner));
1276 }
1277
1278 static void
1279 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1280 {
1281   complaint (&symfile_complaints,
1282              _("macro debug info contains a "
1283                "malformed macro definition:\n`%s'"),
1284              arg1);
1285 }
1286
1287 static void
1288 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1289 {
1290   complaint (&symfile_complaints,
1291              _("invalid attribute class or form for '%s' in '%s'"),
1292              arg1, arg2);
1293 }
1294
1295 /* local function prototypes */
1296
1297 static void dwarf2_locate_sections (bfd *, asection *, void *);
1298
1299 static void dwarf2_find_base_address (struct die_info *die,
1300                                       struct dwarf2_cu *cu);
1301
1302 static struct partial_symtab *create_partial_symtab
1303   (struct dwarf2_per_cu_data *per_cu, const char *name);
1304
1305 static void dwarf2_build_psymtabs_hard (struct objfile *);
1306
1307 static void scan_partial_symbols (struct partial_die_info *,
1308                                   CORE_ADDR *, CORE_ADDR *,
1309                                   int, struct dwarf2_cu *);
1310
1311 static void add_partial_symbol (struct partial_die_info *,
1312                                 struct dwarf2_cu *);
1313
1314 static void add_partial_namespace (struct partial_die_info *pdi,
1315                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1316                                    int need_pc, struct dwarf2_cu *cu);
1317
1318 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1319                                 CORE_ADDR *highpc, int need_pc,
1320                                 struct dwarf2_cu *cu);
1321
1322 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1323                                      struct dwarf2_cu *cu);
1324
1325 static void add_partial_subprogram (struct partial_die_info *pdi,
1326                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1327                                     int need_pc, struct dwarf2_cu *cu);
1328
1329 static void dwarf2_read_symtab (struct partial_symtab *,
1330                                 struct objfile *);
1331
1332 static void psymtab_to_symtab_1 (struct partial_symtab *);
1333
1334 static struct abbrev_info *abbrev_table_lookup_abbrev
1335   (const struct abbrev_table *, unsigned int);
1336
1337 static struct abbrev_table *abbrev_table_read_table
1338   (struct dwarf2_section_info *, sect_offset);
1339
1340 static void abbrev_table_free (struct abbrev_table *);
1341
1342 static void abbrev_table_free_cleanup (void *);
1343
1344 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1345                                  struct dwarf2_section_info *);
1346
1347 static void dwarf2_free_abbrev_table (void *);
1348
1349 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1350
1351 static struct partial_die_info *load_partial_dies
1352   (const struct die_reader_specs *, const gdb_byte *, int);
1353
1354 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1355                                          struct partial_die_info *,
1356                                          struct abbrev_info *,
1357                                          unsigned int,
1358                                          const gdb_byte *);
1359
1360 static struct partial_die_info *find_partial_die (sect_offset, int,
1361                                                   struct dwarf2_cu *);
1362
1363 static void fixup_partial_die (struct partial_die_info *,
1364                                struct dwarf2_cu *);
1365
1366 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1367                                        struct attribute *, struct attr_abbrev *,
1368                                        const gdb_byte *);
1369
1370 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1371
1372 static int read_1_signed_byte (bfd *, const gdb_byte *);
1373
1374 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1375
1376 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1377
1378 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1379
1380 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1381                                unsigned int *);
1382
1383 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1384
1385 static LONGEST read_checked_initial_length_and_offset
1386   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1387    unsigned int *, unsigned int *);
1388
1389 static LONGEST read_offset (bfd *, const gdb_byte *,
1390                             const struct comp_unit_head *,
1391                             unsigned int *);
1392
1393 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1394
1395 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1396                                        sect_offset);
1397
1398 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1399
1400 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1401
1402 static const char *read_indirect_string (bfd *, const gdb_byte *,
1403                                          const struct comp_unit_head *,
1404                                          unsigned int *);
1405
1406 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1407
1408 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1409
1410 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1411
1412 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1413                                               const gdb_byte *,
1414                                               unsigned int *);
1415
1416 static const char *read_str_index (const struct die_reader_specs *reader,
1417                                    struct dwarf2_cu *cu, ULONGEST str_index);
1418
1419 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1420
1421 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1422                                       struct dwarf2_cu *);
1423
1424 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1425                                                 unsigned int);
1426
1427 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1428                                struct dwarf2_cu *cu);
1429
1430 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1431
1432 static struct die_info *die_specification (struct die_info *die,
1433                                            struct dwarf2_cu **);
1434
1435 static void free_line_header (struct line_header *lh);
1436
1437 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1438                                                      struct dwarf2_cu *cu);
1439
1440 static void dwarf_decode_lines (struct line_header *, const char *,
1441                                 struct dwarf2_cu *, struct partial_symtab *,
1442                                 int);
1443
1444 static void dwarf2_start_subfile (const char *, const char *, const char *);
1445
1446 static void dwarf2_start_symtab (struct dwarf2_cu *,
1447                                  const char *, const char *, CORE_ADDR);
1448
1449 static struct symbol *new_symbol (struct die_info *, struct type *,
1450                                   struct dwarf2_cu *);
1451
1452 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1453                                        struct dwarf2_cu *, struct symbol *);
1454
1455 static void dwarf2_const_value (struct attribute *, struct symbol *,
1456                                 struct dwarf2_cu *);
1457
1458 static void dwarf2_const_value_attr (struct attribute *attr,
1459                                      struct type *type,
1460                                      const char *name,
1461                                      struct obstack *obstack,
1462                                      struct dwarf2_cu *cu, LONGEST *value,
1463                                      const gdb_byte **bytes,
1464                                      struct dwarf2_locexpr_baton **baton);
1465
1466 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1467
1468 static int need_gnat_info (struct dwarf2_cu *);
1469
1470 static struct type *die_descriptive_type (struct die_info *,
1471                                           struct dwarf2_cu *);
1472
1473 static void set_descriptive_type (struct type *, struct die_info *,
1474                                   struct dwarf2_cu *);
1475
1476 static struct type *die_containing_type (struct die_info *,
1477                                          struct dwarf2_cu *);
1478
1479 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1480                                      struct dwarf2_cu *);
1481
1482 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1483
1484 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1485
1486 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1487
1488 static char *typename_concat (struct obstack *obs, const char *prefix,
1489                               const char *suffix, int physname,
1490                               struct dwarf2_cu *cu);
1491
1492 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1493
1494 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1495
1496 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1497
1498 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1499
1500 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1501
1502 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1503                                struct dwarf2_cu *, struct partial_symtab *);
1504
1505 static int dwarf2_get_pc_bounds (struct die_info *,
1506                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1507                                  struct partial_symtab *);
1508
1509 static void get_scope_pc_bounds (struct die_info *,
1510                                  CORE_ADDR *, CORE_ADDR *,
1511                                  struct dwarf2_cu *);
1512
1513 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1514                                         CORE_ADDR, struct dwarf2_cu *);
1515
1516 static void dwarf2_add_field (struct field_info *, struct die_info *,
1517                               struct dwarf2_cu *);
1518
1519 static void dwarf2_attach_fields_to_type (struct field_info *,
1520                                           struct type *, struct dwarf2_cu *);
1521
1522 static void dwarf2_add_member_fn (struct field_info *,
1523                                   struct die_info *, struct type *,
1524                                   struct dwarf2_cu *);
1525
1526 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1527                                              struct type *,
1528                                              struct dwarf2_cu *);
1529
1530 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1531
1532 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1533
1534 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1535
1536 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1537
1538 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1539
1540 static struct type *read_module_type (struct die_info *die,
1541                                       struct dwarf2_cu *cu);
1542
1543 static const char *namespace_name (struct die_info *die,
1544                                    int *is_anonymous, struct dwarf2_cu *);
1545
1546 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1547
1548 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1549
1550 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1551                                                        struct dwarf2_cu *);
1552
1553 static struct die_info *read_die_and_siblings_1
1554   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1555    struct die_info *);
1556
1557 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1558                                                const gdb_byte *info_ptr,
1559                                                const gdb_byte **new_info_ptr,
1560                                                struct die_info *parent);
1561
1562 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1563                                         struct die_info **, const gdb_byte *,
1564                                         int *, int);
1565
1566 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1567                                       struct die_info **, const gdb_byte *,
1568                                       int *);
1569
1570 static void process_die (struct die_info *, struct dwarf2_cu *);
1571
1572 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1573                                              struct obstack *);
1574
1575 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1576
1577 static const char *dwarf2_full_name (const char *name,
1578                                      struct die_info *die,
1579                                      struct dwarf2_cu *cu);
1580
1581 static const char *dwarf2_physname (const char *name, struct die_info *die,
1582                                     struct dwarf2_cu *cu);
1583
1584 static struct die_info *dwarf2_extension (struct die_info *die,
1585                                           struct dwarf2_cu **);
1586
1587 static const char *dwarf_tag_name (unsigned int);
1588
1589 static const char *dwarf_attr_name (unsigned int);
1590
1591 static const char *dwarf_form_name (unsigned int);
1592
1593 static char *dwarf_bool_name (unsigned int);
1594
1595 static const char *dwarf_type_encoding_name (unsigned int);
1596
1597 static struct die_info *sibling_die (struct die_info *);
1598
1599 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1600
1601 static void dump_die_for_error (struct die_info *);
1602
1603 static void dump_die_1 (struct ui_file *, int level, int max_level,
1604                         struct die_info *);
1605
1606 /*static*/ void dump_die (struct die_info *, int max_level);
1607
1608 static void store_in_ref_table (struct die_info *,
1609                                 struct dwarf2_cu *);
1610
1611 static int is_ref_attr (struct attribute *);
1612
1613 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1614
1615 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1616
1617 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1618                                                struct attribute *,
1619                                                struct dwarf2_cu **);
1620
1621 static struct die_info *follow_die_ref (struct die_info *,
1622                                         struct attribute *,
1623                                         struct dwarf2_cu **);
1624
1625 static struct die_info *follow_die_sig (struct die_info *,
1626                                         struct attribute *,
1627                                         struct dwarf2_cu **);
1628
1629 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1630                                          struct dwarf2_cu *);
1631
1632 static struct type *get_DW_AT_signature_type (struct die_info *,
1633                                               struct attribute *,
1634                                               struct dwarf2_cu *);
1635
1636 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1637
1638 static void read_signatured_type (struct signatured_type *);
1639
1640 static struct type_unit_group *get_type_unit_group
1641     (struct dwarf2_cu *, struct attribute *);
1642
1643 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1644
1645 /* memory allocation interface */
1646
1647 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1648
1649 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1650
1651 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1652                                  const char *, int);
1653
1654 static int attr_form_is_block (struct attribute *);
1655
1656 static int attr_form_is_section_offset (struct attribute *);
1657
1658 static int attr_form_is_constant (struct attribute *);
1659
1660 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1661                                    struct dwarf2_loclist_baton *baton,
1662                                    struct attribute *attr);
1663
1664 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1665                                          struct symbol *sym,
1666                                          struct dwarf2_cu *cu,
1667                                          int is_block);
1668
1669 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1670                                      const gdb_byte *info_ptr,
1671                                      struct abbrev_info *abbrev);
1672
1673 static void free_stack_comp_unit (void *);
1674
1675 static hashval_t partial_die_hash (const void *item);
1676
1677 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1678
1679 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1680   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1681
1682 static void init_one_comp_unit (struct dwarf2_cu *cu,
1683                                 struct dwarf2_per_cu_data *per_cu);
1684
1685 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1686                                    struct die_info *comp_unit_die,
1687                                    enum language pretend_language);
1688
1689 static void free_heap_comp_unit (void *);
1690
1691 static void free_cached_comp_units (void *);
1692
1693 static void age_cached_comp_units (void);
1694
1695 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1696
1697 static struct type *set_die_type (struct die_info *, struct type *,
1698                                   struct dwarf2_cu *);
1699
1700 static void create_all_comp_units (struct objfile *);
1701
1702 static int create_all_type_units (struct objfile *);
1703
1704 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1705                                  enum language);
1706
1707 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1708                                     enum language);
1709
1710 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1711                                     enum language);
1712
1713 static void dwarf2_add_dependence (struct dwarf2_cu *,
1714                                    struct dwarf2_per_cu_data *);
1715
1716 static void dwarf2_mark (struct dwarf2_cu *);
1717
1718 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1719
1720 static struct type *get_die_type_at_offset (sect_offset,
1721                                             struct dwarf2_per_cu_data *);
1722
1723 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1724
1725 static void dwarf2_release_queue (void *dummy);
1726
1727 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1728                              enum language pretend_language);
1729
1730 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1731                                   struct dwarf2_per_cu_data *per_cu,
1732                                   enum language pretend_language);
1733
1734 static void process_queue (void);
1735
1736 static void find_file_and_directory (struct die_info *die,
1737                                      struct dwarf2_cu *cu,
1738                                      const char **name, const char **comp_dir);
1739
1740 static char *file_full_name (int file, struct line_header *lh,
1741                              const char *comp_dir);
1742
1743 static const gdb_byte *read_and_check_comp_unit_head
1744   (struct comp_unit_head *header,
1745    struct dwarf2_section_info *section,
1746    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1747    int is_debug_types_section);
1748
1749 static void init_cutu_and_read_dies
1750   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1751    int use_existing_cu, int keep,
1752    die_reader_func_ftype *die_reader_func, void *data);
1753
1754 static void init_cutu_and_read_dies_simple
1755   (struct dwarf2_per_cu_data *this_cu,
1756    die_reader_func_ftype *die_reader_func, void *data);
1757
1758 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1759
1760 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1761
1762 static struct dwo_unit *lookup_dwo_in_dwp
1763   (struct dwp_file *dwp_file, const struct dwp_hash_table *htab,
1764    const char *comp_dir, ULONGEST signature, int is_debug_types);
1765
1766 static struct dwp_file *get_dwp_file (void);
1767
1768 static struct dwo_unit *lookup_dwo_comp_unit
1769   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1770
1771 static struct dwo_unit *lookup_dwo_type_unit
1772   (struct signatured_type *, const char *, const char *);
1773
1774 static void free_dwo_file_cleanup (void *);
1775
1776 static void process_cu_includes (void);
1777
1778 static void check_producer (struct dwarf2_cu *cu);
1779
1780 #if WORDS_BIGENDIAN
1781
1782 /* Convert VALUE between big- and little-endian.  */
1783 static offset_type
1784 byte_swap (offset_type value)
1785 {
1786   offset_type result;
1787
1788   result = (value & 0xff) << 24;
1789   result |= (value & 0xff00) << 8;
1790   result |= (value & 0xff0000) >> 8;
1791   result |= (value & 0xff000000) >> 24;
1792   return result;
1793 }
1794
1795 #define MAYBE_SWAP(V)  byte_swap (V)
1796
1797 #else
1798 #define MAYBE_SWAP(V) (V)
1799 #endif /* WORDS_BIGENDIAN */
1800
1801 /* The suffix for an index file.  */
1802 #define INDEX_SUFFIX ".gdb-index"
1803
1804 /* Try to locate the sections we need for DWARF 2 debugging
1805    information and return true if we have enough to do something.
1806    NAMES points to the dwarf2 section names, or is NULL if the standard
1807    ELF names are used.  */
1808
1809 int
1810 dwarf2_has_info (struct objfile *objfile,
1811                  const struct dwarf2_debug_sections *names)
1812 {
1813   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1814   if (!dwarf2_per_objfile)
1815     {
1816       /* Initialize per-objfile state.  */
1817       struct dwarf2_per_objfile *data
1818         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1819
1820       memset (data, 0, sizeof (*data));
1821       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1822       dwarf2_per_objfile = data;
1823
1824       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1825                              (void *) names);
1826       dwarf2_per_objfile->objfile = objfile;
1827     }
1828   return (dwarf2_per_objfile->info.asection != NULL
1829           && dwarf2_per_objfile->abbrev.asection != NULL);
1830 }
1831
1832 /* When loading sections, we look either for uncompressed section or for
1833    compressed section names.  */
1834
1835 static int
1836 section_is_p (const char *section_name,
1837               const struct dwarf2_section_names *names)
1838 {
1839   if (names->normal != NULL
1840       && strcmp (section_name, names->normal) == 0)
1841     return 1;
1842   if (names->compressed != NULL
1843       && strcmp (section_name, names->compressed) == 0)
1844     return 1;
1845   return 0;
1846 }
1847
1848 /* This function is mapped across the sections and remembers the
1849    offset and size of each of the debugging sections we are interested
1850    in.  */
1851
1852 static void
1853 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1854 {
1855   const struct dwarf2_debug_sections *names;
1856   flagword aflag = bfd_get_section_flags (abfd, sectp);
1857
1858   if (vnames == NULL)
1859     names = &dwarf2_elf_names;
1860   else
1861     names = (const struct dwarf2_debug_sections *) vnames;
1862
1863   if ((aflag & SEC_HAS_CONTENTS) == 0)
1864     {
1865     }
1866   else if (section_is_p (sectp->name, &names->info))
1867     {
1868       dwarf2_per_objfile->info.asection = sectp;
1869       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1870     }
1871   else if (section_is_p (sectp->name, &names->abbrev))
1872     {
1873       dwarf2_per_objfile->abbrev.asection = sectp;
1874       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1875     }
1876   else if (section_is_p (sectp->name, &names->line))
1877     {
1878       dwarf2_per_objfile->line.asection = sectp;
1879       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1880     }
1881   else if (section_is_p (sectp->name, &names->loc))
1882     {
1883       dwarf2_per_objfile->loc.asection = sectp;
1884       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1885     }
1886   else if (section_is_p (sectp->name, &names->macinfo))
1887     {
1888       dwarf2_per_objfile->macinfo.asection = sectp;
1889       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1890     }
1891   else if (section_is_p (sectp->name, &names->macro))
1892     {
1893       dwarf2_per_objfile->macro.asection = sectp;
1894       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1895     }
1896   else if (section_is_p (sectp->name, &names->str))
1897     {
1898       dwarf2_per_objfile->str.asection = sectp;
1899       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1900     }
1901   else if (section_is_p (sectp->name, &names->addr))
1902     {
1903       dwarf2_per_objfile->addr.asection = sectp;
1904       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1905     }
1906   else if (section_is_p (sectp->name, &names->frame))
1907     {
1908       dwarf2_per_objfile->frame.asection = sectp;
1909       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1910     }
1911   else if (section_is_p (sectp->name, &names->eh_frame))
1912     {
1913       dwarf2_per_objfile->eh_frame.asection = sectp;
1914       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1915     }
1916   else if (section_is_p (sectp->name, &names->ranges))
1917     {
1918       dwarf2_per_objfile->ranges.asection = sectp;
1919       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1920     }
1921   else if (section_is_p (sectp->name, &names->types))
1922     {
1923       struct dwarf2_section_info type_section;
1924
1925       memset (&type_section, 0, sizeof (type_section));
1926       type_section.asection = sectp;
1927       type_section.size = bfd_get_section_size (sectp);
1928
1929       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1930                      &type_section);
1931     }
1932   else if (section_is_p (sectp->name, &names->gdb_index))
1933     {
1934       dwarf2_per_objfile->gdb_index.asection = sectp;
1935       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1936     }
1937
1938   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1939       && bfd_section_vma (abfd, sectp) == 0)
1940     dwarf2_per_objfile->has_section_at_zero = 1;
1941 }
1942
1943 /* A helper function that decides whether a section is empty,
1944    or not present.  */
1945
1946 static int
1947 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1948 {
1949   return info->asection == NULL || info->size == 0;
1950 }
1951
1952 /* Read the contents of the section INFO.
1953    OBJFILE is the main object file, but not necessarily the file where
1954    the section comes from.  E.g., for DWO files INFO->asection->owner
1955    is the bfd of the DWO file.
1956    If the section is compressed, uncompress it before returning.  */
1957
1958 static void
1959 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1960 {
1961   asection *sectp = info->asection;
1962   bfd *abfd;
1963   gdb_byte *buf, *retbuf;
1964   unsigned char header[4];
1965
1966   if (info->readin)
1967     return;
1968   info->buffer = NULL;
1969   info->readin = 1;
1970
1971   if (dwarf2_section_empty_p (info))
1972     return;
1973
1974   abfd = sectp->owner;
1975
1976   /* If the section has relocations, we must read it ourselves.
1977      Otherwise we attach it to the BFD.  */
1978   if ((sectp->flags & SEC_RELOC) == 0)
1979     {
1980       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1981       return;
1982     }
1983
1984   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1985   info->buffer = buf;
1986
1987   /* When debugging .o files, we may need to apply relocations; see
1988      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1989      We never compress sections in .o files, so we only need to
1990      try this when the section is not compressed.  */
1991   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1992   if (retbuf != NULL)
1993     {
1994       info->buffer = retbuf;
1995       return;
1996     }
1997
1998   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1999       || bfd_bread (buf, info->size, abfd) != info->size)
2000     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
2001            bfd_get_filename (abfd));
2002 }
2003
2004 /* A helper function that returns the size of a section in a safe way.
2005    If you are positive that the section has been read before using the
2006    size, then it is safe to refer to the dwarf2_section_info object's
2007    "size" field directly.  In other cases, you must call this
2008    function, because for compressed sections the size field is not set
2009    correctly until the section has been read.  */
2010
2011 static bfd_size_type
2012 dwarf2_section_size (struct objfile *objfile,
2013                      struct dwarf2_section_info *info)
2014 {
2015   if (!info->readin)
2016     dwarf2_read_section (objfile, info);
2017   return info->size;
2018 }
2019
2020 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2021    SECTION_NAME.  */
2022
2023 void
2024 dwarf2_get_section_info (struct objfile *objfile,
2025                          enum dwarf2_section_enum sect,
2026                          asection **sectp, const gdb_byte **bufp,
2027                          bfd_size_type *sizep)
2028 {
2029   struct dwarf2_per_objfile *data
2030     = objfile_data (objfile, dwarf2_objfile_data_key);
2031   struct dwarf2_section_info *info;
2032
2033   /* We may see an objfile without any DWARF, in which case we just
2034      return nothing.  */
2035   if (data == NULL)
2036     {
2037       *sectp = NULL;
2038       *bufp = NULL;
2039       *sizep = 0;
2040       return;
2041     }
2042   switch (sect)
2043     {
2044     case DWARF2_DEBUG_FRAME:
2045       info = &data->frame;
2046       break;
2047     case DWARF2_EH_FRAME:
2048       info = &data->eh_frame;
2049       break;
2050     default:
2051       gdb_assert_not_reached ("unexpected section");
2052     }
2053
2054   dwarf2_read_section (objfile, info);
2055
2056   *sectp = info->asection;
2057   *bufp = info->buffer;
2058   *sizep = info->size;
2059 }
2060
2061 /* A helper function to find the sections for a .dwz file.  */
2062
2063 static void
2064 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2065 {
2066   struct dwz_file *dwz_file = arg;
2067
2068   /* Note that we only support the standard ELF names, because .dwz
2069      is ELF-only (at the time of writing).  */
2070   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2071     {
2072       dwz_file->abbrev.asection = sectp;
2073       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2074     }
2075   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2076     {
2077       dwz_file->info.asection = sectp;
2078       dwz_file->info.size = bfd_get_section_size (sectp);
2079     }
2080   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2081     {
2082       dwz_file->str.asection = sectp;
2083       dwz_file->str.size = bfd_get_section_size (sectp);
2084     }
2085   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2086     {
2087       dwz_file->line.asection = sectp;
2088       dwz_file->line.size = bfd_get_section_size (sectp);
2089     }
2090   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2091     {
2092       dwz_file->macro.asection = sectp;
2093       dwz_file->macro.size = bfd_get_section_size (sectp);
2094     }
2095   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2096     {
2097       dwz_file->gdb_index.asection = sectp;
2098       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2099     }
2100 }
2101
2102 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2103    cannot be found.  */
2104
2105 static struct dwz_file *
2106 dwarf2_get_dwz_file (void)
2107 {
2108   bfd *abfd, *dwz_bfd;
2109   asection *section;
2110   gdb_byte *data;
2111   struct cleanup *cleanup;
2112   const char *filename;
2113   struct dwz_file *result;
2114
2115   if (dwarf2_per_objfile->dwz_file != NULL)
2116     return dwarf2_per_objfile->dwz_file;
2117
2118   abfd = dwarf2_per_objfile->objfile->obfd;
2119   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2120   if (section == NULL)
2121     error (_("could not find '.gnu_debugaltlink' section"));
2122   if (!bfd_malloc_and_get_section (abfd, section, &data))
2123     error (_("could not read '.gnu_debugaltlink' section: %s"),
2124            bfd_errmsg (bfd_get_error ()));
2125   cleanup = make_cleanup (xfree, data);
2126
2127   filename = (const char *) data;
2128   if (!IS_ABSOLUTE_PATH (filename))
2129     {
2130       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2131       char *rel;
2132
2133       make_cleanup (xfree, abs);
2134       abs = ldirname (abs);
2135       make_cleanup (xfree, abs);
2136
2137       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2138       make_cleanup (xfree, rel);
2139       filename = rel;
2140     }
2141
2142   /* The format is just a NUL-terminated file name, followed by the
2143      build-id.  For now, though, we ignore the build-id.  */
2144   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2145   if (dwz_bfd == NULL)
2146     error (_("could not read '%s': %s"), filename,
2147            bfd_errmsg (bfd_get_error ()));
2148
2149   if (!bfd_check_format (dwz_bfd, bfd_object))
2150     {
2151       gdb_bfd_unref (dwz_bfd);
2152       error (_("file '%s' was not usable: %s"), filename,
2153              bfd_errmsg (bfd_get_error ()));
2154     }
2155
2156   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2157                            struct dwz_file);
2158   result->dwz_bfd = dwz_bfd;
2159
2160   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2161
2162   do_cleanups (cleanup);
2163
2164   dwarf2_per_objfile->dwz_file = result;
2165   return result;
2166 }
2167 \f
2168 /* DWARF quick_symbols_functions support.  */
2169
2170 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2171    unique line tables, so we maintain a separate table of all .debug_line
2172    derived entries to support the sharing.
2173    All the quick functions need is the list of file names.  We discard the
2174    line_header when we're done and don't need to record it here.  */
2175 struct quick_file_names
2176 {
2177   /* The data used to construct the hash key.  */
2178   struct stmt_list_hash hash;
2179
2180   /* The number of entries in file_names, real_names.  */
2181   unsigned int num_file_names;
2182
2183   /* The file names from the line table, after being run through
2184      file_full_name.  */
2185   const char **file_names;
2186
2187   /* The file names from the line table after being run through
2188      gdb_realpath.  These are computed lazily.  */
2189   const char **real_names;
2190 };
2191
2192 /* When using the index (and thus not using psymtabs), each CU has an
2193    object of this type.  This is used to hold information needed by
2194    the various "quick" methods.  */
2195 struct dwarf2_per_cu_quick_data
2196 {
2197   /* The file table.  This can be NULL if there was no file table
2198      or it's currently not read in.
2199      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2200   struct quick_file_names *file_names;
2201
2202   /* The corresponding symbol table.  This is NULL if symbols for this
2203      CU have not yet been read.  */
2204   struct symtab *symtab;
2205
2206   /* A temporary mark bit used when iterating over all CUs in
2207      expand_symtabs_matching.  */
2208   unsigned int mark : 1;
2209
2210   /* True if we've tried to read the file table and found there isn't one.
2211      There will be no point in trying to read it again next time.  */
2212   unsigned int no_file_data : 1;
2213 };
2214
2215 /* Utility hash function for a stmt_list_hash.  */
2216
2217 static hashval_t
2218 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2219 {
2220   hashval_t v = 0;
2221
2222   if (stmt_list_hash->dwo_unit != NULL)
2223     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2224   v += stmt_list_hash->line_offset.sect_off;
2225   return v;
2226 }
2227
2228 /* Utility equality function for a stmt_list_hash.  */
2229
2230 static int
2231 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2232                     const struct stmt_list_hash *rhs)
2233 {
2234   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2235     return 0;
2236   if (lhs->dwo_unit != NULL
2237       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2238     return 0;
2239
2240   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2241 }
2242
2243 /* Hash function for a quick_file_names.  */
2244
2245 static hashval_t
2246 hash_file_name_entry (const void *e)
2247 {
2248   const struct quick_file_names *file_data = e;
2249
2250   return hash_stmt_list_entry (&file_data->hash);
2251 }
2252
2253 /* Equality function for a quick_file_names.  */
2254
2255 static int
2256 eq_file_name_entry (const void *a, const void *b)
2257 {
2258   const struct quick_file_names *ea = a;
2259   const struct quick_file_names *eb = b;
2260
2261   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2262 }
2263
2264 /* Delete function for a quick_file_names.  */
2265
2266 static void
2267 delete_file_name_entry (void *e)
2268 {
2269   struct quick_file_names *file_data = e;
2270   int i;
2271
2272   for (i = 0; i < file_data->num_file_names; ++i)
2273     {
2274       xfree ((void*) file_data->file_names[i]);
2275       if (file_data->real_names)
2276         xfree ((void*) file_data->real_names[i]);
2277     }
2278
2279   /* The space for the struct itself lives on objfile_obstack,
2280      so we don't free it here.  */
2281 }
2282
2283 /* Create a quick_file_names hash table.  */
2284
2285 static htab_t
2286 create_quick_file_names_table (unsigned int nr_initial_entries)
2287 {
2288   return htab_create_alloc (nr_initial_entries,
2289                             hash_file_name_entry, eq_file_name_entry,
2290                             delete_file_name_entry, xcalloc, xfree);
2291 }
2292
2293 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2294    have to be created afterwards.  You should call age_cached_comp_units after
2295    processing PER_CU->CU.  dw2_setup must have been already called.  */
2296
2297 static void
2298 load_cu (struct dwarf2_per_cu_data *per_cu)
2299 {
2300   if (per_cu->is_debug_types)
2301     load_full_type_unit (per_cu);
2302   else
2303     load_full_comp_unit (per_cu, language_minimal);
2304
2305   gdb_assert (per_cu->cu != NULL);
2306
2307   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2308 }
2309
2310 /* Read in the symbols for PER_CU.  */
2311
2312 static void
2313 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2314 {
2315   struct cleanup *back_to;
2316
2317   /* Skip type_unit_groups, reading the type units they contain
2318      is handled elsewhere.  */
2319   if (IS_TYPE_UNIT_GROUP (per_cu))
2320     return;
2321
2322   back_to = make_cleanup (dwarf2_release_queue, NULL);
2323
2324   if (dwarf2_per_objfile->using_index
2325       ? per_cu->v.quick->symtab == NULL
2326       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2327     {
2328       queue_comp_unit (per_cu, language_minimal);
2329       load_cu (per_cu);
2330     }
2331
2332   process_queue ();
2333
2334   /* Age the cache, releasing compilation units that have not
2335      been used recently.  */
2336   age_cached_comp_units ();
2337
2338   do_cleanups (back_to);
2339 }
2340
2341 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2342    the objfile from which this CU came.  Returns the resulting symbol
2343    table.  */
2344
2345 static struct symtab *
2346 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2347 {
2348   gdb_assert (dwarf2_per_objfile->using_index);
2349   if (!per_cu->v.quick->symtab)
2350     {
2351       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2352       increment_reading_symtab ();
2353       dw2_do_instantiate_symtab (per_cu);
2354       process_cu_includes ();
2355       do_cleanups (back_to);
2356     }
2357   return per_cu->v.quick->symtab;
2358 }
2359
2360 /* Return the CU given its index.
2361
2362    This is intended for loops like:
2363
2364    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2365                     + dwarf2_per_objfile->n_type_units); ++i)
2366      {
2367        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2368
2369        ...;
2370      }
2371 */
2372
2373 static struct dwarf2_per_cu_data *
2374 dw2_get_cu (int index)
2375 {
2376   if (index >= dwarf2_per_objfile->n_comp_units)
2377     {
2378       index -= dwarf2_per_objfile->n_comp_units;
2379       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2380       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2381     }
2382
2383   return dwarf2_per_objfile->all_comp_units[index];
2384 }
2385
2386 /* Return the primary CU given its index.
2387    The difference between this function and dw2_get_cu is in the handling
2388    of type units (TUs).  Here we return the type_unit_group object.
2389
2390    This is intended for loops like:
2391
2392    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2393                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2394      {
2395        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2396
2397        ...;
2398      }
2399 */
2400
2401 static struct dwarf2_per_cu_data *
2402 dw2_get_primary_cu (int index)
2403 {
2404   if (index >= dwarf2_per_objfile->n_comp_units)
2405     {
2406       index -= dwarf2_per_objfile->n_comp_units;
2407       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2408       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2409     }
2410
2411   return dwarf2_per_objfile->all_comp_units[index];
2412 }
2413
2414 /* A helper for create_cus_from_index that handles a given list of
2415    CUs.  */
2416
2417 static void
2418 create_cus_from_index_list (struct objfile *objfile,
2419                             const gdb_byte *cu_list, offset_type n_elements,
2420                             struct dwarf2_section_info *section,
2421                             int is_dwz,
2422                             int base_offset)
2423 {
2424   offset_type i;
2425
2426   for (i = 0; i < n_elements; i += 2)
2427     {
2428       struct dwarf2_per_cu_data *the_cu;
2429       ULONGEST offset, length;
2430
2431       gdb_static_assert (sizeof (ULONGEST) >= 8);
2432       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2433       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2434       cu_list += 2 * 8;
2435
2436       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2437                                struct dwarf2_per_cu_data);
2438       the_cu->offset.sect_off = offset;
2439       the_cu->length = length;
2440       the_cu->objfile = objfile;
2441       the_cu->section = section;
2442       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2443                                         struct dwarf2_per_cu_quick_data);
2444       the_cu->is_dwz = is_dwz;
2445       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2446     }
2447 }
2448
2449 /* Read the CU list from the mapped index, and use it to create all
2450    the CU objects for this objfile.  */
2451
2452 static void
2453 create_cus_from_index (struct objfile *objfile,
2454                        const gdb_byte *cu_list, offset_type cu_list_elements,
2455                        const gdb_byte *dwz_list, offset_type dwz_elements)
2456 {
2457   struct dwz_file *dwz;
2458
2459   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2460   dwarf2_per_objfile->all_comp_units
2461     = obstack_alloc (&objfile->objfile_obstack,
2462                      dwarf2_per_objfile->n_comp_units
2463                      * sizeof (struct dwarf2_per_cu_data *));
2464
2465   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2466                               &dwarf2_per_objfile->info, 0, 0);
2467
2468   if (dwz_elements == 0)
2469     return;
2470
2471   dwz = dwarf2_get_dwz_file ();
2472   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2473                               cu_list_elements / 2);
2474 }
2475
2476 /* Create the signatured type hash table from the index.  */
2477
2478 static void
2479 create_signatured_type_table_from_index (struct objfile *objfile,
2480                                          struct dwarf2_section_info *section,
2481                                          const gdb_byte *bytes,
2482                                          offset_type elements)
2483 {
2484   offset_type i;
2485   htab_t sig_types_hash;
2486
2487   dwarf2_per_objfile->n_type_units = elements / 3;
2488   dwarf2_per_objfile->all_type_units
2489     = xmalloc (dwarf2_per_objfile->n_type_units
2490                * sizeof (struct signatured_type *));
2491
2492   sig_types_hash = allocate_signatured_type_table (objfile);
2493
2494   for (i = 0; i < elements; i += 3)
2495     {
2496       struct signatured_type *sig_type;
2497       ULONGEST offset, type_offset_in_tu, signature;
2498       void **slot;
2499
2500       gdb_static_assert (sizeof (ULONGEST) >= 8);
2501       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2502       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2503                                                     BFD_ENDIAN_LITTLE);
2504       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2505       bytes += 3 * 8;
2506
2507       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2508                                  struct signatured_type);
2509       sig_type->signature = signature;
2510       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2511       sig_type->per_cu.is_debug_types = 1;
2512       sig_type->per_cu.section = section;
2513       sig_type->per_cu.offset.sect_off = offset;
2514       sig_type->per_cu.objfile = objfile;
2515       sig_type->per_cu.v.quick
2516         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2517                           struct dwarf2_per_cu_quick_data);
2518
2519       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2520       *slot = sig_type;
2521
2522       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2523     }
2524
2525   dwarf2_per_objfile->signatured_types = sig_types_hash;
2526 }
2527
2528 /* Read the address map data from the mapped index, and use it to
2529    populate the objfile's psymtabs_addrmap.  */
2530
2531 static void
2532 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2533 {
2534   const gdb_byte *iter, *end;
2535   struct obstack temp_obstack;
2536   struct addrmap *mutable_map;
2537   struct cleanup *cleanup;
2538   CORE_ADDR baseaddr;
2539
2540   obstack_init (&temp_obstack);
2541   cleanup = make_cleanup_obstack_free (&temp_obstack);
2542   mutable_map = addrmap_create_mutable (&temp_obstack);
2543
2544   iter = index->address_table;
2545   end = iter + index->address_table_size;
2546
2547   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2548
2549   while (iter < end)
2550     {
2551       ULONGEST hi, lo, cu_index;
2552       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2553       iter += 8;
2554       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2555       iter += 8;
2556       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2557       iter += 4;
2558
2559       if (cu_index < dwarf2_per_objfile->n_comp_units)
2560         {
2561           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2562                              dw2_get_cu (cu_index));
2563         }
2564       else
2565         {
2566           complaint (&symfile_complaints,
2567                      _(".gdb_index address table has invalid CU number %u"),
2568                      (unsigned) cu_index);
2569         }
2570     }
2571
2572   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2573                                                     &objfile->objfile_obstack);
2574   do_cleanups (cleanup);
2575 }
2576
2577 /* The hash function for strings in the mapped index.  This is the same as
2578    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2579    implementation.  This is necessary because the hash function is tied to the
2580    format of the mapped index file.  The hash values do not have to match with
2581    SYMBOL_HASH_NEXT.
2582    
2583    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2584
2585 static hashval_t
2586 mapped_index_string_hash (int index_version, const void *p)
2587 {
2588   const unsigned char *str = (const unsigned char *) p;
2589   hashval_t r = 0;
2590   unsigned char c;
2591
2592   while ((c = *str++) != 0)
2593     {
2594       if (index_version >= 5)
2595         c = tolower (c);
2596       r = r * 67 + c - 113;
2597     }
2598
2599   return r;
2600 }
2601
2602 /* Find a slot in the mapped index INDEX for the object named NAME.
2603    If NAME is found, set *VEC_OUT to point to the CU vector in the
2604    constant pool and return 1.  If NAME cannot be found, return 0.  */
2605
2606 static int
2607 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2608                           offset_type **vec_out)
2609 {
2610   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2611   offset_type hash;
2612   offset_type slot, step;
2613   int (*cmp) (const char *, const char *);
2614
2615   if (current_language->la_language == language_cplus
2616       || current_language->la_language == language_java
2617       || current_language->la_language == language_fortran)
2618     {
2619       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2620          not contain any.  */
2621       const char *paren = strchr (name, '(');
2622
2623       if (paren)
2624         {
2625           char *dup;
2626
2627           dup = xmalloc (paren - name + 1);
2628           memcpy (dup, name, paren - name);
2629           dup[paren - name] = 0;
2630
2631           make_cleanup (xfree, dup);
2632           name = dup;
2633         }
2634     }
2635
2636   /* Index version 4 did not support case insensitive searches.  But the
2637      indices for case insensitive languages are built in lowercase, therefore
2638      simulate our NAME being searched is also lowercased.  */
2639   hash = mapped_index_string_hash ((index->version == 4
2640                                     && case_sensitivity == case_sensitive_off
2641                                     ? 5 : index->version),
2642                                    name);
2643
2644   slot = hash & (index->symbol_table_slots - 1);
2645   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2646   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2647
2648   for (;;)
2649     {
2650       /* Convert a slot number to an offset into the table.  */
2651       offset_type i = 2 * slot;
2652       const char *str;
2653       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2654         {
2655           do_cleanups (back_to);
2656           return 0;
2657         }
2658
2659       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2660       if (!cmp (name, str))
2661         {
2662           *vec_out = (offset_type *) (index->constant_pool
2663                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2664           do_cleanups (back_to);
2665           return 1;
2666         }
2667
2668       slot = (slot + step) & (index->symbol_table_slots - 1);
2669     }
2670 }
2671
2672 /* A helper function that reads the .gdb_index from SECTION and fills
2673    in MAP.  FILENAME is the name of the file containing the section;
2674    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2675    ok to use deprecated sections.
2676
2677    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2678    out parameters that are filled in with information about the CU and
2679    TU lists in the section.
2680
2681    Returns 1 if all went well, 0 otherwise.  */
2682
2683 static int
2684 read_index_from_section (struct objfile *objfile,
2685                          const char *filename,
2686                          int deprecated_ok,
2687                          struct dwarf2_section_info *section,
2688                          struct mapped_index *map,
2689                          const gdb_byte **cu_list,
2690                          offset_type *cu_list_elements,
2691                          const gdb_byte **types_list,
2692                          offset_type *types_list_elements)
2693 {
2694   const gdb_byte *addr;
2695   offset_type version;
2696   offset_type *metadata;
2697   int i;
2698
2699   if (dwarf2_section_empty_p (section))
2700     return 0;
2701
2702   /* Older elfutils strip versions could keep the section in the main
2703      executable while splitting it for the separate debug info file.  */
2704   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2705     return 0;
2706
2707   dwarf2_read_section (objfile, section);
2708
2709   addr = section->buffer;
2710   /* Version check.  */
2711   version = MAYBE_SWAP (*(offset_type *) addr);
2712   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2713      causes the index to behave very poorly for certain requests.  Version 3
2714      contained incomplete addrmap.  So, it seems better to just ignore such
2715      indices.  */
2716   if (version < 4)
2717     {
2718       static int warning_printed = 0;
2719       if (!warning_printed)
2720         {
2721           warning (_("Skipping obsolete .gdb_index section in %s."),
2722                    filename);
2723           warning_printed = 1;
2724         }
2725       return 0;
2726     }
2727   /* Index version 4 uses a different hash function than index version
2728      5 and later.
2729
2730      Versions earlier than 6 did not emit psymbols for inlined
2731      functions.  Using these files will cause GDB not to be able to
2732      set breakpoints on inlined functions by name, so we ignore these
2733      indices unless the user has done
2734      "set use-deprecated-index-sections on".  */
2735   if (version < 6 && !deprecated_ok)
2736     {
2737       static int warning_printed = 0;
2738       if (!warning_printed)
2739         {
2740           warning (_("\
2741 Skipping deprecated .gdb_index section in %s.\n\
2742 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2743 to use the section anyway."),
2744                    filename);
2745           warning_printed = 1;
2746         }
2747       return 0;
2748     }
2749   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2750      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2751      we can't distinguish gdb-generated indices from gold-generated ones, so
2752      nothing to do here.  */
2753
2754   /* Indexes with higher version than the one supported by GDB may be no
2755      longer backward compatible.  */
2756   if (version > 8)
2757     return 0;
2758
2759   map->version = version;
2760   map->total_size = section->size;
2761
2762   metadata = (offset_type *) (addr + sizeof (offset_type));
2763
2764   i = 0;
2765   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2766   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2767                        / 8);
2768   ++i;
2769
2770   *types_list = addr + MAYBE_SWAP (metadata[i]);
2771   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2772                            - MAYBE_SWAP (metadata[i]))
2773                           / 8);
2774   ++i;
2775
2776   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2777   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2778                              - MAYBE_SWAP (metadata[i]));
2779   ++i;
2780
2781   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2782   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2783                               - MAYBE_SWAP (metadata[i]))
2784                              / (2 * sizeof (offset_type)));
2785   ++i;
2786
2787   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
2788
2789   return 1;
2790 }
2791
2792
2793 /* Read the index file.  If everything went ok, initialize the "quick"
2794    elements of all the CUs and return 1.  Otherwise, return 0.  */
2795
2796 static int
2797 dwarf2_read_index (struct objfile *objfile)
2798 {
2799   struct mapped_index local_map, *map;
2800   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2801   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2802
2803   if (!read_index_from_section (objfile, objfile->name,
2804                                 use_deprecated_index_sections,
2805                                 &dwarf2_per_objfile->gdb_index, &local_map,
2806                                 &cu_list, &cu_list_elements,
2807                                 &types_list, &types_list_elements))
2808     return 0;
2809
2810   /* Don't use the index if it's empty.  */
2811   if (local_map.symbol_table_slots == 0)
2812     return 0;
2813
2814   /* If there is a .dwz file, read it so we can get its CU list as
2815      well.  */
2816   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2817     {
2818       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2819       struct mapped_index dwz_map;
2820       const gdb_byte *dwz_types_ignore;
2821       offset_type dwz_types_elements_ignore;
2822
2823       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2824                                     1,
2825                                     &dwz->gdb_index, &dwz_map,
2826                                     &dwz_list, &dwz_list_elements,
2827                                     &dwz_types_ignore,
2828                                     &dwz_types_elements_ignore))
2829         {
2830           warning (_("could not read '.gdb_index' section from %s; skipping"),
2831                    bfd_get_filename (dwz->dwz_bfd));
2832           return 0;
2833         }
2834     }
2835
2836   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2837                          dwz_list_elements);
2838
2839   if (types_list_elements)
2840     {
2841       struct dwarf2_section_info *section;
2842
2843       /* We can only handle a single .debug_types when we have an
2844          index.  */
2845       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2846         return 0;
2847
2848       section = VEC_index (dwarf2_section_info_def,
2849                            dwarf2_per_objfile->types, 0);
2850
2851       create_signatured_type_table_from_index (objfile, section, types_list,
2852                                                types_list_elements);
2853     }
2854
2855   create_addrmap_from_index (objfile, &local_map);
2856
2857   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2858   *map = local_map;
2859
2860   dwarf2_per_objfile->index_table = map;
2861   dwarf2_per_objfile->using_index = 1;
2862   dwarf2_per_objfile->quick_file_names_table =
2863     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2864
2865   return 1;
2866 }
2867
2868 /* A helper for the "quick" functions which sets the global
2869    dwarf2_per_objfile according to OBJFILE.  */
2870
2871 static void
2872 dw2_setup (struct objfile *objfile)
2873 {
2874   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2875   gdb_assert (dwarf2_per_objfile);
2876 }
2877
2878 /* die_reader_func for dw2_get_file_names.  */
2879
2880 static void
2881 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2882                            const gdb_byte *info_ptr,
2883                            struct die_info *comp_unit_die,
2884                            int has_children,
2885                            void *data)
2886 {
2887   struct dwarf2_cu *cu = reader->cu;
2888   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2889   struct objfile *objfile = dwarf2_per_objfile->objfile;
2890   struct dwarf2_per_cu_data *lh_cu;
2891   struct line_header *lh;
2892   struct attribute *attr;
2893   int i;
2894   const char *name, *comp_dir;
2895   void **slot;
2896   struct quick_file_names *qfn;
2897   unsigned int line_offset;
2898
2899   gdb_assert (! this_cu->is_debug_types);
2900
2901   /* Our callers never want to match partial units -- instead they
2902      will match the enclosing full CU.  */
2903   if (comp_unit_die->tag == DW_TAG_partial_unit)
2904     {
2905       this_cu->v.quick->no_file_data = 1;
2906       return;
2907     }
2908
2909   lh_cu = this_cu;
2910   lh = NULL;
2911   slot = NULL;
2912   line_offset = 0;
2913
2914   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2915   if (attr)
2916     {
2917       struct quick_file_names find_entry;
2918
2919       line_offset = DW_UNSND (attr);
2920
2921       /* We may have already read in this line header (TU line header sharing).
2922          If we have we're done.  */
2923       find_entry.hash.dwo_unit = cu->dwo_unit;
2924       find_entry.hash.line_offset.sect_off = line_offset;
2925       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2926                              &find_entry, INSERT);
2927       if (*slot != NULL)
2928         {
2929           lh_cu->v.quick->file_names = *slot;
2930           return;
2931         }
2932
2933       lh = dwarf_decode_line_header (line_offset, cu);
2934     }
2935   if (lh == NULL)
2936     {
2937       lh_cu->v.quick->no_file_data = 1;
2938       return;
2939     }
2940
2941   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2942   qfn->hash.dwo_unit = cu->dwo_unit;
2943   qfn->hash.line_offset.sect_off = line_offset;
2944   gdb_assert (slot != NULL);
2945   *slot = qfn;
2946
2947   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2948
2949   qfn->num_file_names = lh->num_file_names;
2950   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2951                                    lh->num_file_names * sizeof (char *));
2952   for (i = 0; i < lh->num_file_names; ++i)
2953     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2954   qfn->real_names = NULL;
2955
2956   free_line_header (lh);
2957
2958   lh_cu->v.quick->file_names = qfn;
2959 }
2960
2961 /* A helper for the "quick" functions which attempts to read the line
2962    table for THIS_CU.  */
2963
2964 static struct quick_file_names *
2965 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2966 {
2967   /* This should never be called for TUs.  */
2968   gdb_assert (! this_cu->is_debug_types);
2969   /* Nor type unit groups.  */
2970   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
2971
2972   if (this_cu->v.quick->file_names != NULL)
2973     return this_cu->v.quick->file_names;
2974   /* If we know there is no line data, no point in looking again.  */
2975   if (this_cu->v.quick->no_file_data)
2976     return NULL;
2977
2978   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2979
2980   if (this_cu->v.quick->no_file_data)
2981     return NULL;
2982   return this_cu->v.quick->file_names;
2983 }
2984
2985 /* A helper for the "quick" functions which computes and caches the
2986    real path for a given file name from the line table.  */
2987
2988 static const char *
2989 dw2_get_real_path (struct objfile *objfile,
2990                    struct quick_file_names *qfn, int index)
2991 {
2992   if (qfn->real_names == NULL)
2993     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2994                                       qfn->num_file_names, sizeof (char *));
2995
2996   if (qfn->real_names[index] == NULL)
2997     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2998
2999   return qfn->real_names[index];
3000 }
3001
3002 static struct symtab *
3003 dw2_find_last_source_symtab (struct objfile *objfile)
3004 {
3005   int index;
3006
3007   dw2_setup (objfile);
3008   index = dwarf2_per_objfile->n_comp_units - 1;
3009   return dw2_instantiate_symtab (dw2_get_cu (index));
3010 }
3011
3012 /* Traversal function for dw2_forget_cached_source_info.  */
3013
3014 static int
3015 dw2_free_cached_file_names (void **slot, void *info)
3016 {
3017   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3018
3019   if (file_data->real_names)
3020     {
3021       int i;
3022
3023       for (i = 0; i < file_data->num_file_names; ++i)
3024         {
3025           xfree ((void*) file_data->real_names[i]);
3026           file_data->real_names[i] = NULL;
3027         }
3028     }
3029
3030   return 1;
3031 }
3032
3033 static void
3034 dw2_forget_cached_source_info (struct objfile *objfile)
3035 {
3036   dw2_setup (objfile);
3037
3038   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3039                           dw2_free_cached_file_names, NULL);
3040 }
3041
3042 /* Helper function for dw2_map_symtabs_matching_filename that expands
3043    the symtabs and calls the iterator.  */
3044
3045 static int
3046 dw2_map_expand_apply (struct objfile *objfile,
3047                       struct dwarf2_per_cu_data *per_cu,
3048                       const char *name, const char *real_path,
3049                       int (*callback) (struct symtab *, void *),
3050                       void *data)
3051 {
3052   struct symtab *last_made = objfile->symtabs;
3053
3054   /* Don't visit already-expanded CUs.  */
3055   if (per_cu->v.quick->symtab)
3056     return 0;
3057
3058   /* This may expand more than one symtab, and we want to iterate over
3059      all of them.  */
3060   dw2_instantiate_symtab (per_cu);
3061
3062   return iterate_over_some_symtabs (name, real_path, callback, data,
3063                                     objfile->symtabs, last_made);
3064 }
3065
3066 /* Implementation of the map_symtabs_matching_filename method.  */
3067
3068 static int
3069 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3070                                    const char *real_path,
3071                                    int (*callback) (struct symtab *, void *),
3072                                    void *data)
3073 {
3074   int i;
3075   const char *name_basename = lbasename (name);
3076
3077   dw2_setup (objfile);
3078
3079   /* The rule is CUs specify all the files, including those used by
3080      any TU, so there's no need to scan TUs here.  */
3081
3082   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3083     {
3084       int j;
3085       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3086       struct quick_file_names *file_data;
3087
3088       /* We only need to look at symtabs not already expanded.  */
3089       if (per_cu->v.quick->symtab)
3090         continue;
3091
3092       file_data = dw2_get_file_names (per_cu);
3093       if (file_data == NULL)
3094         continue;
3095
3096       for (j = 0; j < file_data->num_file_names; ++j)
3097         {
3098           const char *this_name = file_data->file_names[j];
3099           const char *this_real_name;
3100
3101           if (compare_filenames_for_search (this_name, name))
3102             {
3103               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3104                                         callback, data))
3105                 return 1;
3106               continue;
3107             }
3108
3109           /* Before we invoke realpath, which can get expensive when many
3110              files are involved, do a quick comparison of the basenames.  */
3111           if (! basenames_may_differ
3112               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3113             continue;
3114
3115           this_real_name = dw2_get_real_path (objfile, file_data, j);
3116           if (compare_filenames_for_search (this_real_name, name))
3117             {
3118               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3119                                         callback, data))
3120                 return 1;
3121               continue;
3122             }
3123
3124           if (real_path != NULL)
3125             {
3126               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3127               gdb_assert (IS_ABSOLUTE_PATH (name));
3128               if (this_real_name != NULL
3129                   && FILENAME_CMP (real_path, this_real_name) == 0)
3130                 {
3131                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3132                                             callback, data))
3133                     return 1;
3134                   continue;
3135                 }
3136             }
3137         }
3138     }
3139
3140   return 0;
3141 }
3142
3143 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3144
3145 struct dw2_symtab_iterator
3146 {
3147   /* The internalized form of .gdb_index.  */
3148   struct mapped_index *index;
3149   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3150   int want_specific_block;
3151   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3152      Unused if !WANT_SPECIFIC_BLOCK.  */
3153   int block_index;
3154   /* The kind of symbol we're looking for.  */
3155   domain_enum domain;
3156   /* The list of CUs from the index entry of the symbol,
3157      or NULL if not found.  */
3158   offset_type *vec;
3159   /* The next element in VEC to look at.  */
3160   int next;
3161   /* The number of elements in VEC, or zero if there is no match.  */
3162   int length;
3163 };
3164
3165 /* Initialize the index symtab iterator ITER.
3166    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3167    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3168
3169 static void
3170 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3171                       struct mapped_index *index,
3172                       int want_specific_block,
3173                       int block_index,
3174                       domain_enum domain,
3175                       const char *name)
3176 {
3177   iter->index = index;
3178   iter->want_specific_block = want_specific_block;
3179   iter->block_index = block_index;
3180   iter->domain = domain;
3181   iter->next = 0;
3182
3183   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3184     iter->length = MAYBE_SWAP (*iter->vec);
3185   else
3186     {
3187       iter->vec = NULL;
3188       iter->length = 0;
3189     }
3190 }
3191
3192 /* Return the next matching CU or NULL if there are no more.  */
3193
3194 static struct dwarf2_per_cu_data *
3195 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3196 {
3197   for ( ; iter->next < iter->length; ++iter->next)
3198     {
3199       offset_type cu_index_and_attrs =
3200         MAYBE_SWAP (iter->vec[iter->next + 1]);
3201       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3202       struct dwarf2_per_cu_data *per_cu;
3203       int want_static = iter->block_index != GLOBAL_BLOCK;
3204       /* This value is only valid for index versions >= 7.  */
3205       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3206       gdb_index_symbol_kind symbol_kind =
3207         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3208       /* Only check the symbol attributes if they're present.
3209          Indices prior to version 7 don't record them,
3210          and indices >= 7 may elide them for certain symbols
3211          (gold does this).  */
3212       int attrs_valid =
3213         (iter->index->version >= 7
3214          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3215
3216       /* Don't crash on bad data.  */
3217       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3218                        + dwarf2_per_objfile->n_type_units))
3219         {
3220           complaint (&symfile_complaints,
3221                      _(".gdb_index entry has bad CU index"
3222                        " [in module %s]"), dwarf2_per_objfile->objfile->name);
3223           continue;
3224         }
3225
3226       per_cu = dw2_get_cu (cu_index);
3227
3228       /* Skip if already read in.  */
3229       if (per_cu->v.quick->symtab)
3230         continue;
3231
3232       if (attrs_valid
3233           && iter->want_specific_block
3234           && want_static != is_static)
3235         continue;
3236
3237       /* Only check the symbol's kind if it has one.  */
3238       if (attrs_valid)
3239         {
3240           switch (iter->domain)
3241             {
3242             case VAR_DOMAIN:
3243               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3244                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3245                   /* Some types are also in VAR_DOMAIN.  */
3246                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3247                 continue;
3248               break;
3249             case STRUCT_DOMAIN:
3250               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3251                 continue;
3252               break;
3253             case LABEL_DOMAIN:
3254               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3255                 continue;
3256               break;
3257             default:
3258               break;
3259             }
3260         }
3261
3262       ++iter->next;
3263       return per_cu;
3264     }
3265
3266   return NULL;
3267 }
3268
3269 static struct symtab *
3270 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3271                    const char *name, domain_enum domain)
3272 {
3273   struct symtab *stab_best = NULL;
3274   struct mapped_index *index;
3275
3276   dw2_setup (objfile);
3277
3278   index = dwarf2_per_objfile->index_table;
3279
3280   /* index is NULL if OBJF_READNOW.  */
3281   if (index)
3282     {
3283       struct dw2_symtab_iterator iter;
3284       struct dwarf2_per_cu_data *per_cu;
3285
3286       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3287
3288       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3289         {
3290           struct symbol *sym = NULL;
3291           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3292
3293           /* Some caution must be observed with overloaded functions
3294              and methods, since the index will not contain any overload
3295              information (but NAME might contain it).  */
3296           if (stab->primary)
3297             {
3298               struct blockvector *bv = BLOCKVECTOR (stab);
3299               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3300
3301               sym = lookup_block_symbol (block, name, domain);
3302             }
3303
3304           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3305             {
3306               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3307                 return stab;
3308
3309               stab_best = stab;
3310             }
3311
3312           /* Keep looking through other CUs.  */
3313         }
3314     }
3315
3316   return stab_best;
3317 }
3318
3319 static void
3320 dw2_print_stats (struct objfile *objfile)
3321 {
3322   int i, total, count;
3323
3324   dw2_setup (objfile);
3325   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3326   count = 0;
3327   for (i = 0; i < total; ++i)
3328     {
3329       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3330
3331       if (!per_cu->v.quick->symtab)
3332         ++count;
3333     }
3334   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3335   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3336 }
3337
3338 static void
3339 dw2_dump (struct objfile *objfile)
3340 {
3341   /* Nothing worth printing.  */
3342 }
3343
3344 static void
3345 dw2_relocate (struct objfile *objfile,
3346               const struct section_offsets *new_offsets,
3347               const struct section_offsets *delta)
3348 {
3349   /* There's nothing to relocate here.  */
3350 }
3351
3352 static void
3353 dw2_expand_symtabs_for_function (struct objfile *objfile,
3354                                  const char *func_name)
3355 {
3356   struct mapped_index *index;
3357
3358   dw2_setup (objfile);
3359
3360   index = dwarf2_per_objfile->index_table;
3361
3362   /* index is NULL if OBJF_READNOW.  */
3363   if (index)
3364     {
3365       struct dw2_symtab_iterator iter;
3366       struct dwarf2_per_cu_data *per_cu;
3367
3368       /* Note: It doesn't matter what we pass for block_index here.  */
3369       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3370                             func_name);
3371
3372       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3373         dw2_instantiate_symtab (per_cu);
3374     }
3375 }
3376
3377 static void
3378 dw2_expand_all_symtabs (struct objfile *objfile)
3379 {
3380   int i;
3381
3382   dw2_setup (objfile);
3383
3384   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3385                    + dwarf2_per_objfile->n_type_units); ++i)
3386     {
3387       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3388
3389       dw2_instantiate_symtab (per_cu);
3390     }
3391 }
3392
3393 static void
3394 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3395                                   const char *fullname)
3396 {
3397   int i;
3398
3399   dw2_setup (objfile);
3400
3401   /* We don't need to consider type units here.
3402      This is only called for examining code, e.g. expand_line_sal.
3403      There can be an order of magnitude (or more) more type units
3404      than comp units, and we avoid them if we can.  */
3405
3406   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3407     {
3408       int j;
3409       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3410       struct quick_file_names *file_data;
3411
3412       /* We only need to look at symtabs not already expanded.  */
3413       if (per_cu->v.quick->symtab)
3414         continue;
3415
3416       file_data = dw2_get_file_names (per_cu);
3417       if (file_data == NULL)
3418         continue;
3419
3420       for (j = 0; j < file_data->num_file_names; ++j)
3421         {
3422           const char *this_fullname = file_data->file_names[j];
3423
3424           if (filename_cmp (this_fullname, fullname) == 0)
3425             {
3426               dw2_instantiate_symtab (per_cu);
3427               break;
3428             }
3429         }
3430     }
3431 }
3432
3433 /* A helper function for dw2_find_symbol_file that finds the primary
3434    file name for a given CU.  This is a die_reader_func.  */
3435
3436 static void
3437 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3438                                  const gdb_byte *info_ptr,
3439                                  struct die_info *comp_unit_die,
3440                                  int has_children,
3441                                  void *data)
3442 {
3443   const char **result_ptr = data;
3444   struct dwarf2_cu *cu = reader->cu;
3445   struct attribute *attr;
3446
3447   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3448   if (attr == NULL)
3449     *result_ptr = NULL;
3450   else
3451     *result_ptr = DW_STRING (attr);
3452 }
3453
3454 static const char *
3455 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3456 {
3457   struct dwarf2_per_cu_data *per_cu;
3458   offset_type *vec;
3459   const char *filename;
3460
3461   dw2_setup (objfile);
3462
3463   /* index_table is NULL if OBJF_READNOW.  */
3464   if (!dwarf2_per_objfile->index_table)
3465     {
3466       struct symtab *s;
3467
3468       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3469         {
3470           struct blockvector *bv = BLOCKVECTOR (s);
3471           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3472           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3473
3474           if (sym)
3475             {
3476               /* Only file extension of returned filename is recognized.  */
3477               return SYMBOL_SYMTAB (sym)->filename;
3478             }
3479         }
3480       return NULL;
3481     }
3482
3483   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3484                                  name, &vec))
3485     return NULL;
3486
3487   /* Note that this just looks at the very first one named NAME -- but
3488      actually we are looking for a function.  find_main_filename
3489      should be rewritten so that it doesn't require a custom hook.  It
3490      could just use the ordinary symbol tables.  */
3491   /* vec[0] is the length, which must always be >0.  */
3492   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3493
3494   if (per_cu->v.quick->symtab != NULL)
3495     {
3496       /* Only file extension of returned filename is recognized.  */
3497       return per_cu->v.quick->symtab->filename;
3498     }
3499
3500   /* Initialize filename in case there's a problem reading the DWARF,
3501      dw2_get_primary_filename_reader may not get called.  */
3502   filename = NULL;
3503   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3504                            dw2_get_primary_filename_reader, &filename);
3505
3506   /* Only file extension of returned filename is recognized.  */
3507   return filename;
3508 }
3509
3510 static void
3511 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3512                           struct objfile *objfile, int global,
3513                           int (*callback) (struct block *,
3514                                            struct symbol *, void *),
3515                           void *data, symbol_compare_ftype *match,
3516                           symbol_compare_ftype *ordered_compare)
3517 {
3518   /* Currently unimplemented; used for Ada.  The function can be called if the
3519      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3520      does not look for non-Ada symbols this function should just return.  */
3521 }
3522
3523 static void
3524 dw2_expand_symtabs_matching
3525   (struct objfile *objfile,
3526    int (*file_matcher) (const char *, void *, int basenames),
3527    int (*name_matcher) (const char *, void *),
3528    enum search_domain kind,
3529    void *data)
3530 {
3531   int i;
3532   offset_type iter;
3533   struct mapped_index *index;
3534
3535   dw2_setup (objfile);
3536
3537   /* index_table is NULL if OBJF_READNOW.  */
3538   if (!dwarf2_per_objfile->index_table)
3539     return;
3540   index = dwarf2_per_objfile->index_table;
3541
3542   if (file_matcher != NULL)
3543     {
3544       struct cleanup *cleanup;
3545       htab_t visited_found, visited_not_found;
3546
3547       visited_found = htab_create_alloc (10,
3548                                          htab_hash_pointer, htab_eq_pointer,
3549                                          NULL, xcalloc, xfree);
3550       cleanup = make_cleanup_htab_delete (visited_found);
3551       visited_not_found = htab_create_alloc (10,
3552                                              htab_hash_pointer, htab_eq_pointer,
3553                                              NULL, xcalloc, xfree);
3554       make_cleanup_htab_delete (visited_not_found);
3555
3556       /* The rule is CUs specify all the files, including those used by
3557          any TU, so there's no need to scan TUs here.  */
3558
3559       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3560         {
3561           int j;
3562           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3563           struct quick_file_names *file_data;
3564           void **slot;
3565
3566           per_cu->v.quick->mark = 0;
3567
3568           /* We only need to look at symtabs not already expanded.  */
3569           if (per_cu->v.quick->symtab)
3570             continue;
3571
3572           file_data = dw2_get_file_names (per_cu);
3573           if (file_data == NULL)
3574             continue;
3575
3576           if (htab_find (visited_not_found, file_data) != NULL)
3577             continue;
3578           else if (htab_find (visited_found, file_data) != NULL)
3579             {
3580               per_cu->v.quick->mark = 1;
3581               continue;
3582             }
3583
3584           for (j = 0; j < file_data->num_file_names; ++j)
3585             {
3586               const char *this_real_name;
3587
3588               if (file_matcher (file_data->file_names[j], data, 0))
3589                 {
3590                   per_cu->v.quick->mark = 1;
3591                   break;
3592                 }
3593
3594               /* Before we invoke realpath, which can get expensive when many
3595                  files are involved, do a quick comparison of the basenames.  */
3596               if (!basenames_may_differ
3597                   && !file_matcher (lbasename (file_data->file_names[j]),
3598                                     data, 1))
3599                 continue;
3600
3601               this_real_name = dw2_get_real_path (objfile, file_data, j);
3602               if (file_matcher (this_real_name, data, 0))
3603                 {
3604                   per_cu->v.quick->mark = 1;
3605                   break;
3606                 }
3607             }
3608
3609           slot = htab_find_slot (per_cu->v.quick->mark
3610                                  ? visited_found
3611                                  : visited_not_found,
3612                                  file_data, INSERT);
3613           *slot = file_data;
3614         }
3615
3616       do_cleanups (cleanup);
3617     }
3618
3619   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3620     {
3621       offset_type idx = 2 * iter;
3622       const char *name;
3623       offset_type *vec, vec_len, vec_idx;
3624
3625       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3626         continue;
3627
3628       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3629
3630       if (! (*name_matcher) (name, data))
3631         continue;
3632
3633       /* The name was matched, now expand corresponding CUs that were
3634          marked.  */
3635       vec = (offset_type *) (index->constant_pool
3636                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3637       vec_len = MAYBE_SWAP (vec[0]);
3638       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3639         {
3640           struct dwarf2_per_cu_data *per_cu;
3641           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3642           gdb_index_symbol_kind symbol_kind =
3643             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3644           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3645           /* Only check the symbol attributes if they're present.
3646              Indices prior to version 7 don't record them,
3647              and indices >= 7 may elide them for certain symbols
3648              (gold does this).  */
3649           int attrs_valid =
3650             (index->version >= 7
3651              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3652
3653           /* Only check the symbol's kind if it has one.  */
3654           if (attrs_valid)
3655             {
3656               switch (kind)
3657                 {
3658                 case VARIABLES_DOMAIN:
3659                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3660                     continue;
3661                   break;
3662                 case FUNCTIONS_DOMAIN:
3663                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3664                     continue;
3665                   break;
3666                 case TYPES_DOMAIN:
3667                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3668                     continue;
3669                   break;
3670                 default:
3671                   break;
3672                 }
3673             }
3674
3675           /* Don't crash on bad data.  */
3676           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3677                            + dwarf2_per_objfile->n_type_units))
3678             {
3679               complaint (&symfile_complaints,
3680                          _(".gdb_index entry has bad CU index"
3681                            " [in module %s]"), objfile->name);
3682               continue;
3683             }
3684
3685           per_cu = dw2_get_cu (cu_index);
3686           if (file_matcher == NULL || per_cu->v.quick->mark)
3687             dw2_instantiate_symtab (per_cu);
3688         }
3689     }
3690 }
3691
3692 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3693    symtab.  */
3694
3695 static struct symtab *
3696 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3697 {
3698   int i;
3699
3700   if (BLOCKVECTOR (symtab) != NULL
3701       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3702     return symtab;
3703
3704   if (symtab->includes == NULL)
3705     return NULL;
3706
3707   for (i = 0; symtab->includes[i]; ++i)
3708     {
3709       struct symtab *s = symtab->includes[i];
3710
3711       s = recursively_find_pc_sect_symtab (s, pc);
3712       if (s != NULL)
3713         return s;
3714     }
3715
3716   return NULL;
3717 }
3718
3719 static struct symtab *
3720 dw2_find_pc_sect_symtab (struct objfile *objfile,
3721                          struct minimal_symbol *msymbol,
3722                          CORE_ADDR pc,
3723                          struct obj_section *section,
3724                          int warn_if_readin)
3725 {
3726   struct dwarf2_per_cu_data *data;
3727   struct symtab *result;
3728
3729   dw2_setup (objfile);
3730
3731   if (!objfile->psymtabs_addrmap)
3732     return NULL;
3733
3734   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3735   if (!data)
3736     return NULL;
3737
3738   if (warn_if_readin && data->v.quick->symtab)
3739     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3740              paddress (get_objfile_arch (objfile), pc));
3741
3742   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3743   gdb_assert (result != NULL);
3744   return result;
3745 }
3746
3747 static void
3748 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3749                           void *data, int need_fullname)
3750 {
3751   int i;
3752   struct cleanup *cleanup;
3753   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3754                                       NULL, xcalloc, xfree);
3755
3756   cleanup = make_cleanup_htab_delete (visited);
3757   dw2_setup (objfile);
3758
3759   /* The rule is CUs specify all the files, including those used by
3760      any TU, so there's no need to scan TUs here.
3761      We can ignore file names coming from already-expanded CUs.  */
3762
3763   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3764     {
3765       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3766
3767       if (per_cu->v.quick->symtab)
3768         {
3769           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3770                                         INSERT);
3771
3772           *slot = per_cu->v.quick->file_names;
3773         }
3774     }
3775
3776   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3777     {
3778       int j;
3779       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3780       struct quick_file_names *file_data;
3781       void **slot;
3782
3783       /* We only need to look at symtabs not already expanded.  */
3784       if (per_cu->v.quick->symtab)
3785         continue;
3786
3787       file_data = dw2_get_file_names (per_cu);
3788       if (file_data == NULL)
3789         continue;
3790
3791       slot = htab_find_slot (visited, file_data, INSERT);
3792       if (*slot)
3793         {
3794           /* Already visited.  */
3795           continue;
3796         }
3797       *slot = file_data;
3798
3799       for (j = 0; j < file_data->num_file_names; ++j)
3800         {
3801           const char *this_real_name;
3802
3803           if (need_fullname)
3804             this_real_name = dw2_get_real_path (objfile, file_data, j);
3805           else
3806             this_real_name = NULL;
3807           (*fun) (file_data->file_names[j], this_real_name, data);
3808         }
3809     }
3810
3811   do_cleanups (cleanup);
3812 }
3813
3814 static int
3815 dw2_has_symbols (struct objfile *objfile)
3816 {
3817   return 1;
3818 }
3819
3820 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3821 {
3822   dw2_has_symbols,
3823   dw2_find_last_source_symtab,
3824   dw2_forget_cached_source_info,
3825   dw2_map_symtabs_matching_filename,
3826   dw2_lookup_symbol,
3827   dw2_print_stats,
3828   dw2_dump,
3829   dw2_relocate,
3830   dw2_expand_symtabs_for_function,
3831   dw2_expand_all_symtabs,
3832   dw2_expand_symtabs_with_fullname,
3833   dw2_find_symbol_file,
3834   dw2_map_matching_symbols,
3835   dw2_expand_symtabs_matching,
3836   dw2_find_pc_sect_symtab,
3837   dw2_map_symbol_filenames
3838 };
3839
3840 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3841    file will use psymtabs, or 1 if using the GNU index.  */
3842
3843 int
3844 dwarf2_initialize_objfile (struct objfile *objfile)
3845 {
3846   /* If we're about to read full symbols, don't bother with the
3847      indices.  In this case we also don't care if some other debug
3848      format is making psymtabs, because they are all about to be
3849      expanded anyway.  */
3850   if ((objfile->flags & OBJF_READNOW))
3851     {
3852       int i;
3853
3854       dwarf2_per_objfile->using_index = 1;
3855       create_all_comp_units (objfile);
3856       create_all_type_units (objfile);
3857       dwarf2_per_objfile->quick_file_names_table =
3858         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3859
3860       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3861                        + dwarf2_per_objfile->n_type_units); ++i)
3862         {
3863           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3864
3865           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3866                                             struct dwarf2_per_cu_quick_data);
3867         }
3868
3869       /* Return 1 so that gdb sees the "quick" functions.  However,
3870          these functions will be no-ops because we will have expanded
3871          all symtabs.  */
3872       return 1;
3873     }
3874
3875   if (dwarf2_read_index (objfile))
3876     return 1;
3877
3878   return 0;
3879 }
3880
3881 \f
3882
3883 /* Build a partial symbol table.  */
3884
3885 void
3886 dwarf2_build_psymtabs (struct objfile *objfile)
3887 {
3888   volatile struct gdb_exception except;
3889
3890   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3891     {
3892       init_psymbol_list (objfile, 1024);
3893     }
3894
3895   TRY_CATCH (except, RETURN_MASK_ERROR)
3896     {
3897       /* This isn't really ideal: all the data we allocate on the
3898          objfile's obstack is still uselessly kept around.  However,
3899          freeing it seems unsafe.  */
3900       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3901
3902       dwarf2_build_psymtabs_hard (objfile);
3903       discard_cleanups (cleanups);
3904     }
3905   if (except.reason < 0)
3906     exception_print (gdb_stderr, except);
3907 }
3908
3909 /* Return the total length of the CU described by HEADER.  */
3910
3911 static unsigned int
3912 get_cu_length (const struct comp_unit_head *header)
3913 {
3914   return header->initial_length_size + header->length;
3915 }
3916
3917 /* Return TRUE if OFFSET is within CU_HEADER.  */
3918
3919 static inline int
3920 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3921 {
3922   sect_offset bottom = { cu_header->offset.sect_off };
3923   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3924
3925   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3926 }
3927
3928 /* Find the base address of the compilation unit for range lists and
3929    location lists.  It will normally be specified by DW_AT_low_pc.
3930    In DWARF-3 draft 4, the base address could be overridden by
3931    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3932    compilation units with discontinuous ranges.  */
3933
3934 static void
3935 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3936 {
3937   struct attribute *attr;
3938
3939   cu->base_known = 0;
3940   cu->base_address = 0;
3941
3942   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3943   if (attr)
3944     {
3945       cu->base_address = DW_ADDR (attr);
3946       cu->base_known = 1;
3947     }
3948   else
3949     {
3950       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3951       if (attr)
3952         {
3953           cu->base_address = DW_ADDR (attr);
3954           cu->base_known = 1;
3955         }
3956     }
3957 }
3958
3959 /* Read in the comp unit header information from the debug_info at info_ptr.
3960    NOTE: This leaves members offset, first_die_offset to be filled in
3961    by the caller.  */
3962
3963 static const gdb_byte *
3964 read_comp_unit_head (struct comp_unit_head *cu_header,
3965                      const gdb_byte *info_ptr, bfd *abfd)
3966 {
3967   int signed_addr;
3968   unsigned int bytes_read;
3969
3970   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3971   cu_header->initial_length_size = bytes_read;
3972   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3973   info_ptr += bytes_read;
3974   cu_header->version = read_2_bytes (abfd, info_ptr);
3975   info_ptr += 2;
3976   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3977                                              &bytes_read);
3978   info_ptr += bytes_read;
3979   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3980   info_ptr += 1;
3981   signed_addr = bfd_get_sign_extend_vma (abfd);
3982   if (signed_addr < 0)
3983     internal_error (__FILE__, __LINE__,
3984                     _("read_comp_unit_head: dwarf from non elf file"));
3985   cu_header->signed_addr_p = signed_addr;
3986
3987   return info_ptr;
3988 }
3989
3990 /* Helper function that returns the proper abbrev section for
3991    THIS_CU.  */
3992
3993 static struct dwarf2_section_info *
3994 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3995 {
3996   struct dwarf2_section_info *abbrev;
3997
3998   if (this_cu->is_dwz)
3999     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4000   else
4001     abbrev = &dwarf2_per_objfile->abbrev;
4002
4003   return abbrev;
4004 }
4005
4006 /* Subroutine of read_and_check_comp_unit_head and
4007    read_and_check_type_unit_head to simplify them.
4008    Perform various error checking on the header.  */
4009
4010 static void
4011 error_check_comp_unit_head (struct comp_unit_head *header,
4012                             struct dwarf2_section_info *section,
4013                             struct dwarf2_section_info *abbrev_section)
4014 {
4015   bfd *abfd = section->asection->owner;
4016   const char *filename = bfd_get_filename (abfd);
4017
4018   if (header->version != 2 && header->version != 3 && header->version != 4)
4019     error (_("Dwarf Error: wrong version in compilation unit header "
4020            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4021            filename);
4022
4023   if (header->abbrev_offset.sect_off
4024       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4025     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4026            "(offset 0x%lx + 6) [in module %s]"),
4027            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4028            filename);
4029
4030   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4031      avoid potential 32-bit overflow.  */
4032   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4033       > section->size)
4034     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4035            "(offset 0x%lx + 0) [in module %s]"),
4036            (long) header->length, (long) header->offset.sect_off,
4037            filename);
4038 }
4039
4040 /* Read in a CU/TU header and perform some basic error checking.
4041    The contents of the header are stored in HEADER.
4042    The result is a pointer to the start of the first DIE.  */
4043
4044 static const gdb_byte *
4045 read_and_check_comp_unit_head (struct comp_unit_head *header,
4046                                struct dwarf2_section_info *section,
4047                                struct dwarf2_section_info *abbrev_section,
4048                                const gdb_byte *info_ptr,
4049                                int is_debug_types_section)
4050 {
4051   const gdb_byte *beg_of_comp_unit = info_ptr;
4052   bfd *abfd = section->asection->owner;
4053
4054   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4055
4056   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4057
4058   /* If we're reading a type unit, skip over the signature and
4059      type_offset fields.  */
4060   if (is_debug_types_section)
4061     info_ptr += 8 /*signature*/ + header->offset_size;
4062
4063   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4064
4065   error_check_comp_unit_head (header, section, abbrev_section);
4066
4067   return info_ptr;
4068 }
4069
4070 /* Read in the types comp unit header information from .debug_types entry at
4071    types_ptr.  The result is a pointer to one past the end of the header.  */
4072
4073 static const gdb_byte *
4074 read_and_check_type_unit_head (struct comp_unit_head *header,
4075                                struct dwarf2_section_info *section,
4076                                struct dwarf2_section_info *abbrev_section,
4077                                const gdb_byte *info_ptr,
4078                                ULONGEST *signature,
4079                                cu_offset *type_offset_in_tu)
4080 {
4081   const gdb_byte *beg_of_comp_unit = info_ptr;
4082   bfd *abfd = section->asection->owner;
4083
4084   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4085
4086   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4087
4088   /* If we're reading a type unit, skip over the signature and
4089      type_offset fields.  */
4090   if (signature != NULL)
4091     *signature = read_8_bytes (abfd, info_ptr);
4092   info_ptr += 8;
4093   if (type_offset_in_tu != NULL)
4094     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4095                                                header->offset_size);
4096   info_ptr += header->offset_size;
4097
4098   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4099
4100   error_check_comp_unit_head (header, section, abbrev_section);
4101
4102   return info_ptr;
4103 }
4104
4105 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4106
4107 static sect_offset
4108 read_abbrev_offset (struct dwarf2_section_info *section,
4109                     sect_offset offset)
4110 {
4111   bfd *abfd = section->asection->owner;
4112   const gdb_byte *info_ptr;
4113   unsigned int length, initial_length_size, offset_size;
4114   sect_offset abbrev_offset;
4115
4116   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4117   info_ptr = section->buffer + offset.sect_off;
4118   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4119   offset_size = initial_length_size == 4 ? 4 : 8;
4120   info_ptr += initial_length_size + 2 /*version*/;
4121   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4122   return abbrev_offset;
4123 }
4124
4125 /* Allocate a new partial symtab for file named NAME and mark this new
4126    partial symtab as being an include of PST.  */
4127
4128 static void
4129 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4130                                struct objfile *objfile)
4131 {
4132   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4133
4134   if (!IS_ABSOLUTE_PATH (subpst->filename))
4135     {
4136       /* It shares objfile->objfile_obstack.  */
4137       subpst->dirname = pst->dirname;
4138     }
4139
4140   subpst->section_offsets = pst->section_offsets;
4141   subpst->textlow = 0;
4142   subpst->texthigh = 0;
4143
4144   subpst->dependencies = (struct partial_symtab **)
4145     obstack_alloc (&objfile->objfile_obstack,
4146                    sizeof (struct partial_symtab *));
4147   subpst->dependencies[0] = pst;
4148   subpst->number_of_dependencies = 1;
4149
4150   subpst->globals_offset = 0;
4151   subpst->n_global_syms = 0;
4152   subpst->statics_offset = 0;
4153   subpst->n_static_syms = 0;
4154   subpst->symtab = NULL;
4155   subpst->read_symtab = pst->read_symtab;
4156   subpst->readin = 0;
4157
4158   /* No private part is necessary for include psymtabs.  This property
4159      can be used to differentiate between such include psymtabs and
4160      the regular ones.  */
4161   subpst->read_symtab_private = NULL;
4162 }
4163
4164 /* Read the Line Number Program data and extract the list of files
4165    included by the source file represented by PST.  Build an include
4166    partial symtab for each of these included files.  */
4167
4168 static void
4169 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4170                                struct die_info *die,
4171                                struct partial_symtab *pst)
4172 {
4173   struct line_header *lh = NULL;
4174   struct attribute *attr;
4175
4176   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4177   if (attr)
4178     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4179   if (lh == NULL)
4180     return;  /* No linetable, so no includes.  */
4181
4182   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4183   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4184
4185   free_line_header (lh);
4186 }
4187
4188 static hashval_t
4189 hash_signatured_type (const void *item)
4190 {
4191   const struct signatured_type *sig_type = item;
4192
4193   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4194   return sig_type->signature;
4195 }
4196
4197 static int
4198 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4199 {
4200   const struct signatured_type *lhs = item_lhs;
4201   const struct signatured_type *rhs = item_rhs;
4202
4203   return lhs->signature == rhs->signature;
4204 }
4205
4206 /* Allocate a hash table for signatured types.  */
4207
4208 static htab_t
4209 allocate_signatured_type_table (struct objfile *objfile)
4210 {
4211   return htab_create_alloc_ex (41,
4212                                hash_signatured_type,
4213                                eq_signatured_type,
4214                                NULL,
4215                                &objfile->objfile_obstack,
4216                                hashtab_obstack_allocate,
4217                                dummy_obstack_deallocate);
4218 }
4219
4220 /* A helper function to add a signatured type CU to a table.  */
4221
4222 static int
4223 add_signatured_type_cu_to_table (void **slot, void *datum)
4224 {
4225   struct signatured_type *sigt = *slot;
4226   struct signatured_type ***datap = datum;
4227
4228   **datap = sigt;
4229   ++*datap;
4230
4231   return 1;
4232 }
4233
4234 /* Create the hash table of all entries in the .debug_types
4235    (or .debug_types.dwo) section(s).
4236    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4237    otherwise it is NULL.
4238
4239    The result is a pointer to the hash table or NULL if there are no types.
4240
4241    Note: This function processes DWO files only, not DWP files.  */
4242
4243 static htab_t
4244 create_debug_types_hash_table (struct dwo_file *dwo_file,
4245                                VEC (dwarf2_section_info_def) *types)
4246 {
4247   struct objfile *objfile = dwarf2_per_objfile->objfile;
4248   htab_t types_htab = NULL;
4249   int ix;
4250   struct dwarf2_section_info *section;
4251   struct dwarf2_section_info *abbrev_section;
4252
4253   if (VEC_empty (dwarf2_section_info_def, types))
4254     return NULL;
4255
4256   abbrev_section = (dwo_file != NULL
4257                     ? &dwo_file->sections.abbrev
4258                     : &dwarf2_per_objfile->abbrev);
4259
4260   if (dwarf2_read_debug)
4261     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4262                         dwo_file ? ".dwo" : "",
4263                         bfd_get_filename (abbrev_section->asection->owner));
4264
4265   for (ix = 0;
4266        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4267        ++ix)
4268     {
4269       bfd *abfd;
4270       const gdb_byte *info_ptr, *end_ptr;
4271       struct dwarf2_section_info *abbrev_section;
4272
4273       dwarf2_read_section (objfile, section);
4274       info_ptr = section->buffer;
4275
4276       if (info_ptr == NULL)
4277         continue;
4278
4279       /* We can't set abfd until now because the section may be empty or
4280          not present, in which case section->asection will be NULL.  */
4281       abfd = section->asection->owner;
4282
4283       if (dwo_file)
4284         abbrev_section = &dwo_file->sections.abbrev;
4285       else
4286         abbrev_section = &dwarf2_per_objfile->abbrev;
4287
4288       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4289          because we don't need to read any dies: the signature is in the
4290          header.  */
4291
4292       end_ptr = info_ptr + section->size;
4293       while (info_ptr < end_ptr)
4294         {
4295           sect_offset offset;
4296           cu_offset type_offset_in_tu;
4297           ULONGEST signature;
4298           struct signatured_type *sig_type;
4299           struct dwo_unit *dwo_tu;
4300           void **slot;
4301           const gdb_byte *ptr = info_ptr;
4302           struct comp_unit_head header;
4303           unsigned int length;
4304
4305           offset.sect_off = ptr - section->buffer;
4306
4307           /* We need to read the type's signature in order to build the hash
4308              table, but we don't need anything else just yet.  */
4309
4310           ptr = read_and_check_type_unit_head (&header, section,
4311                                                abbrev_section, ptr,
4312                                                &signature, &type_offset_in_tu);
4313
4314           length = get_cu_length (&header);
4315
4316           /* Skip dummy type units.  */
4317           if (ptr >= info_ptr + length
4318               || peek_abbrev_code (abfd, ptr) == 0)
4319             {
4320               info_ptr += length;
4321               continue;
4322             }
4323
4324           if (types_htab == NULL)
4325             {
4326               if (dwo_file)
4327                 types_htab = allocate_dwo_unit_table (objfile);
4328               else
4329                 types_htab = allocate_signatured_type_table (objfile);
4330             }
4331
4332           if (dwo_file)
4333             {
4334               sig_type = NULL;
4335               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4336                                        struct dwo_unit);
4337               dwo_tu->dwo_file = dwo_file;
4338               dwo_tu->signature = signature;
4339               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4340               dwo_tu->section = section;
4341               dwo_tu->offset = offset;
4342               dwo_tu->length = length;
4343             }
4344           else
4345             {
4346               /* N.B.: type_offset is not usable if this type uses a DWO file.
4347                  The real type_offset is in the DWO file.  */
4348               dwo_tu = NULL;
4349               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4350                                          struct signatured_type);
4351               sig_type->signature = signature;
4352               sig_type->type_offset_in_tu = type_offset_in_tu;
4353               sig_type->per_cu.objfile = objfile;
4354               sig_type->per_cu.is_debug_types = 1;
4355               sig_type->per_cu.section = section;
4356               sig_type->per_cu.offset = offset;
4357               sig_type->per_cu.length = length;
4358             }
4359
4360           slot = htab_find_slot (types_htab,
4361                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4362                                  INSERT);
4363           gdb_assert (slot != NULL);
4364           if (*slot != NULL)
4365             {
4366               sect_offset dup_offset;
4367
4368               if (dwo_file)
4369                 {
4370                   const struct dwo_unit *dup_tu = *slot;
4371
4372                   dup_offset = dup_tu->offset;
4373                 }
4374               else
4375                 {
4376                   const struct signatured_type *dup_tu = *slot;
4377
4378                   dup_offset = dup_tu->per_cu.offset;
4379                 }
4380
4381               complaint (&symfile_complaints,
4382                          _("debug type entry at offset 0x%x is duplicate to"
4383                            " the entry at offset 0x%x, signature %s"),
4384                          offset.sect_off, dup_offset.sect_off,
4385                          hex_string (signature));
4386             }
4387           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4388
4389           if (dwarf2_read_debug)
4390             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4391                                 offset.sect_off,
4392                                 hex_string (signature));
4393
4394           info_ptr += length;
4395         }
4396     }
4397
4398   return types_htab;
4399 }
4400
4401 /* Create the hash table of all entries in the .debug_types section,
4402    and initialize all_type_units.
4403    The result is zero if there is an error (e.g. missing .debug_types section),
4404    otherwise non-zero.  */
4405
4406 static int
4407 create_all_type_units (struct objfile *objfile)
4408 {
4409   htab_t types_htab;
4410   struct signatured_type **iter;
4411
4412   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4413   if (types_htab == NULL)
4414     {
4415       dwarf2_per_objfile->signatured_types = NULL;
4416       return 0;
4417     }
4418
4419   dwarf2_per_objfile->signatured_types = types_htab;
4420
4421   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4422   dwarf2_per_objfile->all_type_units
4423     = xmalloc (dwarf2_per_objfile->n_type_units
4424                * sizeof (struct signatured_type *));
4425   iter = &dwarf2_per_objfile->all_type_units[0];
4426   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4427   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4428               == dwarf2_per_objfile->n_type_units);
4429
4430   return 1;
4431 }
4432
4433 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4434    Fill in SIG_ENTRY with DWO_ENTRY.  */
4435
4436 static void
4437 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4438                                   struct signatured_type *sig_entry,
4439                                   struct dwo_unit *dwo_entry)
4440 {
4441   sig_entry->per_cu.section = dwo_entry->section;
4442   sig_entry->per_cu.offset = dwo_entry->offset;
4443   sig_entry->per_cu.length = dwo_entry->length;
4444   sig_entry->per_cu.reading_dwo_directly = 1;
4445   sig_entry->per_cu.objfile = objfile;
4446   gdb_assert (! sig_entry->per_cu.queued);
4447   gdb_assert (sig_entry->per_cu.cu == NULL);
4448   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4449   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4450   gdb_assert (sig_entry->signature == dwo_entry->signature);
4451   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4452   gdb_assert (sig_entry->type_unit_group == NULL);
4453   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4454   sig_entry->dwo_unit = dwo_entry;
4455 }
4456
4457 /* Subroutine of lookup_signatured_type.
4458    Create the signatured_type data structure for a TU to be read in
4459    directly from a DWO file, bypassing the stub.
4460    We do this for the case where there is no DWP file and we're using
4461    .gdb_index: When reading a CU we want to stay in the DWO file containing
4462    that CU.  Otherwise we could end up reading several other DWO files (due
4463    to comdat folding) to process the transitive closure of all the mentioned
4464    TUs, and that can be slow.  The current DWO file will have every type
4465    signature that it needs.
4466    We only do this for .gdb_index because in the psymtab case we already have
4467    to read all the DWOs to build the type unit groups.  */
4468
4469 static struct signatured_type *
4470 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4471 {
4472   struct objfile *objfile = dwarf2_per_objfile->objfile;
4473   struct dwo_file *dwo_file;
4474   struct dwo_unit find_dwo_entry, *dwo_entry;
4475   struct signatured_type find_sig_entry, *sig_entry;
4476
4477   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4478
4479   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4480      dwo_unit of the TU itself.  */
4481   dwo_file = cu->dwo_unit->dwo_file;
4482
4483   /* We only ever need to read in one copy of a signatured type.
4484      Just use the global signatured_types array.  If this is the first time
4485      we're reading this type, replace the recorded data from .gdb_index with
4486      this TU.  */
4487
4488   if (dwarf2_per_objfile->signatured_types == NULL)
4489     return NULL;
4490   find_sig_entry.signature = sig;
4491   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4492   if (sig_entry == NULL)
4493     return NULL;
4494   /* Have we already tried to read this TU?  */
4495   if (sig_entry->dwo_unit != NULL)
4496     return sig_entry;
4497
4498   /* Ok, this is the first time we're reading this TU.  */
4499   if (dwo_file->tus == NULL)
4500     return NULL;
4501   find_dwo_entry.signature = sig;
4502   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4503   if (dwo_entry == NULL)
4504     return NULL;
4505
4506   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4507   return sig_entry;
4508 }
4509
4510 /* Subroutine of lookup_dwp_signatured_type.
4511    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4512
4513 static struct signatured_type *
4514 add_type_unit (ULONGEST sig)
4515 {
4516   struct objfile *objfile = dwarf2_per_objfile->objfile;
4517   int n_type_units = dwarf2_per_objfile->n_type_units;
4518   struct signatured_type *sig_type;
4519   void **slot;
4520
4521   ++n_type_units;
4522   dwarf2_per_objfile->all_type_units =
4523     xrealloc (dwarf2_per_objfile->all_type_units,
4524               n_type_units * sizeof (struct signatured_type *));
4525   dwarf2_per_objfile->n_type_units = n_type_units;
4526   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4527                              struct signatured_type);
4528   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4529   sig_type->signature = sig;
4530   sig_type->per_cu.is_debug_types = 1;
4531   sig_type->per_cu.v.quick =
4532     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4533                     struct dwarf2_per_cu_quick_data);
4534   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4535                          sig_type, INSERT);
4536   gdb_assert (*slot == NULL);
4537   *slot = sig_type;
4538   /* The rest of sig_type must be filled in by the caller.  */
4539   return sig_type;
4540 }
4541
4542 /* Subroutine of lookup_signatured_type.
4543    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4544    then try the DWP file.
4545    Normally this "can't happen", but if there's a bug in signature
4546    generation and/or the DWP file is built incorrectly, it can happen.
4547    Using the type directly from the DWP file means we don't have the stub
4548    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4549    not critical.  [Eventually the stub may go away for type units anyway.]  */
4550
4551 static struct signatured_type *
4552 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4553 {
4554   struct objfile *objfile = dwarf2_per_objfile->objfile;
4555   struct dwp_file *dwp_file = get_dwp_file ();
4556   struct dwo_unit *dwo_entry;
4557   struct signatured_type find_sig_entry, *sig_entry;
4558
4559   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4560   gdb_assert (dwp_file != NULL);
4561
4562   if (dwarf2_per_objfile->signatured_types != NULL)
4563     {
4564       find_sig_entry.signature = sig;
4565       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4566                              &find_sig_entry);
4567       if (sig_entry != NULL)
4568         return sig_entry;
4569     }
4570
4571   /* This is the "shouldn't happen" case.
4572      Try the DWP file and hope for the best.  */
4573   if (dwp_file->tus == NULL)
4574     return NULL;
4575   dwo_entry = lookup_dwo_in_dwp (dwp_file, dwp_file->tus, NULL,
4576                                  sig, 1 /* is_debug_types */);
4577   if (dwo_entry == NULL)
4578     return NULL;
4579
4580   sig_entry = add_type_unit (sig);
4581   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4582
4583   /* The caller will signal a complaint if we return NULL.
4584      Here we don't return NULL but we still want to complain.  */
4585   complaint (&symfile_complaints,
4586              _("Bad type signature %s referenced by %s at 0x%x,"
4587                " coping by using copy in DWP [in module %s]"),
4588              hex_string (sig),
4589              cu->per_cu->is_debug_types ? "TU" : "CU",
4590              cu->per_cu->offset.sect_off,
4591              objfile->name);
4592
4593   return sig_entry;
4594 }
4595
4596 /* Lookup a signature based type for DW_FORM_ref_sig8.
4597    Returns NULL if signature SIG is not present in the table.
4598    It is up to the caller to complain about this.  */
4599
4600 static struct signatured_type *
4601 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4602 {
4603   if (cu->dwo_unit
4604       && dwarf2_per_objfile->using_index)
4605     {
4606       /* We're in a DWO/DWP file, and we're using .gdb_index.
4607          These cases require special processing.  */
4608       if (get_dwp_file () == NULL)
4609         return lookup_dwo_signatured_type (cu, sig);
4610       else
4611         return lookup_dwp_signatured_type (cu, sig);
4612     }
4613   else
4614     {
4615       struct signatured_type find_entry, *entry;
4616
4617       if (dwarf2_per_objfile->signatured_types == NULL)
4618         return NULL;
4619       find_entry.signature = sig;
4620       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4621       return entry;
4622     }
4623 }
4624 \f
4625 /* Low level DIE reading support.  */
4626
4627 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4628
4629 static void
4630 init_cu_die_reader (struct die_reader_specs *reader,
4631                     struct dwarf2_cu *cu,
4632                     struct dwarf2_section_info *section,
4633                     struct dwo_file *dwo_file)
4634 {
4635   gdb_assert (section->readin && section->buffer != NULL);
4636   reader->abfd = section->asection->owner;
4637   reader->cu = cu;
4638   reader->dwo_file = dwo_file;
4639   reader->die_section = section;
4640   reader->buffer = section->buffer;
4641   reader->buffer_end = section->buffer + section->size;
4642   reader->comp_dir = NULL;
4643 }
4644
4645 /* Subroutine of init_cutu_and_read_dies to simplify it.
4646    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4647    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4648    already.
4649
4650    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4651    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4652    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4653    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4654    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4655    COMP_DIR must be non-NULL.
4656    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4657    are filled in with the info of the DIE from the DWO file.
4658    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4659    provided an abbrev table to use.
4660    The result is non-zero if a valid (non-dummy) DIE was found.  */
4661
4662 static int
4663 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4664                         struct dwo_unit *dwo_unit,
4665                         int abbrev_table_provided,
4666                         struct die_info *stub_comp_unit_die,
4667                         const char *stub_comp_dir,
4668                         struct die_reader_specs *result_reader,
4669                         const gdb_byte **result_info_ptr,
4670                         struct die_info **result_comp_unit_die,
4671                         int *result_has_children)
4672 {
4673   struct objfile *objfile = dwarf2_per_objfile->objfile;
4674   struct dwarf2_cu *cu = this_cu->cu;
4675   struct dwarf2_section_info *section;
4676   bfd *abfd;
4677   const gdb_byte *begin_info_ptr, *info_ptr;
4678   const char *comp_dir_string;
4679   ULONGEST signature; /* Or dwo_id.  */
4680   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4681   int i,num_extra_attrs;
4682   struct dwarf2_section_info *dwo_abbrev_section;
4683   struct attribute *attr;
4684   struct attribute comp_dir_attr;
4685   struct die_info *comp_unit_die;
4686
4687   /* Both can't be provided.  */
4688   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4689
4690   /* These attributes aren't processed until later:
4691      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4692      However, the attribute is found in the stub which we won't have later.
4693      In order to not impose this complication on the rest of the code,
4694      we read them here and copy them to the DWO CU/TU die.  */
4695
4696   stmt_list = NULL;
4697   low_pc = NULL;
4698   high_pc = NULL;
4699   ranges = NULL;
4700   comp_dir = NULL;
4701
4702   if (stub_comp_unit_die != NULL)
4703     {
4704       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4705          DWO file.  */
4706       if (! this_cu->is_debug_types)
4707         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4708       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4709       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4710       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4711       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4712
4713       /* There should be a DW_AT_addr_base attribute here (if needed).
4714          We need the value before we can process DW_FORM_GNU_addr_index.  */
4715       cu->addr_base = 0;
4716       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4717       if (attr)
4718         cu->addr_base = DW_UNSND (attr);
4719
4720       /* There should be a DW_AT_ranges_base attribute here (if needed).
4721          We need the value before we can process DW_AT_ranges.  */
4722       cu->ranges_base = 0;
4723       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4724       if (attr)
4725         cu->ranges_base = DW_UNSND (attr);
4726     }
4727   else if (stub_comp_dir != NULL)
4728     {
4729       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4730       comp_dir = (struct attribute *)
4731         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4732       comp_dir->name = DW_AT_comp_dir;
4733       comp_dir->form = DW_FORM_string;
4734       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4735       DW_STRING (comp_dir) = stub_comp_dir;
4736     }
4737
4738   /* Set up for reading the DWO CU/TU.  */
4739   cu->dwo_unit = dwo_unit;
4740   section = dwo_unit->section;
4741   dwarf2_read_section (objfile, section);
4742   abfd = section->asection->owner;
4743   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4744   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4745   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4746
4747   if (this_cu->is_debug_types)
4748     {
4749       ULONGEST header_signature;
4750       cu_offset type_offset_in_tu;
4751       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4752
4753       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4754                                                 dwo_abbrev_section,
4755                                                 info_ptr,
4756                                                 &header_signature,
4757                                                 &type_offset_in_tu);
4758       /* This is not an assert because it can be caused by bad debug info.  */
4759       if (sig_type->signature != header_signature)
4760         {
4761           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4762                    " TU at offset 0x%x [in module %s]"),
4763                  hex_string (sig_type->signature),
4764                  hex_string (header_signature),
4765                  dwo_unit->offset.sect_off,
4766                  bfd_get_filename (abfd));
4767         }
4768       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4769       /* For DWOs coming from DWP files, we don't know the CU length
4770          nor the type's offset in the TU until now.  */
4771       dwo_unit->length = get_cu_length (&cu->header);
4772       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4773
4774       /* Establish the type offset that can be used to lookup the type.
4775          For DWO files, we don't know it until now.  */
4776       sig_type->type_offset_in_section.sect_off =
4777         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4778     }
4779   else
4780     {
4781       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4782                                                 dwo_abbrev_section,
4783                                                 info_ptr, 0);
4784       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4785       /* For DWOs coming from DWP files, we don't know the CU length
4786          until now.  */
4787       dwo_unit->length = get_cu_length (&cu->header);
4788     }
4789
4790   /* Replace the CU's original abbrev table with the DWO's.
4791      Reminder: We can't read the abbrev table until we've read the header.  */
4792   if (abbrev_table_provided)
4793     {
4794       /* Don't free the provided abbrev table, the caller of
4795          init_cutu_and_read_dies owns it.  */
4796       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4797       /* Ensure the DWO abbrev table gets freed.  */
4798       make_cleanup (dwarf2_free_abbrev_table, cu);
4799     }
4800   else
4801     {
4802       dwarf2_free_abbrev_table (cu);
4803       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4804       /* Leave any existing abbrev table cleanup as is.  */
4805     }
4806
4807   /* Read in the die, but leave space to copy over the attributes
4808      from the stub.  This has the benefit of simplifying the rest of
4809      the code - all the work to maintain the illusion of a single
4810      DW_TAG_{compile,type}_unit DIE is done here.  */
4811   num_extra_attrs = ((stmt_list != NULL)
4812                      + (low_pc != NULL)
4813                      + (high_pc != NULL)
4814                      + (ranges != NULL)
4815                      + (comp_dir != NULL));
4816   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4817                               result_has_children, num_extra_attrs);
4818
4819   /* Copy over the attributes from the stub to the DIE we just read in.  */
4820   comp_unit_die = *result_comp_unit_die;
4821   i = comp_unit_die->num_attrs;
4822   if (stmt_list != NULL)
4823     comp_unit_die->attrs[i++] = *stmt_list;
4824   if (low_pc != NULL)
4825     comp_unit_die->attrs[i++] = *low_pc;
4826   if (high_pc != NULL)
4827     comp_unit_die->attrs[i++] = *high_pc;
4828   if (ranges != NULL)
4829     comp_unit_die->attrs[i++] = *ranges;
4830   if (comp_dir != NULL)
4831     comp_unit_die->attrs[i++] = *comp_dir;
4832   comp_unit_die->num_attrs += num_extra_attrs;
4833
4834   if (dwarf2_die_debug)
4835     {
4836       fprintf_unfiltered (gdb_stdlog,
4837                           "Read die from %s@0x%x of %s:\n",
4838                           bfd_section_name (abfd, section->asection),
4839                           (unsigned) (begin_info_ptr - section->buffer),
4840                           bfd_get_filename (abfd));
4841       dump_die (comp_unit_die, dwarf2_die_debug);
4842     }
4843
4844   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
4845      TUs by skipping the stub and going directly to the entry in the DWO file.
4846      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
4847      to get it via circuitous means.  Blech.  */
4848   if (comp_dir != NULL)
4849     result_reader->comp_dir = DW_STRING (comp_dir);
4850
4851   /* Skip dummy compilation units.  */
4852   if (info_ptr >= begin_info_ptr + dwo_unit->length
4853       || peek_abbrev_code (abfd, info_ptr) == 0)
4854     return 0;
4855
4856   *result_info_ptr = info_ptr;
4857   return 1;
4858 }
4859
4860 /* Subroutine of init_cutu_and_read_dies to simplify it.
4861    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4862    Returns NULL if the specified DWO unit cannot be found.  */
4863
4864 static struct dwo_unit *
4865 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4866                  struct die_info *comp_unit_die)
4867 {
4868   struct dwarf2_cu *cu = this_cu->cu;
4869   struct attribute *attr;
4870   ULONGEST signature;
4871   struct dwo_unit *dwo_unit;
4872   const char *comp_dir, *dwo_name;
4873
4874   gdb_assert (cu != NULL);
4875
4876   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4877   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4878   gdb_assert (attr != NULL);
4879   dwo_name = DW_STRING (attr);
4880   comp_dir = NULL;
4881   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4882   if (attr)
4883     comp_dir = DW_STRING (attr);
4884
4885   if (this_cu->is_debug_types)
4886     {
4887       struct signatured_type *sig_type;
4888
4889       /* Since this_cu is the first member of struct signatured_type,
4890          we can go from a pointer to one to a pointer to the other.  */
4891       sig_type = (struct signatured_type *) this_cu;
4892       signature = sig_type->signature;
4893       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4894     }
4895   else
4896     {
4897       struct attribute *attr;
4898
4899       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4900       if (! attr)
4901         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4902                  " [in module %s]"),
4903                dwo_name, this_cu->objfile->name);
4904       signature = DW_UNSND (attr);
4905       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4906                                        signature);
4907     }
4908
4909   return dwo_unit;
4910 }
4911
4912 /* Subroutine of init_cutu_and_read_dies to simplify it.
4913    Read a TU directly from a DWO file, bypassing the stub.  */
4914
4915 static void
4916 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
4917                            die_reader_func_ftype *die_reader_func,
4918                            void *data)
4919 {
4920   struct dwarf2_cu *cu;
4921   struct signatured_type *sig_type;
4922   struct cleanup *cleanups, *free_cu_cleanup;
4923   struct die_reader_specs reader;
4924   const gdb_byte *info_ptr;
4925   struct die_info *comp_unit_die;
4926   int has_children;
4927
4928   /* Verify we can do the following downcast, and that we have the
4929      data we need.  */
4930   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
4931   sig_type = (struct signatured_type *) this_cu;
4932   gdb_assert (sig_type->dwo_unit != NULL);
4933
4934   cleanups = make_cleanup (null_cleanup, NULL);
4935
4936   gdb_assert (this_cu->cu == NULL);
4937   cu = xmalloc (sizeof (*cu));
4938   init_one_comp_unit (cu, this_cu);
4939   /* If an error occurs while loading, release our storage.  */
4940   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4941
4942   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
4943                               0 /* abbrev_table_provided */,
4944                               NULL /* stub_comp_unit_die */,
4945                               sig_type->dwo_unit->dwo_file->comp_dir,
4946                               &reader, &info_ptr,
4947                               &comp_unit_die, &has_children) == 0)
4948     {
4949       /* Dummy die.  */
4950       do_cleanups (cleanups);
4951       return;
4952     }
4953
4954   /* All the "real" work is done here.  */
4955   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4956
4957   /* This duplicates some code in init_cutu_and_read_dies,
4958      but the alternative is making the latter more complex.
4959      This function is only for the special case of using DWO files directly:
4960      no point in overly complicating the general case just to handle this.  */
4961   if (keep)
4962     {
4963       /* We've successfully allocated this compilation unit.  Let our
4964          caller clean it up when finished with it.  */
4965       discard_cleanups (free_cu_cleanup);
4966
4967       /* We can only discard free_cu_cleanup and all subsequent cleanups.
4968          So we have to manually free the abbrev table.  */
4969       dwarf2_free_abbrev_table (cu);
4970
4971       /* Link this CU into read_in_chain.  */
4972       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4973       dwarf2_per_objfile->read_in_chain = this_cu;
4974     }
4975   else
4976     do_cleanups (free_cu_cleanup);
4977
4978   do_cleanups (cleanups);
4979 }
4980
4981 /* Initialize a CU (or TU) and read its DIEs.
4982    If the CU defers to a DWO file, read the DWO file as well.
4983
4984    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4985    Otherwise the table specified in the comp unit header is read in and used.
4986    This is an optimization for when we already have the abbrev table.
4987
4988    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4989    Otherwise, a new CU is allocated with xmalloc.
4990
4991    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4992    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4993
4994    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4995    linker) then DIE_READER_FUNC will not get called.  */
4996
4997 static void
4998 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4999                          struct abbrev_table *abbrev_table,
5000                          int use_existing_cu, int keep,
5001                          die_reader_func_ftype *die_reader_func,
5002                          void *data)
5003 {
5004   struct objfile *objfile = dwarf2_per_objfile->objfile;
5005   struct dwarf2_section_info *section = this_cu->section;
5006   bfd *abfd = section->asection->owner;
5007   struct dwarf2_cu *cu;
5008   const gdb_byte *begin_info_ptr, *info_ptr;
5009   struct die_reader_specs reader;
5010   struct die_info *comp_unit_die;
5011   int has_children;
5012   struct attribute *attr;
5013   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5014   struct signatured_type *sig_type = NULL;
5015   struct dwarf2_section_info *abbrev_section;
5016   /* Non-zero if CU currently points to a DWO file and we need to
5017      reread it.  When this happens we need to reread the skeleton die
5018      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5019   int rereading_dwo_cu = 0;
5020
5021   if (dwarf2_die_debug)
5022     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5023                         this_cu->is_debug_types ? "type" : "comp",
5024                         this_cu->offset.sect_off);
5025
5026   if (use_existing_cu)
5027     gdb_assert (keep);
5028
5029   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5030      file (instead of going through the stub), short-circuit all of this.  */
5031   if (this_cu->reading_dwo_directly)
5032     {
5033       /* Narrow down the scope of possibilities to have to understand.  */
5034       gdb_assert (this_cu->is_debug_types);
5035       gdb_assert (abbrev_table == NULL);
5036       gdb_assert (!use_existing_cu);
5037       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5038       return;
5039     }
5040
5041   cleanups = make_cleanup (null_cleanup, NULL);
5042
5043   /* This is cheap if the section is already read in.  */
5044   dwarf2_read_section (objfile, section);
5045
5046   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5047
5048   abbrev_section = get_abbrev_section_for_cu (this_cu);
5049
5050   if (use_existing_cu && this_cu->cu != NULL)
5051     {
5052       cu = this_cu->cu;
5053
5054       /* If this CU is from a DWO file we need to start over, we need to
5055          refetch the attributes from the skeleton CU.
5056          This could be optimized by retrieving those attributes from when we
5057          were here the first time: the previous comp_unit_die was stored in
5058          comp_unit_obstack.  But there's no data yet that we need this
5059          optimization.  */
5060       if (cu->dwo_unit != NULL)
5061         rereading_dwo_cu = 1;
5062     }
5063   else
5064     {
5065       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5066       gdb_assert (this_cu->cu == NULL);
5067
5068       cu = xmalloc (sizeof (*cu));
5069       init_one_comp_unit (cu, this_cu);
5070
5071       /* If an error occurs while loading, release our storage.  */
5072       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5073     }
5074
5075   /* Get the header.  */
5076   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5077     {
5078       /* We already have the header, there's no need to read it in again.  */
5079       info_ptr += cu->header.first_die_offset.cu_off;
5080     }
5081   else
5082     {
5083       if (this_cu->is_debug_types)
5084         {
5085           ULONGEST signature;
5086           cu_offset type_offset_in_tu;
5087
5088           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5089                                                     abbrev_section, info_ptr,
5090                                                     &signature,
5091                                                     &type_offset_in_tu);
5092
5093           /* Since per_cu is the first member of struct signatured_type,
5094              we can go from a pointer to one to a pointer to the other.  */
5095           sig_type = (struct signatured_type *) this_cu;
5096           gdb_assert (sig_type->signature == signature);
5097           gdb_assert (sig_type->type_offset_in_tu.cu_off
5098                       == type_offset_in_tu.cu_off);
5099           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5100
5101           /* LENGTH has not been set yet for type units if we're
5102              using .gdb_index.  */
5103           this_cu->length = get_cu_length (&cu->header);
5104
5105           /* Establish the type offset that can be used to lookup the type.  */
5106           sig_type->type_offset_in_section.sect_off =
5107             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5108         }
5109       else
5110         {
5111           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5112                                                     abbrev_section,
5113                                                     info_ptr, 0);
5114
5115           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5116           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5117         }
5118     }
5119
5120   /* Skip dummy compilation units.  */
5121   if (info_ptr >= begin_info_ptr + this_cu->length
5122       || peek_abbrev_code (abfd, info_ptr) == 0)
5123     {
5124       do_cleanups (cleanups);
5125       return;
5126     }
5127
5128   /* If we don't have them yet, read the abbrevs for this compilation unit.
5129      And if we need to read them now, make sure they're freed when we're
5130      done.  Note that it's important that if the CU had an abbrev table
5131      on entry we don't free it when we're done: Somewhere up the call stack
5132      it may be in use.  */
5133   if (abbrev_table != NULL)
5134     {
5135       gdb_assert (cu->abbrev_table == NULL);
5136       gdb_assert (cu->header.abbrev_offset.sect_off
5137                   == abbrev_table->offset.sect_off);
5138       cu->abbrev_table = abbrev_table;
5139     }
5140   else if (cu->abbrev_table == NULL)
5141     {
5142       dwarf2_read_abbrevs (cu, abbrev_section);
5143       make_cleanup (dwarf2_free_abbrev_table, cu);
5144     }
5145   else if (rereading_dwo_cu)
5146     {
5147       dwarf2_free_abbrev_table (cu);
5148       dwarf2_read_abbrevs (cu, abbrev_section);
5149     }
5150
5151   /* Read the top level CU/TU die.  */
5152   init_cu_die_reader (&reader, cu, section, NULL);
5153   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5154
5155   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5156      from the DWO file.
5157      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5158      DWO CU, that this test will fail (the attribute will not be present).  */
5159   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5160   if (attr)
5161     {
5162       struct dwo_unit *dwo_unit;
5163       struct die_info *dwo_comp_unit_die;
5164
5165       if (has_children)
5166         {
5167           complaint (&symfile_complaints,
5168                      _("compilation unit with DW_AT_GNU_dwo_name"
5169                        " has children (offset 0x%x) [in module %s]"),
5170                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5171         }
5172       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5173       if (dwo_unit != NULL)
5174         {
5175           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5176                                       abbrev_table != NULL,
5177                                       comp_unit_die, NULL,
5178                                       &reader, &info_ptr,
5179                                       &dwo_comp_unit_die, &has_children) == 0)
5180             {
5181               /* Dummy die.  */
5182               do_cleanups (cleanups);
5183               return;
5184             }
5185           comp_unit_die = dwo_comp_unit_die;
5186         }
5187       else
5188         {
5189           /* Yikes, we couldn't find the rest of the DIE, we only have
5190              the stub.  A complaint has already been logged.  There's
5191              not much more we can do except pass on the stub DIE to
5192              die_reader_func.  We don't want to throw an error on bad
5193              debug info.  */
5194         }
5195     }
5196
5197   /* All of the above is setup for this call.  Yikes.  */
5198   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5199
5200   /* Done, clean up.  */
5201   if (free_cu_cleanup != NULL)
5202     {
5203       if (keep)
5204         {
5205           /* We've successfully allocated this compilation unit.  Let our
5206              caller clean it up when finished with it.  */
5207           discard_cleanups (free_cu_cleanup);
5208
5209           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5210              So we have to manually free the abbrev table.  */
5211           dwarf2_free_abbrev_table (cu);
5212
5213           /* Link this CU into read_in_chain.  */
5214           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5215           dwarf2_per_objfile->read_in_chain = this_cu;
5216         }
5217       else
5218         do_cleanups (free_cu_cleanup);
5219     }
5220
5221   do_cleanups (cleanups);
5222 }
5223
5224 /* Read CU/TU THIS_CU in section SECTION,
5225    but do not follow DW_AT_GNU_dwo_name if present.
5226    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5227    to have already done the lookup to find the DWO/DWP file).
5228
5229    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5230    THIS_CU->is_debug_types, but nothing else.
5231
5232    We fill in THIS_CU->length.
5233
5234    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5235    linker) then DIE_READER_FUNC will not get called.
5236
5237    THIS_CU->cu is always freed when done.
5238    This is done in order to not leave THIS_CU->cu in a state where we have
5239    to care whether it refers to the "main" CU or the DWO CU.  */
5240
5241 static void
5242 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5243                                    struct dwarf2_section_info *abbrev_section,
5244                                    struct dwo_file *dwo_file,
5245                                    die_reader_func_ftype *die_reader_func,
5246                                    void *data)
5247 {
5248   struct objfile *objfile = dwarf2_per_objfile->objfile;
5249   struct dwarf2_section_info *section = this_cu->section;
5250   bfd *abfd = section->asection->owner;
5251   struct dwarf2_cu cu;
5252   const gdb_byte *begin_info_ptr, *info_ptr;
5253   struct die_reader_specs reader;
5254   struct cleanup *cleanups;
5255   struct die_info *comp_unit_die;
5256   int has_children;
5257
5258   if (dwarf2_die_debug)
5259     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5260                         this_cu->is_debug_types ? "type" : "comp",
5261                         this_cu->offset.sect_off);
5262
5263   gdb_assert (this_cu->cu == NULL);
5264
5265   /* This is cheap if the section is already read in.  */
5266   dwarf2_read_section (objfile, section);
5267
5268   init_one_comp_unit (&cu, this_cu);
5269
5270   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5271
5272   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5273   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5274                                             abbrev_section, info_ptr,
5275                                             this_cu->is_debug_types);
5276
5277   this_cu->length = get_cu_length (&cu.header);
5278
5279   /* Skip dummy compilation units.  */
5280   if (info_ptr >= begin_info_ptr + this_cu->length
5281       || peek_abbrev_code (abfd, info_ptr) == 0)
5282     {
5283       do_cleanups (cleanups);
5284       return;
5285     }
5286
5287   dwarf2_read_abbrevs (&cu, abbrev_section);
5288   make_cleanup (dwarf2_free_abbrev_table, &cu);
5289
5290   init_cu_die_reader (&reader, &cu, section, dwo_file);
5291   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5292
5293   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5294
5295   do_cleanups (cleanups);
5296 }
5297
5298 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5299    does not lookup the specified DWO file.
5300    This cannot be used to read DWO files.
5301
5302    THIS_CU->cu is always freed when done.
5303    This is done in order to not leave THIS_CU->cu in a state where we have
5304    to care whether it refers to the "main" CU or the DWO CU.
5305    We can revisit this if the data shows there's a performance issue.  */
5306
5307 static void
5308 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5309                                 die_reader_func_ftype *die_reader_func,
5310                                 void *data)
5311 {
5312   init_cutu_and_read_dies_no_follow (this_cu,
5313                                      get_abbrev_section_for_cu (this_cu),
5314                                      NULL,
5315                                      die_reader_func, data);
5316 }
5317 \f
5318 /* Type Unit Groups.
5319
5320    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5321    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5322    so that all types coming from the same compilation (.o file) are grouped
5323    together.  A future step could be to put the types in the same symtab as
5324    the CU the types ultimately came from.  */
5325
5326 static hashval_t
5327 hash_type_unit_group (const void *item)
5328 {
5329   const struct type_unit_group *tu_group = item;
5330
5331   return hash_stmt_list_entry (&tu_group->hash);
5332 }
5333
5334 static int
5335 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5336 {
5337   const struct type_unit_group *lhs = item_lhs;
5338   const struct type_unit_group *rhs = item_rhs;
5339
5340   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5341 }
5342
5343 /* Allocate a hash table for type unit groups.  */
5344
5345 static htab_t
5346 allocate_type_unit_groups_table (void)
5347 {
5348   return htab_create_alloc_ex (3,
5349                                hash_type_unit_group,
5350                                eq_type_unit_group,
5351                                NULL,
5352                                &dwarf2_per_objfile->objfile->objfile_obstack,
5353                                hashtab_obstack_allocate,
5354                                dummy_obstack_deallocate);
5355 }
5356
5357 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5358    partial symtabs.  We combine several TUs per psymtab to not let the size
5359    of any one psymtab grow too big.  */
5360 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5361 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5362
5363 /* Helper routine for get_type_unit_group.
5364    Create the type_unit_group object used to hold one or more TUs.  */
5365
5366 static struct type_unit_group *
5367 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5368 {
5369   struct objfile *objfile = dwarf2_per_objfile->objfile;
5370   struct dwarf2_per_cu_data *per_cu;
5371   struct type_unit_group *tu_group;
5372
5373   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5374                              struct type_unit_group);
5375   per_cu = &tu_group->per_cu;
5376   per_cu->objfile = objfile;
5377
5378   if (dwarf2_per_objfile->using_index)
5379     {
5380       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5381                                         struct dwarf2_per_cu_quick_data);
5382     }
5383   else
5384     {
5385       unsigned int line_offset = line_offset_struct.sect_off;
5386       struct partial_symtab *pst;
5387       char *name;
5388
5389       /* Give the symtab a useful name for debug purposes.  */
5390       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5391         name = xstrprintf ("<type_units_%d>",
5392                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5393       else
5394         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5395
5396       pst = create_partial_symtab (per_cu, name);
5397       pst->anonymous = 1;
5398
5399       xfree (name);
5400     }
5401
5402   tu_group->hash.dwo_unit = cu->dwo_unit;
5403   tu_group->hash.line_offset = line_offset_struct;
5404
5405   return tu_group;
5406 }
5407
5408 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5409    STMT_LIST is a DW_AT_stmt_list attribute.  */
5410
5411 static struct type_unit_group *
5412 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5413 {
5414   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5415   struct type_unit_group *tu_group;
5416   void **slot;
5417   unsigned int line_offset;
5418   struct type_unit_group type_unit_group_for_lookup;
5419
5420   if (dwarf2_per_objfile->type_unit_groups == NULL)
5421     {
5422       dwarf2_per_objfile->type_unit_groups =
5423         allocate_type_unit_groups_table ();
5424     }
5425
5426   /* Do we need to create a new group, or can we use an existing one?  */
5427
5428   if (stmt_list)
5429     {
5430       line_offset = DW_UNSND (stmt_list);
5431       ++tu_stats->nr_symtab_sharers;
5432     }
5433   else
5434     {
5435       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5436          We can do various things here like create one group per TU or
5437          spread them over multiple groups to split up the expansion work.
5438          To avoid worst case scenarios (too many groups or too large groups)
5439          we, umm, group them in bunches.  */
5440       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5441                      | (tu_stats->nr_stmt_less_type_units
5442                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5443       ++tu_stats->nr_stmt_less_type_units;
5444     }
5445
5446   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5447   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5448   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5449                          &type_unit_group_for_lookup, INSERT);
5450   if (*slot != NULL)
5451     {
5452       tu_group = *slot;
5453       gdb_assert (tu_group != NULL);
5454     }
5455   else
5456     {
5457       sect_offset line_offset_struct;
5458
5459       line_offset_struct.sect_off = line_offset;
5460       tu_group = create_type_unit_group (cu, line_offset_struct);
5461       *slot = tu_group;
5462       ++tu_stats->nr_symtabs;
5463     }
5464
5465   return tu_group;
5466 }
5467
5468 /* Struct used to sort TUs by their abbreviation table offset.  */
5469
5470 struct tu_abbrev_offset
5471 {
5472   struct signatured_type *sig_type;
5473   sect_offset abbrev_offset;
5474 };
5475
5476 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5477
5478 static int
5479 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5480 {
5481   const struct tu_abbrev_offset * const *a = ap;
5482   const struct tu_abbrev_offset * const *b = bp;
5483   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5484   unsigned int boff = (*b)->abbrev_offset.sect_off;
5485
5486   return (aoff > boff) - (aoff < boff);
5487 }
5488
5489 /* A helper function to add a type_unit_group to a table.  */
5490
5491 static int
5492 add_type_unit_group_to_table (void **slot, void *datum)
5493 {
5494   struct type_unit_group *tu_group = *slot;
5495   struct type_unit_group ***datap = datum;
5496
5497   **datap = tu_group;
5498   ++*datap;
5499
5500   return 1;
5501 }
5502
5503 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5504    each one passing FUNC,DATA.
5505
5506    The efficiency is because we sort TUs by the abbrev table they use and
5507    only read each abbrev table once.  In one program there are 200K TUs
5508    sharing 8K abbrev tables.
5509
5510    The main purpose of this function is to support building the
5511    dwarf2_per_objfile->type_unit_groups table.
5512    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5513    can collapse the search space by grouping them by stmt_list.
5514    The savings can be significant, in the same program from above the 200K TUs
5515    share 8K stmt_list tables.
5516
5517    FUNC is expected to call get_type_unit_group, which will create the
5518    struct type_unit_group if necessary and add it to
5519    dwarf2_per_objfile->type_unit_groups.  */
5520
5521 static void
5522 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5523 {
5524   struct objfile *objfile = dwarf2_per_objfile->objfile;
5525   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5526   struct cleanup *cleanups;
5527   struct abbrev_table *abbrev_table;
5528   sect_offset abbrev_offset;
5529   struct tu_abbrev_offset *sorted_by_abbrev;
5530   struct type_unit_group **iter;
5531   int i;
5532
5533   /* It's up to the caller to not call us multiple times.  */
5534   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5535
5536   if (dwarf2_per_objfile->n_type_units == 0)
5537     return;
5538
5539   /* TUs typically share abbrev tables, and there can be way more TUs than
5540      abbrev tables.  Sort by abbrev table to reduce the number of times we
5541      read each abbrev table in.
5542      Alternatives are to punt or to maintain a cache of abbrev tables.
5543      This is simpler and efficient enough for now.
5544
5545      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5546      symtab to use).  Typically TUs with the same abbrev offset have the same
5547      stmt_list value too so in practice this should work well.
5548
5549      The basic algorithm here is:
5550
5551       sort TUs by abbrev table
5552       for each TU with same abbrev table:
5553         read abbrev table if first user
5554         read TU top level DIE
5555           [IWBN if DWO skeletons had DW_AT_stmt_list]
5556         call FUNC  */
5557
5558   if (dwarf2_read_debug)
5559     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5560
5561   /* Sort in a separate table to maintain the order of all_type_units
5562      for .gdb_index: TU indices directly index all_type_units.  */
5563   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5564                               dwarf2_per_objfile->n_type_units);
5565   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5566     {
5567       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5568
5569       sorted_by_abbrev[i].sig_type = sig_type;
5570       sorted_by_abbrev[i].abbrev_offset =
5571         read_abbrev_offset (sig_type->per_cu.section,
5572                             sig_type->per_cu.offset);
5573     }
5574   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5575   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5576          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5577
5578   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5579      called any number of times, so we don't reset tu_stats here.  */
5580
5581   abbrev_offset.sect_off = ~(unsigned) 0;
5582   abbrev_table = NULL;
5583   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5584
5585   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5586     {
5587       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5588
5589       /* Switch to the next abbrev table if necessary.  */
5590       if (abbrev_table == NULL
5591           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5592         {
5593           if (abbrev_table != NULL)
5594             {
5595               abbrev_table_free (abbrev_table);
5596               /* Reset to NULL in case abbrev_table_read_table throws
5597                  an error: abbrev_table_free_cleanup will get called.  */
5598               abbrev_table = NULL;
5599             }
5600           abbrev_offset = tu->abbrev_offset;
5601           abbrev_table =
5602             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5603                                      abbrev_offset);
5604           ++tu_stats->nr_uniq_abbrev_tables;
5605         }
5606
5607       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5608                                func, data);
5609     }
5610
5611   /* type_unit_groups can be NULL if there is an error in the debug info.
5612      Just create an empty table so the rest of gdb doesn't have to watch
5613      for this error case.  */
5614   if (dwarf2_per_objfile->type_unit_groups == NULL)
5615     {
5616       dwarf2_per_objfile->type_unit_groups =
5617         allocate_type_unit_groups_table ();
5618       dwarf2_per_objfile->n_type_unit_groups = 0;
5619     }
5620
5621   /* Create a vector of pointers to primary type units to make it easy to
5622      iterate over them and CUs.  See dw2_get_primary_cu.  */
5623   dwarf2_per_objfile->n_type_unit_groups =
5624     htab_elements (dwarf2_per_objfile->type_unit_groups);
5625   dwarf2_per_objfile->all_type_unit_groups =
5626     obstack_alloc (&objfile->objfile_obstack,
5627                    dwarf2_per_objfile->n_type_unit_groups
5628                    * sizeof (struct type_unit_group *));
5629   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5630   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5631                           add_type_unit_group_to_table, &iter);
5632   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5633               == dwarf2_per_objfile->n_type_unit_groups);
5634
5635   do_cleanups (cleanups);
5636
5637   if (dwarf2_read_debug)
5638     {
5639       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5640       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5641                           dwarf2_per_objfile->n_type_units);
5642       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5643                           tu_stats->nr_uniq_abbrev_tables);
5644       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5645                           tu_stats->nr_symtabs);
5646       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5647                           tu_stats->nr_symtab_sharers);
5648       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5649                           tu_stats->nr_stmt_less_type_units);
5650     }
5651 }
5652 \f
5653 /* Partial symbol tables.  */
5654
5655 /* Create a psymtab named NAME and assign it to PER_CU.
5656
5657    The caller must fill in the following details:
5658    dirname, textlow, texthigh.  */
5659
5660 static struct partial_symtab *
5661 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5662 {
5663   struct objfile *objfile = per_cu->objfile;
5664   struct partial_symtab *pst;
5665
5666   pst = start_psymtab_common (objfile, objfile->section_offsets,
5667                               name, 0,
5668                               objfile->global_psymbols.next,
5669                               objfile->static_psymbols.next);
5670
5671   pst->psymtabs_addrmap_supported = 1;
5672
5673   /* This is the glue that links PST into GDB's symbol API.  */
5674   pst->read_symtab_private = per_cu;
5675   pst->read_symtab = dwarf2_read_symtab;
5676   per_cu->v.psymtab = pst;
5677
5678   return pst;
5679 }
5680
5681 /* die_reader_func for process_psymtab_comp_unit.  */
5682
5683 static void
5684 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5685                                   const gdb_byte *info_ptr,
5686                                   struct die_info *comp_unit_die,
5687                                   int has_children,
5688                                   void *data)
5689 {
5690   struct dwarf2_cu *cu = reader->cu;
5691   struct objfile *objfile = cu->objfile;
5692   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5693   struct attribute *attr;
5694   CORE_ADDR baseaddr;
5695   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5696   struct partial_symtab *pst;
5697   int has_pc_info;
5698   const char *filename;
5699   int *want_partial_unit_ptr = data;
5700
5701   if (comp_unit_die->tag == DW_TAG_partial_unit
5702       && (want_partial_unit_ptr == NULL
5703           || !*want_partial_unit_ptr))
5704     return;
5705
5706   gdb_assert (! per_cu->is_debug_types);
5707
5708   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5709
5710   cu->list_in_scope = &file_symbols;
5711
5712   /* Allocate a new partial symbol table structure.  */
5713   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5714   if (attr == NULL || !DW_STRING (attr))
5715     filename = "";
5716   else
5717     filename = DW_STRING (attr);
5718
5719   pst = create_partial_symtab (per_cu, filename);
5720
5721   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5722   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5723   if (attr != NULL)
5724     pst->dirname = DW_STRING (attr);
5725
5726   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5727
5728   dwarf2_find_base_address (comp_unit_die, cu);
5729
5730   /* Possibly set the default values of LOWPC and HIGHPC from
5731      `DW_AT_ranges'.  */
5732   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5733                                       &best_highpc, cu, pst);
5734   if (has_pc_info == 1 && best_lowpc < best_highpc)
5735     /* Store the contiguous range if it is not empty; it can be empty for
5736        CUs with no code.  */
5737     addrmap_set_empty (objfile->psymtabs_addrmap,
5738                        best_lowpc + baseaddr,
5739                        best_highpc + baseaddr - 1, pst);
5740
5741   /* Check if comp unit has_children.
5742      If so, read the rest of the partial symbols from this comp unit.
5743      If not, there's no more debug_info for this comp unit.  */
5744   if (has_children)
5745     {
5746       struct partial_die_info *first_die;
5747       CORE_ADDR lowpc, highpc;
5748
5749       lowpc = ((CORE_ADDR) -1);
5750       highpc = ((CORE_ADDR) 0);
5751
5752       first_die = load_partial_dies (reader, info_ptr, 1);
5753
5754       scan_partial_symbols (first_die, &lowpc, &highpc,
5755                             ! has_pc_info, cu);
5756
5757       /* If we didn't find a lowpc, set it to highpc to avoid
5758          complaints from `maint check'.  */
5759       if (lowpc == ((CORE_ADDR) -1))
5760         lowpc = highpc;
5761
5762       /* If the compilation unit didn't have an explicit address range,
5763          then use the information extracted from its child dies.  */
5764       if (! has_pc_info)
5765         {
5766           best_lowpc = lowpc;
5767           best_highpc = highpc;
5768         }
5769     }
5770   pst->textlow = best_lowpc + baseaddr;
5771   pst->texthigh = best_highpc + baseaddr;
5772
5773   pst->n_global_syms = objfile->global_psymbols.next -
5774     (objfile->global_psymbols.list + pst->globals_offset);
5775   pst->n_static_syms = objfile->static_psymbols.next -
5776     (objfile->static_psymbols.list + pst->statics_offset);
5777   sort_pst_symbols (objfile, pst);
5778
5779   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5780     {
5781       int i;
5782       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5783       struct dwarf2_per_cu_data *iter;
5784
5785       /* Fill in 'dependencies' here; we fill in 'users' in a
5786          post-pass.  */
5787       pst->number_of_dependencies = len;
5788       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5789                                          len * sizeof (struct symtab *));
5790       for (i = 0;
5791            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5792                         i, iter);
5793            ++i)
5794         pst->dependencies[i] = iter->v.psymtab;
5795
5796       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5797     }
5798
5799   /* Get the list of files included in the current compilation unit,
5800      and build a psymtab for each of them.  */
5801   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5802
5803   if (dwarf2_read_debug)
5804     {
5805       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5806
5807       fprintf_unfiltered (gdb_stdlog,
5808                           "Psymtab for %s unit @0x%x: %s - %s"
5809                           ", %d global, %d static syms\n",
5810                           per_cu->is_debug_types ? "type" : "comp",
5811                           per_cu->offset.sect_off,
5812                           paddress (gdbarch, pst->textlow),
5813                           paddress (gdbarch, pst->texthigh),
5814                           pst->n_global_syms, pst->n_static_syms);
5815     }
5816 }
5817
5818 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5819    Process compilation unit THIS_CU for a psymtab.  */
5820
5821 static void
5822 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5823                            int want_partial_unit)
5824 {
5825   /* If this compilation unit was already read in, free the
5826      cached copy in order to read it in again.  This is
5827      necessary because we skipped some symbols when we first
5828      read in the compilation unit (see load_partial_dies).
5829      This problem could be avoided, but the benefit is unclear.  */
5830   if (this_cu->cu != NULL)
5831     free_one_cached_comp_unit (this_cu);
5832
5833   gdb_assert (! this_cu->is_debug_types);
5834   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5835                            process_psymtab_comp_unit_reader,
5836                            &want_partial_unit);
5837
5838   /* Age out any secondary CUs.  */
5839   age_cached_comp_units ();
5840 }
5841
5842 /* Reader function for build_type_psymtabs.  */
5843
5844 static void
5845 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5846                             const gdb_byte *info_ptr,
5847                             struct die_info *type_unit_die,
5848                             int has_children,
5849                             void *data)
5850 {
5851   struct objfile *objfile = dwarf2_per_objfile->objfile;
5852   struct dwarf2_cu *cu = reader->cu;
5853   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5854   struct signatured_type *sig_type;
5855   struct type_unit_group *tu_group;
5856   struct attribute *attr;
5857   struct partial_die_info *first_die;
5858   CORE_ADDR lowpc, highpc;
5859   struct partial_symtab *pst;
5860
5861   gdb_assert (data == NULL);
5862   gdb_assert (per_cu->is_debug_types);
5863   sig_type = (struct signatured_type *) per_cu;
5864
5865   if (! has_children)
5866     return;
5867
5868   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5869   tu_group = get_type_unit_group (cu, attr);
5870
5871   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5872
5873   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5874   cu->list_in_scope = &file_symbols;
5875   pst = create_partial_symtab (per_cu, "");
5876   pst->anonymous = 1;
5877
5878   first_die = load_partial_dies (reader, info_ptr, 1);
5879
5880   lowpc = (CORE_ADDR) -1;
5881   highpc = (CORE_ADDR) 0;
5882   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5883
5884   pst->n_global_syms = objfile->global_psymbols.next -
5885     (objfile->global_psymbols.list + pst->globals_offset);
5886   pst->n_static_syms = objfile->static_psymbols.next -
5887     (objfile->static_psymbols.list + pst->statics_offset);
5888   sort_pst_symbols (objfile, pst);
5889 }
5890
5891 /* Traversal function for build_type_psymtabs.  */
5892
5893 static int
5894 build_type_psymtab_dependencies (void **slot, void *info)
5895 {
5896   struct objfile *objfile = dwarf2_per_objfile->objfile;
5897   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5898   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5899   struct partial_symtab *pst = per_cu->v.psymtab;
5900   int len = VEC_length (sig_type_ptr, tu_group->tus);
5901   struct signatured_type *iter;
5902   int i;
5903
5904   gdb_assert (len > 0);
5905   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5906
5907   pst->number_of_dependencies = len;
5908   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5909                                      len * sizeof (struct psymtab *));
5910   for (i = 0;
5911        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5912        ++i)
5913     {
5914       gdb_assert (iter->per_cu.is_debug_types);
5915       pst->dependencies[i] = iter->per_cu.v.psymtab;
5916       iter->type_unit_group = tu_group;
5917     }
5918
5919   VEC_free (sig_type_ptr, tu_group->tus);
5920
5921   return 1;
5922 }
5923
5924 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5925    Build partial symbol tables for the .debug_types comp-units.  */
5926
5927 static void
5928 build_type_psymtabs (struct objfile *objfile)
5929 {
5930   if (! create_all_type_units (objfile))
5931     return;
5932
5933   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5934
5935   /* Now that all TUs have been processed we can fill in the dependencies.  */
5936   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5937                           build_type_psymtab_dependencies, NULL);
5938 }
5939
5940 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5941
5942 static void
5943 psymtabs_addrmap_cleanup (void *o)
5944 {
5945   struct objfile *objfile = o;
5946
5947   objfile->psymtabs_addrmap = NULL;
5948 }
5949
5950 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5951
5952 static void
5953 set_partial_user (struct objfile *objfile)
5954 {
5955   int i;
5956
5957   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5958     {
5959       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5960       struct partial_symtab *pst = per_cu->v.psymtab;
5961       int j;
5962
5963       if (pst == NULL)
5964         continue;
5965
5966       for (j = 0; j < pst->number_of_dependencies; ++j)
5967         {
5968           /* Set the 'user' field only if it is not already set.  */
5969           if (pst->dependencies[j]->user == NULL)
5970             pst->dependencies[j]->user = pst;
5971         }
5972     }
5973 }
5974
5975 /* Build the partial symbol table by doing a quick pass through the
5976    .debug_info and .debug_abbrev sections.  */
5977
5978 static void
5979 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5980 {
5981   struct cleanup *back_to, *addrmap_cleanup;
5982   struct obstack temp_obstack;
5983   int i;
5984
5985   if (dwarf2_read_debug)
5986     {
5987       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5988                           objfile->name);
5989     }
5990
5991   dwarf2_per_objfile->reading_partial_symbols = 1;
5992
5993   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5994
5995   /* Any cached compilation units will be linked by the per-objfile
5996      read_in_chain.  Make sure to free them when we're done.  */
5997   back_to = make_cleanup (free_cached_comp_units, NULL);
5998
5999   build_type_psymtabs (objfile);
6000
6001   create_all_comp_units (objfile);
6002
6003   /* Create a temporary address map on a temporary obstack.  We later
6004      copy this to the final obstack.  */
6005   obstack_init (&temp_obstack);
6006   make_cleanup_obstack_free (&temp_obstack);
6007   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6008   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6009
6010   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6011     {
6012       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6013
6014       process_psymtab_comp_unit (per_cu, 0);
6015     }
6016
6017   set_partial_user (objfile);
6018
6019   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6020                                                     &objfile->objfile_obstack);
6021   discard_cleanups (addrmap_cleanup);
6022
6023   do_cleanups (back_to);
6024
6025   if (dwarf2_read_debug)
6026     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6027                         objfile->name);
6028 }
6029
6030 /* die_reader_func for load_partial_comp_unit.  */
6031
6032 static void
6033 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6034                                const gdb_byte *info_ptr,
6035                                struct die_info *comp_unit_die,
6036                                int has_children,
6037                                void *data)
6038 {
6039   struct dwarf2_cu *cu = reader->cu;
6040
6041   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6042
6043   /* Check if comp unit has_children.
6044      If so, read the rest of the partial symbols from this comp unit.
6045      If not, there's no more debug_info for this comp unit.  */
6046   if (has_children)
6047     load_partial_dies (reader, info_ptr, 0);
6048 }
6049
6050 /* Load the partial DIEs for a secondary CU into memory.
6051    This is also used when rereading a primary CU with load_all_dies.  */
6052
6053 static void
6054 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6055 {
6056   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6057                            load_partial_comp_unit_reader, NULL);
6058 }
6059
6060 static void
6061 read_comp_units_from_section (struct objfile *objfile,
6062                               struct dwarf2_section_info *section,
6063                               unsigned int is_dwz,
6064                               int *n_allocated,
6065                               int *n_comp_units,
6066                               struct dwarf2_per_cu_data ***all_comp_units)
6067 {
6068   const gdb_byte *info_ptr;
6069   bfd *abfd = section->asection->owner;
6070
6071   if (dwarf2_read_debug)
6072     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6073                         section->asection->name, bfd_get_filename (abfd));
6074
6075   dwarf2_read_section (objfile, section);
6076
6077   info_ptr = section->buffer;
6078
6079   while (info_ptr < section->buffer + section->size)
6080     {
6081       unsigned int length, initial_length_size;
6082       struct dwarf2_per_cu_data *this_cu;
6083       sect_offset offset;
6084
6085       offset.sect_off = info_ptr - section->buffer;
6086
6087       /* Read just enough information to find out where the next
6088          compilation unit is.  */
6089       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6090
6091       /* Save the compilation unit for later lookup.  */
6092       this_cu = obstack_alloc (&objfile->objfile_obstack,
6093                                sizeof (struct dwarf2_per_cu_data));
6094       memset (this_cu, 0, sizeof (*this_cu));
6095       this_cu->offset = offset;
6096       this_cu->length = length + initial_length_size;
6097       this_cu->is_dwz = is_dwz;
6098       this_cu->objfile = objfile;
6099       this_cu->section = section;
6100
6101       if (*n_comp_units == *n_allocated)
6102         {
6103           *n_allocated *= 2;
6104           *all_comp_units = xrealloc (*all_comp_units,
6105                                       *n_allocated
6106                                       * sizeof (struct dwarf2_per_cu_data *));
6107         }
6108       (*all_comp_units)[*n_comp_units] = this_cu;
6109       ++*n_comp_units;
6110
6111       info_ptr = info_ptr + this_cu->length;
6112     }
6113 }
6114
6115 /* Create a list of all compilation units in OBJFILE.
6116    This is only done for -readnow and building partial symtabs.  */
6117
6118 static void
6119 create_all_comp_units (struct objfile *objfile)
6120 {
6121   int n_allocated;
6122   int n_comp_units;
6123   struct dwarf2_per_cu_data **all_comp_units;
6124
6125   n_comp_units = 0;
6126   n_allocated = 10;
6127   all_comp_units = xmalloc (n_allocated
6128                             * sizeof (struct dwarf2_per_cu_data *));
6129
6130   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6131                                 &n_allocated, &n_comp_units, &all_comp_units);
6132
6133   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
6134     {
6135       struct dwz_file *dwz = dwarf2_get_dwz_file ();
6136
6137       read_comp_units_from_section (objfile, &dwz->info, 1,
6138                                     &n_allocated, &n_comp_units,
6139                                     &all_comp_units);
6140     }
6141
6142   dwarf2_per_objfile->all_comp_units
6143     = obstack_alloc (&objfile->objfile_obstack,
6144                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6145   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6146           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6147   xfree (all_comp_units);
6148   dwarf2_per_objfile->n_comp_units = n_comp_units;
6149 }
6150
6151 /* Process all loaded DIEs for compilation unit CU, starting at
6152    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6153    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6154    DW_AT_ranges).  If NEED_PC is set, then this function will set
6155    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6156    and record the covered ranges in the addrmap.  */
6157
6158 static void
6159 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6160                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6161 {
6162   struct partial_die_info *pdi;
6163
6164   /* Now, march along the PDI's, descending into ones which have
6165      interesting children but skipping the children of the other ones,
6166      until we reach the end of the compilation unit.  */
6167
6168   pdi = first_die;
6169
6170   while (pdi != NULL)
6171     {
6172       fixup_partial_die (pdi, cu);
6173
6174       /* Anonymous namespaces or modules have no name but have interesting
6175          children, so we need to look at them.  Ditto for anonymous
6176          enums.  */
6177
6178       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6179           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6180           || pdi->tag == DW_TAG_imported_unit)
6181         {
6182           switch (pdi->tag)
6183             {
6184             case DW_TAG_subprogram:
6185               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6186               break;
6187             case DW_TAG_constant:
6188             case DW_TAG_variable:
6189             case DW_TAG_typedef:
6190             case DW_TAG_union_type:
6191               if (!pdi->is_declaration)
6192                 {
6193                   add_partial_symbol (pdi, cu);
6194                 }
6195               break;
6196             case DW_TAG_class_type:
6197             case DW_TAG_interface_type:
6198             case DW_TAG_structure_type:
6199               if (!pdi->is_declaration)
6200                 {
6201                   add_partial_symbol (pdi, cu);
6202                 }
6203               break;
6204             case DW_TAG_enumeration_type:
6205               if (!pdi->is_declaration)
6206                 add_partial_enumeration (pdi, cu);
6207               break;
6208             case DW_TAG_base_type:
6209             case DW_TAG_subrange_type:
6210               /* File scope base type definitions are added to the partial
6211                  symbol table.  */
6212               add_partial_symbol (pdi, cu);
6213               break;
6214             case DW_TAG_namespace:
6215               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6216               break;
6217             case DW_TAG_module:
6218               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6219               break;
6220             case DW_TAG_imported_unit:
6221               {
6222                 struct dwarf2_per_cu_data *per_cu;
6223
6224                 /* For now we don't handle imported units in type units.  */
6225                 if (cu->per_cu->is_debug_types)
6226                   {
6227                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6228                              " supported in type units [in module %s]"),
6229                            cu->objfile->name);
6230                   }
6231
6232                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6233                                                            pdi->is_dwz,
6234                                                            cu->objfile);
6235
6236                 /* Go read the partial unit, if needed.  */
6237                 if (per_cu->v.psymtab == NULL)
6238                   process_psymtab_comp_unit (per_cu, 1);
6239
6240                 VEC_safe_push (dwarf2_per_cu_ptr,
6241                                cu->per_cu->imported_symtabs, per_cu);
6242               }
6243               break;
6244             default:
6245               break;
6246             }
6247         }
6248
6249       /* If the die has a sibling, skip to the sibling.  */
6250
6251       pdi = pdi->die_sibling;
6252     }
6253 }
6254
6255 /* Functions used to compute the fully scoped name of a partial DIE.
6256
6257    Normally, this is simple.  For C++, the parent DIE's fully scoped
6258    name is concatenated with "::" and the partial DIE's name.  For
6259    Java, the same thing occurs except that "." is used instead of "::".
6260    Enumerators are an exception; they use the scope of their parent
6261    enumeration type, i.e. the name of the enumeration type is not
6262    prepended to the enumerator.
6263
6264    There are two complexities.  One is DW_AT_specification; in this
6265    case "parent" means the parent of the target of the specification,
6266    instead of the direct parent of the DIE.  The other is compilers
6267    which do not emit DW_TAG_namespace; in this case we try to guess
6268    the fully qualified name of structure types from their members'
6269    linkage names.  This must be done using the DIE's children rather
6270    than the children of any DW_AT_specification target.  We only need
6271    to do this for structures at the top level, i.e. if the target of
6272    any DW_AT_specification (if any; otherwise the DIE itself) does not
6273    have a parent.  */
6274
6275 /* Compute the scope prefix associated with PDI's parent, in
6276    compilation unit CU.  The result will be allocated on CU's
6277    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6278    field.  NULL is returned if no prefix is necessary.  */
6279 static const char *
6280 partial_die_parent_scope (struct partial_die_info *pdi,
6281                           struct dwarf2_cu *cu)
6282 {
6283   const char *grandparent_scope;
6284   struct partial_die_info *parent, *real_pdi;
6285
6286   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6287      then this means the parent of the specification DIE.  */
6288
6289   real_pdi = pdi;
6290   while (real_pdi->has_specification)
6291     real_pdi = find_partial_die (real_pdi->spec_offset,
6292                                  real_pdi->spec_is_dwz, cu);
6293
6294   parent = real_pdi->die_parent;
6295   if (parent == NULL)
6296     return NULL;
6297
6298   if (parent->scope_set)
6299     return parent->scope;
6300
6301   fixup_partial_die (parent, cu);
6302
6303   grandparent_scope = partial_die_parent_scope (parent, cu);
6304
6305   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6306      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6307      Work around this problem here.  */
6308   if (cu->language == language_cplus
6309       && parent->tag == DW_TAG_namespace
6310       && strcmp (parent->name, "::") == 0
6311       && grandparent_scope == NULL)
6312     {
6313       parent->scope = NULL;
6314       parent->scope_set = 1;
6315       return NULL;
6316     }
6317
6318   if (pdi->tag == DW_TAG_enumerator)
6319     /* Enumerators should not get the name of the enumeration as a prefix.  */
6320     parent->scope = grandparent_scope;
6321   else if (parent->tag == DW_TAG_namespace
6322       || parent->tag == DW_TAG_module
6323       || parent->tag == DW_TAG_structure_type
6324       || parent->tag == DW_TAG_class_type
6325       || parent->tag == DW_TAG_interface_type
6326       || parent->tag == DW_TAG_union_type
6327       || parent->tag == DW_TAG_enumeration_type)
6328     {
6329       if (grandparent_scope == NULL)
6330         parent->scope = parent->name;
6331       else
6332         parent->scope = typename_concat (&cu->comp_unit_obstack,
6333                                          grandparent_scope,
6334                                          parent->name, 0, cu);
6335     }
6336   else
6337     {
6338       /* FIXME drow/2004-04-01: What should we be doing with
6339          function-local names?  For partial symbols, we should probably be
6340          ignoring them.  */
6341       complaint (&symfile_complaints,
6342                  _("unhandled containing DIE tag %d for DIE at %d"),
6343                  parent->tag, pdi->offset.sect_off);
6344       parent->scope = grandparent_scope;
6345     }
6346
6347   parent->scope_set = 1;
6348   return parent->scope;
6349 }
6350
6351 /* Return the fully scoped name associated with PDI, from compilation unit
6352    CU.  The result will be allocated with malloc.  */
6353
6354 static char *
6355 partial_die_full_name (struct partial_die_info *pdi,
6356                        struct dwarf2_cu *cu)
6357 {
6358   const char *parent_scope;
6359
6360   /* If this is a template instantiation, we can not work out the
6361      template arguments from partial DIEs.  So, unfortunately, we have
6362      to go through the full DIEs.  At least any work we do building
6363      types here will be reused if full symbols are loaded later.  */
6364   if (pdi->has_template_arguments)
6365     {
6366       fixup_partial_die (pdi, cu);
6367
6368       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6369         {
6370           struct die_info *die;
6371           struct attribute attr;
6372           struct dwarf2_cu *ref_cu = cu;
6373
6374           /* DW_FORM_ref_addr is using section offset.  */
6375           attr.name = 0;
6376           attr.form = DW_FORM_ref_addr;
6377           attr.u.unsnd = pdi->offset.sect_off;
6378           die = follow_die_ref (NULL, &attr, &ref_cu);
6379
6380           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6381         }
6382     }
6383
6384   parent_scope = partial_die_parent_scope (pdi, cu);
6385   if (parent_scope == NULL)
6386     return NULL;
6387   else
6388     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6389 }
6390
6391 static void
6392 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6393 {
6394   struct objfile *objfile = cu->objfile;
6395   CORE_ADDR addr = 0;
6396   const char *actual_name = NULL;
6397   CORE_ADDR baseaddr;
6398   char *built_actual_name;
6399
6400   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6401
6402   built_actual_name = partial_die_full_name (pdi, cu);
6403   if (built_actual_name != NULL)
6404     actual_name = built_actual_name;
6405
6406   if (actual_name == NULL)
6407     actual_name = pdi->name;
6408
6409   switch (pdi->tag)
6410     {
6411     case DW_TAG_subprogram:
6412       if (pdi->is_external || cu->language == language_ada)
6413         {
6414           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6415              of the global scope.  But in Ada, we want to be able to access
6416              nested procedures globally.  So all Ada subprograms are stored
6417              in the global scope.  */
6418           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6419              mst_text, objfile); */
6420           add_psymbol_to_list (actual_name, strlen (actual_name),
6421                                built_actual_name != NULL,
6422                                VAR_DOMAIN, LOC_BLOCK,
6423                                &objfile->global_psymbols,
6424                                0, pdi->lowpc + baseaddr,
6425                                cu->language, objfile);
6426         }
6427       else
6428         {
6429           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6430              mst_file_text, objfile); */
6431           add_psymbol_to_list (actual_name, strlen (actual_name),
6432                                built_actual_name != NULL,
6433                                VAR_DOMAIN, LOC_BLOCK,
6434                                &objfile->static_psymbols,
6435                                0, pdi->lowpc + baseaddr,
6436                                cu->language, objfile);
6437         }
6438       break;
6439     case DW_TAG_constant:
6440       {
6441         struct psymbol_allocation_list *list;
6442
6443         if (pdi->is_external)
6444           list = &objfile->global_psymbols;
6445         else
6446           list = &objfile->static_psymbols;
6447         add_psymbol_to_list (actual_name, strlen (actual_name),
6448                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6449                              list, 0, 0, cu->language, objfile);
6450       }
6451       break;
6452     case DW_TAG_variable:
6453       if (pdi->d.locdesc)
6454         addr = decode_locdesc (pdi->d.locdesc, cu);
6455
6456       if (pdi->d.locdesc
6457           && addr == 0
6458           && !dwarf2_per_objfile->has_section_at_zero)
6459         {
6460           /* A global or static variable may also have been stripped
6461              out by the linker if unused, in which case its address
6462              will be nullified; do not add such variables into partial
6463              symbol table then.  */
6464         }
6465       else if (pdi->is_external)
6466         {
6467           /* Global Variable.
6468              Don't enter into the minimal symbol tables as there is
6469              a minimal symbol table entry from the ELF symbols already.
6470              Enter into partial symbol table if it has a location
6471              descriptor or a type.
6472              If the location descriptor is missing, new_symbol will create
6473              a LOC_UNRESOLVED symbol, the address of the variable will then
6474              be determined from the minimal symbol table whenever the variable
6475              is referenced.
6476              The address for the partial symbol table entry is not
6477              used by GDB, but it comes in handy for debugging partial symbol
6478              table building.  */
6479
6480           if (pdi->d.locdesc || pdi->has_type)
6481             add_psymbol_to_list (actual_name, strlen (actual_name),
6482                                  built_actual_name != NULL,
6483                                  VAR_DOMAIN, LOC_STATIC,
6484                                  &objfile->global_psymbols,
6485                                  0, addr + baseaddr,
6486                                  cu->language, objfile);
6487         }
6488       else
6489         {
6490           /* Static Variable.  Skip symbols without location descriptors.  */
6491           if (pdi->d.locdesc == NULL)
6492             {
6493               xfree (built_actual_name);
6494               return;
6495             }
6496           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6497              mst_file_data, objfile); */
6498           add_psymbol_to_list (actual_name, strlen (actual_name),
6499                                built_actual_name != NULL,
6500                                VAR_DOMAIN, LOC_STATIC,
6501                                &objfile->static_psymbols,
6502                                0, addr + baseaddr,
6503                                cu->language, objfile);
6504         }
6505       break;
6506     case DW_TAG_typedef:
6507     case DW_TAG_base_type:
6508     case DW_TAG_subrange_type:
6509       add_psymbol_to_list (actual_name, strlen (actual_name),
6510                            built_actual_name != NULL,
6511                            VAR_DOMAIN, LOC_TYPEDEF,
6512                            &objfile->static_psymbols,
6513                            0, (CORE_ADDR) 0, cu->language, objfile);
6514       break;
6515     case DW_TAG_namespace:
6516       add_psymbol_to_list (actual_name, strlen (actual_name),
6517                            built_actual_name != NULL,
6518                            VAR_DOMAIN, LOC_TYPEDEF,
6519                            &objfile->global_psymbols,
6520                            0, (CORE_ADDR) 0, cu->language, objfile);
6521       break;
6522     case DW_TAG_class_type:
6523     case DW_TAG_interface_type:
6524     case DW_TAG_structure_type:
6525     case DW_TAG_union_type:
6526     case DW_TAG_enumeration_type:
6527       /* Skip external references.  The DWARF standard says in the section
6528          about "Structure, Union, and Class Type Entries": "An incomplete
6529          structure, union or class type is represented by a structure,
6530          union or class entry that does not have a byte size attribute
6531          and that has a DW_AT_declaration attribute."  */
6532       if (!pdi->has_byte_size && pdi->is_declaration)
6533         {
6534           xfree (built_actual_name);
6535           return;
6536         }
6537
6538       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6539          static vs. global.  */
6540       add_psymbol_to_list (actual_name, strlen (actual_name),
6541                            built_actual_name != NULL,
6542                            STRUCT_DOMAIN, LOC_TYPEDEF,
6543                            (cu->language == language_cplus
6544                             || cu->language == language_java)
6545                            ? &objfile->global_psymbols
6546                            : &objfile->static_psymbols,
6547                            0, (CORE_ADDR) 0, cu->language, objfile);
6548
6549       break;
6550     case DW_TAG_enumerator:
6551       add_psymbol_to_list (actual_name, strlen (actual_name),
6552                            built_actual_name != NULL,
6553                            VAR_DOMAIN, LOC_CONST,
6554                            (cu->language == language_cplus
6555                             || cu->language == language_java)
6556                            ? &objfile->global_psymbols
6557                            : &objfile->static_psymbols,
6558                            0, (CORE_ADDR) 0, cu->language, objfile);
6559       break;
6560     default:
6561       break;
6562     }
6563
6564   xfree (built_actual_name);
6565 }
6566
6567 /* Read a partial die corresponding to a namespace; also, add a symbol
6568    corresponding to that namespace to the symbol table.  NAMESPACE is
6569    the name of the enclosing namespace.  */
6570
6571 static void
6572 add_partial_namespace (struct partial_die_info *pdi,
6573                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6574                        int need_pc, struct dwarf2_cu *cu)
6575 {
6576   /* Add a symbol for the namespace.  */
6577
6578   add_partial_symbol (pdi, cu);
6579
6580   /* Now scan partial symbols in that namespace.  */
6581
6582   if (pdi->has_children)
6583     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6584 }
6585
6586 /* Read a partial die corresponding to a Fortran module.  */
6587
6588 static void
6589 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6590                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6591 {
6592   /* Now scan partial symbols in that module.  */
6593
6594   if (pdi->has_children)
6595     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6596 }
6597
6598 /* Read a partial die corresponding to a subprogram and create a partial
6599    symbol for that subprogram.  When the CU language allows it, this
6600    routine also defines a partial symbol for each nested subprogram
6601    that this subprogram contains.
6602
6603    DIE my also be a lexical block, in which case we simply search
6604    recursively for suprograms defined inside that lexical block.
6605    Again, this is only performed when the CU language allows this
6606    type of definitions.  */
6607
6608 static void
6609 add_partial_subprogram (struct partial_die_info *pdi,
6610                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6611                         int need_pc, struct dwarf2_cu *cu)
6612 {
6613   if (pdi->tag == DW_TAG_subprogram)
6614     {
6615       if (pdi->has_pc_info)
6616         {
6617           if (pdi->lowpc < *lowpc)
6618             *lowpc = pdi->lowpc;
6619           if (pdi->highpc > *highpc)
6620             *highpc = pdi->highpc;
6621           if (need_pc)
6622             {
6623               CORE_ADDR baseaddr;
6624               struct objfile *objfile = cu->objfile;
6625
6626               baseaddr = ANOFFSET (objfile->section_offsets,
6627                                    SECT_OFF_TEXT (objfile));
6628               addrmap_set_empty (objfile->psymtabs_addrmap,
6629                                  pdi->lowpc + baseaddr,
6630                                  pdi->highpc - 1 + baseaddr,
6631                                  cu->per_cu->v.psymtab);
6632             }
6633         }
6634
6635       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6636         {
6637           if (!pdi->is_declaration)
6638             /* Ignore subprogram DIEs that do not have a name, they are
6639                illegal.  Do not emit a complaint at this point, we will
6640                do so when we convert this psymtab into a symtab.  */
6641             if (pdi->name)
6642               add_partial_symbol (pdi, cu);
6643         }
6644     }
6645
6646   if (! pdi->has_children)
6647     return;
6648
6649   if (cu->language == language_ada)
6650     {
6651       pdi = pdi->die_child;
6652       while (pdi != NULL)
6653         {
6654           fixup_partial_die (pdi, cu);
6655           if (pdi->tag == DW_TAG_subprogram
6656               || pdi->tag == DW_TAG_lexical_block)
6657             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6658           pdi = pdi->die_sibling;
6659         }
6660     }
6661 }
6662
6663 /* Read a partial die corresponding to an enumeration type.  */
6664
6665 static void
6666 add_partial_enumeration (struct partial_die_info *enum_pdi,
6667                          struct dwarf2_cu *cu)
6668 {
6669   struct partial_die_info *pdi;
6670
6671   if (enum_pdi->name != NULL)
6672     add_partial_symbol (enum_pdi, cu);
6673
6674   pdi = enum_pdi->die_child;
6675   while (pdi)
6676     {
6677       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6678         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6679       else
6680         add_partial_symbol (pdi, cu);
6681       pdi = pdi->die_sibling;
6682     }
6683 }
6684
6685 /* Return the initial uleb128 in the die at INFO_PTR.  */
6686
6687 static unsigned int
6688 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6689 {
6690   unsigned int bytes_read;
6691
6692   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6693 }
6694
6695 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6696    Return the corresponding abbrev, or NULL if the number is zero (indicating
6697    an empty DIE).  In either case *BYTES_READ will be set to the length of
6698    the initial number.  */
6699
6700 static struct abbrev_info *
6701 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6702                  struct dwarf2_cu *cu)
6703 {
6704   bfd *abfd = cu->objfile->obfd;
6705   unsigned int abbrev_number;
6706   struct abbrev_info *abbrev;
6707
6708   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6709
6710   if (abbrev_number == 0)
6711     return NULL;
6712
6713   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6714   if (!abbrev)
6715     {
6716       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6717              abbrev_number, bfd_get_filename (abfd));
6718     }
6719
6720   return abbrev;
6721 }
6722
6723 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6724    Returns a pointer to the end of a series of DIEs, terminated by an empty
6725    DIE.  Any children of the skipped DIEs will also be skipped.  */
6726
6727 static const gdb_byte *
6728 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6729 {
6730   struct dwarf2_cu *cu = reader->cu;
6731   struct abbrev_info *abbrev;
6732   unsigned int bytes_read;
6733
6734   while (1)
6735     {
6736       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6737       if (abbrev == NULL)
6738         return info_ptr + bytes_read;
6739       else
6740         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6741     }
6742 }
6743
6744 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6745    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6746    abbrev corresponding to that skipped uleb128 should be passed in
6747    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6748    children.  */
6749
6750 static const gdb_byte *
6751 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6752               struct abbrev_info *abbrev)
6753 {
6754   unsigned int bytes_read;
6755   struct attribute attr;
6756   bfd *abfd = reader->abfd;
6757   struct dwarf2_cu *cu = reader->cu;
6758   const gdb_byte *buffer = reader->buffer;
6759   const gdb_byte *buffer_end = reader->buffer_end;
6760   const gdb_byte *start_info_ptr = info_ptr;
6761   unsigned int form, i;
6762
6763   for (i = 0; i < abbrev->num_attrs; i++)
6764     {
6765       /* The only abbrev we care about is DW_AT_sibling.  */
6766       if (abbrev->attrs[i].name == DW_AT_sibling)
6767         {
6768           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6769           if (attr.form == DW_FORM_ref_addr)
6770             complaint (&symfile_complaints,
6771                        _("ignoring absolute DW_AT_sibling"));
6772           else
6773             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6774         }
6775
6776       /* If it isn't DW_AT_sibling, skip this attribute.  */
6777       form = abbrev->attrs[i].form;
6778     skip_attribute:
6779       switch (form)
6780         {
6781         case DW_FORM_ref_addr:
6782           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6783              and later it is offset sized.  */
6784           if (cu->header.version == 2)
6785             info_ptr += cu->header.addr_size;
6786           else
6787             info_ptr += cu->header.offset_size;
6788           break;
6789         case DW_FORM_GNU_ref_alt:
6790           info_ptr += cu->header.offset_size;
6791           break;
6792         case DW_FORM_addr:
6793           info_ptr += cu->header.addr_size;
6794           break;
6795         case DW_FORM_data1:
6796         case DW_FORM_ref1:
6797         case DW_FORM_flag:
6798           info_ptr += 1;
6799           break;
6800         case DW_FORM_flag_present:
6801           break;
6802         case DW_FORM_data2:
6803         case DW_FORM_ref2:
6804           info_ptr += 2;
6805           break;
6806         case DW_FORM_data4:
6807         case DW_FORM_ref4:
6808           info_ptr += 4;
6809           break;
6810         case DW_FORM_data8:
6811         case DW_FORM_ref8:
6812         case DW_FORM_ref_sig8:
6813           info_ptr += 8;
6814           break;
6815         case DW_FORM_string:
6816           read_direct_string (abfd, info_ptr, &bytes_read);
6817           info_ptr += bytes_read;
6818           break;
6819         case DW_FORM_sec_offset:
6820         case DW_FORM_strp:
6821         case DW_FORM_GNU_strp_alt:
6822           info_ptr += cu->header.offset_size;
6823           break;
6824         case DW_FORM_exprloc:
6825         case DW_FORM_block:
6826           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6827           info_ptr += bytes_read;
6828           break;
6829         case DW_FORM_block1:
6830           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6831           break;
6832         case DW_FORM_block2:
6833           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6834           break;
6835         case DW_FORM_block4:
6836           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6837           break;
6838         case DW_FORM_sdata:
6839         case DW_FORM_udata:
6840         case DW_FORM_ref_udata:
6841         case DW_FORM_GNU_addr_index:
6842         case DW_FORM_GNU_str_index:
6843           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6844           break;
6845         case DW_FORM_indirect:
6846           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6847           info_ptr += bytes_read;
6848           /* We need to continue parsing from here, so just go back to
6849              the top.  */
6850           goto skip_attribute;
6851
6852         default:
6853           error (_("Dwarf Error: Cannot handle %s "
6854                    "in DWARF reader [in module %s]"),
6855                  dwarf_form_name (form),
6856                  bfd_get_filename (abfd));
6857         }
6858     }
6859
6860   if (abbrev->has_children)
6861     return skip_children (reader, info_ptr);
6862   else
6863     return info_ptr;
6864 }
6865
6866 /* Locate ORIG_PDI's sibling.
6867    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6868
6869 static const gdb_byte *
6870 locate_pdi_sibling (const struct die_reader_specs *reader,
6871                     struct partial_die_info *orig_pdi,
6872                     const gdb_byte *info_ptr)
6873 {
6874   /* Do we know the sibling already?  */
6875
6876   if (orig_pdi->sibling)
6877     return orig_pdi->sibling;
6878
6879   /* Are there any children to deal with?  */
6880
6881   if (!orig_pdi->has_children)
6882     return info_ptr;
6883
6884   /* Skip the children the long way.  */
6885
6886   return skip_children (reader, info_ptr);
6887 }
6888
6889 /* Expand this partial symbol table into a full symbol table.  SELF is
6890    not NULL.  */
6891
6892 static void
6893 dwarf2_read_symtab (struct partial_symtab *self,
6894                     struct objfile *objfile)
6895 {
6896   if (self->readin)
6897     {
6898       warning (_("bug: psymtab for %s is already read in."),
6899                self->filename);
6900     }
6901   else
6902     {
6903       if (info_verbose)
6904         {
6905           printf_filtered (_("Reading in symbols for %s..."),
6906                            self->filename);
6907           gdb_flush (gdb_stdout);
6908         }
6909
6910       /* Restore our global data.  */
6911       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6912
6913       /* If this psymtab is constructed from a debug-only objfile, the
6914          has_section_at_zero flag will not necessarily be correct.  We
6915          can get the correct value for this flag by looking at the data
6916          associated with the (presumably stripped) associated objfile.  */
6917       if (objfile->separate_debug_objfile_backlink)
6918         {
6919           struct dwarf2_per_objfile *dpo_backlink
6920             = objfile_data (objfile->separate_debug_objfile_backlink,
6921                             dwarf2_objfile_data_key);
6922
6923           dwarf2_per_objfile->has_section_at_zero
6924             = dpo_backlink->has_section_at_zero;
6925         }
6926
6927       dwarf2_per_objfile->reading_partial_symbols = 0;
6928
6929       psymtab_to_symtab_1 (self);
6930
6931       /* Finish up the debug error message.  */
6932       if (info_verbose)
6933         printf_filtered (_("done.\n"));
6934     }
6935
6936   process_cu_includes ();
6937 }
6938 \f
6939 /* Reading in full CUs.  */
6940
6941 /* Add PER_CU to the queue.  */
6942
6943 static void
6944 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6945                  enum language pretend_language)
6946 {
6947   struct dwarf2_queue_item *item;
6948
6949   per_cu->queued = 1;
6950   item = xmalloc (sizeof (*item));
6951   item->per_cu = per_cu;
6952   item->pretend_language = pretend_language;
6953   item->next = NULL;
6954
6955   if (dwarf2_queue == NULL)
6956     dwarf2_queue = item;
6957   else
6958     dwarf2_queue_tail->next = item;
6959
6960   dwarf2_queue_tail = item;
6961 }
6962
6963 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6964    unit and add it to our queue.
6965    The result is non-zero if PER_CU was queued, otherwise the result is zero
6966    meaning either PER_CU is already queued or it is already loaded.  */
6967
6968 static int
6969 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6970                        struct dwarf2_per_cu_data *per_cu,
6971                        enum language pretend_language)
6972 {
6973   /* We may arrive here during partial symbol reading, if we need full
6974      DIEs to process an unusual case (e.g. template arguments).  Do
6975      not queue PER_CU, just tell our caller to load its DIEs.  */
6976   if (dwarf2_per_objfile->reading_partial_symbols)
6977     {
6978       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6979         return 1;
6980       return 0;
6981     }
6982
6983   /* Mark the dependence relation so that we don't flush PER_CU
6984      too early.  */
6985   dwarf2_add_dependence (this_cu, per_cu);
6986
6987   /* If it's already on the queue, we have nothing to do.  */
6988   if (per_cu->queued)
6989     return 0;
6990
6991   /* If the compilation unit is already loaded, just mark it as
6992      used.  */
6993   if (per_cu->cu != NULL)
6994     {
6995       per_cu->cu->last_used = 0;
6996       return 0;
6997     }
6998
6999   /* Add it to the queue.  */
7000   queue_comp_unit (per_cu, pretend_language);
7001
7002   return 1;
7003 }
7004
7005 /* Process the queue.  */
7006
7007 static void
7008 process_queue (void)
7009 {
7010   struct dwarf2_queue_item *item, *next_item;
7011
7012   if (dwarf2_read_debug)
7013     {
7014       fprintf_unfiltered (gdb_stdlog,
7015                           "Expanding one or more symtabs of objfile %s ...\n",
7016                           dwarf2_per_objfile->objfile->name);
7017     }
7018
7019   /* The queue starts out with one item, but following a DIE reference
7020      may load a new CU, adding it to the end of the queue.  */
7021   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7022     {
7023       if (dwarf2_per_objfile->using_index
7024           ? !item->per_cu->v.quick->symtab
7025           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7026         {
7027           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7028
7029           if (dwarf2_read_debug)
7030             {
7031               fprintf_unfiltered (gdb_stdlog,
7032                                   "Expanding symtab of %s at offset 0x%x\n",
7033                                   per_cu->is_debug_types ? "TU" : "CU",
7034                                   per_cu->offset.sect_off);
7035             }
7036
7037           if (per_cu->is_debug_types)
7038             process_full_type_unit (per_cu, item->pretend_language);
7039           else
7040             process_full_comp_unit (per_cu, item->pretend_language);
7041
7042           if (dwarf2_read_debug)
7043             {
7044               fprintf_unfiltered (gdb_stdlog,
7045                                   "Done expanding %s at offset 0x%x\n",
7046                                   per_cu->is_debug_types ? "TU" : "CU",
7047                                   per_cu->offset.sect_off);
7048             }
7049         }
7050
7051       item->per_cu->queued = 0;
7052       next_item = item->next;
7053       xfree (item);
7054     }
7055
7056   dwarf2_queue_tail = NULL;
7057
7058   if (dwarf2_read_debug)
7059     {
7060       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7061                           dwarf2_per_objfile->objfile->name);
7062     }
7063 }
7064
7065 /* Free all allocated queue entries.  This function only releases anything if
7066    an error was thrown; if the queue was processed then it would have been
7067    freed as we went along.  */
7068
7069 static void
7070 dwarf2_release_queue (void *dummy)
7071 {
7072   struct dwarf2_queue_item *item, *last;
7073
7074   item = dwarf2_queue;
7075   while (item)
7076     {
7077       /* Anything still marked queued is likely to be in an
7078          inconsistent state, so discard it.  */
7079       if (item->per_cu->queued)
7080         {
7081           if (item->per_cu->cu != NULL)
7082             free_one_cached_comp_unit (item->per_cu);
7083           item->per_cu->queued = 0;
7084         }
7085
7086       last = item;
7087       item = item->next;
7088       xfree (last);
7089     }
7090
7091   dwarf2_queue = dwarf2_queue_tail = NULL;
7092 }
7093
7094 /* Read in full symbols for PST, and anything it depends on.  */
7095
7096 static void
7097 psymtab_to_symtab_1 (struct partial_symtab *pst)
7098 {
7099   struct dwarf2_per_cu_data *per_cu;
7100   int i;
7101
7102   if (pst->readin)
7103     return;
7104
7105   for (i = 0; i < pst->number_of_dependencies; i++)
7106     if (!pst->dependencies[i]->readin
7107         && pst->dependencies[i]->user == NULL)
7108       {
7109         /* Inform about additional files that need to be read in.  */
7110         if (info_verbose)
7111           {
7112             /* FIXME: i18n: Need to make this a single string.  */
7113             fputs_filtered (" ", gdb_stdout);
7114             wrap_here ("");
7115             fputs_filtered ("and ", gdb_stdout);
7116             wrap_here ("");
7117             printf_filtered ("%s...", pst->dependencies[i]->filename);
7118             wrap_here ("");     /* Flush output.  */
7119             gdb_flush (gdb_stdout);
7120           }
7121         psymtab_to_symtab_1 (pst->dependencies[i]);
7122       }
7123
7124   per_cu = pst->read_symtab_private;
7125
7126   if (per_cu == NULL)
7127     {
7128       /* It's an include file, no symbols to read for it.
7129          Everything is in the parent symtab.  */
7130       pst->readin = 1;
7131       return;
7132     }
7133
7134   dw2_do_instantiate_symtab (per_cu);
7135 }
7136
7137 /* Trivial hash function for die_info: the hash value of a DIE
7138    is its offset in .debug_info for this objfile.  */
7139
7140 static hashval_t
7141 die_hash (const void *item)
7142 {
7143   const struct die_info *die = item;
7144
7145   return die->offset.sect_off;
7146 }
7147
7148 /* Trivial comparison function for die_info structures: two DIEs
7149    are equal if they have the same offset.  */
7150
7151 static int
7152 die_eq (const void *item_lhs, const void *item_rhs)
7153 {
7154   const struct die_info *die_lhs = item_lhs;
7155   const struct die_info *die_rhs = item_rhs;
7156
7157   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7158 }
7159
7160 /* die_reader_func for load_full_comp_unit.
7161    This is identical to read_signatured_type_reader,
7162    but is kept separate for now.  */
7163
7164 static void
7165 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7166                             const gdb_byte *info_ptr,
7167                             struct die_info *comp_unit_die,
7168                             int has_children,
7169                             void *data)
7170 {
7171   struct dwarf2_cu *cu = reader->cu;
7172   enum language *language_ptr = data;
7173
7174   gdb_assert (cu->die_hash == NULL);
7175   cu->die_hash =
7176     htab_create_alloc_ex (cu->header.length / 12,
7177                           die_hash,
7178                           die_eq,
7179                           NULL,
7180                           &cu->comp_unit_obstack,
7181                           hashtab_obstack_allocate,
7182                           dummy_obstack_deallocate);
7183
7184   if (has_children)
7185     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7186                                                   &info_ptr, comp_unit_die);
7187   cu->dies = comp_unit_die;
7188   /* comp_unit_die is not stored in die_hash, no need.  */
7189
7190   /* We try not to read any attributes in this function, because not
7191      all CUs needed for references have been loaded yet, and symbol
7192      table processing isn't initialized.  But we have to set the CU language,
7193      or we won't be able to build types correctly.
7194      Similarly, if we do not read the producer, we can not apply
7195      producer-specific interpretation.  */
7196   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7197 }
7198
7199 /* Load the DIEs associated with PER_CU into memory.  */
7200
7201 static void
7202 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7203                      enum language pretend_language)
7204 {
7205   gdb_assert (! this_cu->is_debug_types);
7206
7207   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7208                            load_full_comp_unit_reader, &pretend_language);
7209 }
7210
7211 /* Add a DIE to the delayed physname list.  */
7212
7213 static void
7214 add_to_method_list (struct type *type, int fnfield_index, int index,
7215                     const char *name, struct die_info *die,
7216                     struct dwarf2_cu *cu)
7217 {
7218   struct delayed_method_info mi;
7219   mi.type = type;
7220   mi.fnfield_index = fnfield_index;
7221   mi.index = index;
7222   mi.name = name;
7223   mi.die = die;
7224   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7225 }
7226
7227 /* A cleanup for freeing the delayed method list.  */
7228
7229 static void
7230 free_delayed_list (void *ptr)
7231 {
7232   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7233   if (cu->method_list != NULL)
7234     {
7235       VEC_free (delayed_method_info, cu->method_list);
7236       cu->method_list = NULL;
7237     }
7238 }
7239
7240 /* Compute the physnames of any methods on the CU's method list.
7241
7242    The computation of method physnames is delayed in order to avoid the
7243    (bad) condition that one of the method's formal parameters is of an as yet
7244    incomplete type.  */
7245
7246 static void
7247 compute_delayed_physnames (struct dwarf2_cu *cu)
7248 {
7249   int i;
7250   struct delayed_method_info *mi;
7251   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7252     {
7253       const char *physname;
7254       struct fn_fieldlist *fn_flp
7255         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7256       physname = dwarf2_physname (mi->name, mi->die, cu);
7257       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7258     }
7259 }
7260
7261 /* Go objects should be embedded in a DW_TAG_module DIE,
7262    and it's not clear if/how imported objects will appear.
7263    To keep Go support simple until that's worked out,
7264    go back through what we've read and create something usable.
7265    We could do this while processing each DIE, and feels kinda cleaner,
7266    but that way is more invasive.
7267    This is to, for example, allow the user to type "p var" or "b main"
7268    without having to specify the package name, and allow lookups
7269    of module.object to work in contexts that use the expression
7270    parser.  */
7271
7272 static void
7273 fixup_go_packaging (struct dwarf2_cu *cu)
7274 {
7275   char *package_name = NULL;
7276   struct pending *list;
7277   int i;
7278
7279   for (list = global_symbols; list != NULL; list = list->next)
7280     {
7281       for (i = 0; i < list->nsyms; ++i)
7282         {
7283           struct symbol *sym = list->symbol[i];
7284
7285           if (SYMBOL_LANGUAGE (sym) == language_go
7286               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7287             {
7288               char *this_package_name = go_symbol_package_name (sym);
7289
7290               if (this_package_name == NULL)
7291                 continue;
7292               if (package_name == NULL)
7293                 package_name = this_package_name;
7294               else
7295                 {
7296                   if (strcmp (package_name, this_package_name) != 0)
7297                     complaint (&symfile_complaints,
7298                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7299                                (SYMBOL_SYMTAB (sym)
7300                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7301                                 : cu->objfile->name),
7302                                this_package_name, package_name);
7303                   xfree (this_package_name);
7304                 }
7305             }
7306         }
7307     }
7308
7309   if (package_name != NULL)
7310     {
7311       struct objfile *objfile = cu->objfile;
7312       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7313                                                       package_name,
7314                                                       strlen (package_name));
7315       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7316                                      saved_package_name, objfile);
7317       struct symbol *sym;
7318
7319       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7320
7321       sym = allocate_symbol (objfile);
7322       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7323       SYMBOL_SET_NAMES (sym, saved_package_name,
7324                         strlen (saved_package_name), 0, objfile);
7325       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7326          e.g., "main" finds the "main" module and not C's main().  */
7327       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7328       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7329       SYMBOL_TYPE (sym) = type;
7330
7331       add_symbol_to_list (sym, &global_symbols);
7332
7333       xfree (package_name);
7334     }
7335 }
7336
7337 /* Return the symtab for PER_CU.  This works properly regardless of
7338    whether we're using the index or psymtabs.  */
7339
7340 static struct symtab *
7341 get_symtab (struct dwarf2_per_cu_data *per_cu)
7342 {
7343   return (dwarf2_per_objfile->using_index
7344           ? per_cu->v.quick->symtab
7345           : per_cu->v.psymtab->symtab);
7346 }
7347
7348 /* A helper function for computing the list of all symbol tables
7349    included by PER_CU.  */
7350
7351 static void
7352 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
7353                                 htab_t all_children,
7354                                 struct dwarf2_per_cu_data *per_cu)
7355 {
7356   void **slot;
7357   int ix;
7358   struct dwarf2_per_cu_data *iter;
7359
7360   slot = htab_find_slot (all_children, per_cu, INSERT);
7361   if (*slot != NULL)
7362     {
7363       /* This inclusion and its children have been processed.  */
7364       return;
7365     }
7366
7367   *slot = per_cu;
7368   /* Only add a CU if it has a symbol table.  */
7369   if (get_symtab (per_cu) != NULL)
7370     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
7371
7372   for (ix = 0;
7373        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7374        ++ix)
7375     recursively_compute_inclusions (result, all_children, iter);
7376 }
7377
7378 /* Compute the symtab 'includes' fields for the symtab related to
7379    PER_CU.  */
7380
7381 static void
7382 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7383 {
7384   gdb_assert (! per_cu->is_debug_types);
7385
7386   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7387     {
7388       int ix, len;
7389       struct dwarf2_per_cu_data *iter;
7390       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
7391       htab_t all_children;
7392       struct symtab *symtab = get_symtab (per_cu);
7393
7394       /* If we don't have a symtab, we can just skip this case.  */
7395       if (symtab == NULL)
7396         return;
7397
7398       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7399                                         NULL, xcalloc, xfree);
7400
7401       for (ix = 0;
7402            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7403                         ix, iter);
7404            ++ix)
7405         recursively_compute_inclusions (&result_children, all_children, iter);
7406
7407       /* Now we have a transitive closure of all the included CUs, and
7408          for .gdb_index version 7 the included TUs, so we can convert it
7409          to a list of symtabs.  */
7410       len = VEC_length (dwarf2_per_cu_ptr, result_children);
7411       symtab->includes
7412         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7413                          (len + 1) * sizeof (struct symtab *));
7414       for (ix = 0;
7415            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
7416            ++ix)
7417         symtab->includes[ix] = get_symtab (iter);
7418       symtab->includes[len] = NULL;
7419
7420       VEC_free (dwarf2_per_cu_ptr, result_children);
7421       htab_delete (all_children);
7422     }
7423 }
7424
7425 /* Compute the 'includes' field for the symtabs of all the CUs we just
7426    read.  */
7427
7428 static void
7429 process_cu_includes (void)
7430 {
7431   int ix;
7432   struct dwarf2_per_cu_data *iter;
7433
7434   for (ix = 0;
7435        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7436                     ix, iter);
7437        ++ix)
7438     {
7439       if (! iter->is_debug_types)
7440         compute_symtab_includes (iter);
7441     }
7442
7443   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7444 }
7445
7446 /* Generate full symbol information for PER_CU, whose DIEs have
7447    already been loaded into memory.  */
7448
7449 static void
7450 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7451                         enum language pretend_language)
7452 {
7453   struct dwarf2_cu *cu = per_cu->cu;
7454   struct objfile *objfile = per_cu->objfile;
7455   CORE_ADDR lowpc, highpc;
7456   struct symtab *symtab;
7457   struct cleanup *back_to, *delayed_list_cleanup;
7458   CORE_ADDR baseaddr;
7459   struct block *static_block;
7460
7461   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7462
7463   buildsym_init ();
7464   back_to = make_cleanup (really_free_pendings, NULL);
7465   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7466
7467   cu->list_in_scope = &file_symbols;
7468
7469   cu->language = pretend_language;
7470   cu->language_defn = language_def (cu->language);
7471
7472   /* Do line number decoding in read_file_scope () */
7473   process_die (cu->dies, cu);
7474
7475   /* For now fudge the Go package.  */
7476   if (cu->language == language_go)
7477     fixup_go_packaging (cu);
7478
7479   /* Now that we have processed all the DIEs in the CU, all the types 
7480      should be complete, and it should now be safe to compute all of the
7481      physnames.  */
7482   compute_delayed_physnames (cu);
7483   do_cleanups (delayed_list_cleanup);
7484
7485   /* Some compilers don't define a DW_AT_high_pc attribute for the
7486      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7487      it, by scanning the DIE's below the compilation unit.  */
7488   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7489
7490   static_block
7491     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7492
7493   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7494      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7495      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7496      addrmap to help ensure it has an accurate map of pc values belonging to
7497      this comp unit.  */
7498   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7499
7500   symtab = end_symtab_from_static_block (static_block, objfile,
7501                                          SECT_OFF_TEXT (objfile), 0);
7502
7503   if (symtab != NULL)
7504     {
7505       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7506
7507       /* Set symtab language to language from DW_AT_language.  If the
7508          compilation is from a C file generated by language preprocessors, do
7509          not set the language if it was already deduced by start_subfile.  */
7510       if (!(cu->language == language_c && symtab->language != language_c))
7511         symtab->language = cu->language;
7512
7513       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7514          produce DW_AT_location with location lists but it can be possibly
7515          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7516          there were bugs in prologue debug info, fixed later in GCC-4.5
7517          by "unwind info for epilogues" patch (which is not directly related).
7518
7519          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7520          needed, it would be wrong due to missing DW_AT_producer there.
7521
7522          Still one can confuse GDB by using non-standard GCC compilation
7523          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7524          */ 
7525       if (cu->has_loclist && gcc_4_minor >= 5)
7526         symtab->locations_valid = 1;
7527
7528       if (gcc_4_minor >= 5)
7529         symtab->epilogue_unwind_valid = 1;
7530
7531       symtab->call_site_htab = cu->call_site_htab;
7532     }
7533
7534   if (dwarf2_per_objfile->using_index)
7535     per_cu->v.quick->symtab = symtab;
7536   else
7537     {
7538       struct partial_symtab *pst = per_cu->v.psymtab;
7539       pst->symtab = symtab;
7540       pst->readin = 1;
7541     }
7542
7543   /* Push it for inclusion processing later.  */
7544   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7545
7546   do_cleanups (back_to);
7547 }
7548
7549 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7550    already been loaded into memory.  */
7551
7552 static void
7553 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7554                         enum language pretend_language)
7555 {
7556   struct dwarf2_cu *cu = per_cu->cu;
7557   struct objfile *objfile = per_cu->objfile;
7558   struct symtab *symtab;
7559   struct cleanup *back_to, *delayed_list_cleanup;
7560   struct signatured_type *sig_type;
7561
7562   gdb_assert (per_cu->is_debug_types);
7563   sig_type = (struct signatured_type *) per_cu;
7564
7565   buildsym_init ();
7566   back_to = make_cleanup (really_free_pendings, NULL);
7567   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7568
7569   cu->list_in_scope = &file_symbols;
7570
7571   cu->language = pretend_language;
7572   cu->language_defn = language_def (cu->language);
7573
7574   /* The symbol tables are set up in read_type_unit_scope.  */
7575   process_die (cu->dies, cu);
7576
7577   /* For now fudge the Go package.  */
7578   if (cu->language == language_go)
7579     fixup_go_packaging (cu);
7580
7581   /* Now that we have processed all the DIEs in the CU, all the types 
7582      should be complete, and it should now be safe to compute all of the
7583      physnames.  */
7584   compute_delayed_physnames (cu);
7585   do_cleanups (delayed_list_cleanup);
7586
7587   /* TUs share symbol tables.
7588      If this is the first TU to use this symtab, complete the construction
7589      of it with end_expandable_symtab.  Otherwise, complete the addition of
7590      this TU's symbols to the existing symtab.  */
7591   if (sig_type->type_unit_group->primary_symtab == NULL)
7592     {
7593       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7594       sig_type->type_unit_group->primary_symtab = symtab;
7595
7596       if (symtab != NULL)
7597         {
7598           /* Set symtab language to language from DW_AT_language.  If the
7599              compilation is from a C file generated by language preprocessors,
7600              do not set the language if it was already deduced by
7601              start_subfile.  */
7602           if (!(cu->language == language_c && symtab->language != language_c))
7603             symtab->language = cu->language;
7604         }
7605     }
7606   else
7607     {
7608       augment_type_symtab (objfile,
7609                            sig_type->type_unit_group->primary_symtab);
7610       symtab = sig_type->type_unit_group->primary_symtab;
7611     }
7612
7613   if (dwarf2_per_objfile->using_index)
7614     per_cu->v.quick->symtab = symtab;
7615   else
7616     {
7617       struct partial_symtab *pst = per_cu->v.psymtab;
7618       pst->symtab = symtab;
7619       pst->readin = 1;
7620     }
7621
7622   do_cleanups (back_to);
7623 }
7624
7625 /* Process an imported unit DIE.  */
7626
7627 static void
7628 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7629 {
7630   struct attribute *attr;
7631
7632   /* For now we don't handle imported units in type units.  */
7633   if (cu->per_cu->is_debug_types)
7634     {
7635       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7636                " supported in type units [in module %s]"),
7637              cu->objfile->name);
7638     }
7639
7640   attr = dwarf2_attr (die, DW_AT_import, cu);
7641   if (attr != NULL)
7642     {
7643       struct dwarf2_per_cu_data *per_cu;
7644       struct symtab *imported_symtab;
7645       sect_offset offset;
7646       int is_dwz;
7647
7648       offset = dwarf2_get_ref_die_offset (attr);
7649       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7650       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7651
7652       /* Queue the unit, if needed.  */
7653       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7654         load_full_comp_unit (per_cu, cu->language);
7655
7656       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7657                      per_cu);
7658     }
7659 }
7660
7661 /* Process a die and its children.  */
7662
7663 static void
7664 process_die (struct die_info *die, struct dwarf2_cu *cu)
7665 {
7666   switch (die->tag)
7667     {
7668     case DW_TAG_padding:
7669       break;
7670     case DW_TAG_compile_unit:
7671     case DW_TAG_partial_unit:
7672       read_file_scope (die, cu);
7673       break;
7674     case DW_TAG_type_unit:
7675       read_type_unit_scope (die, cu);
7676       break;
7677     case DW_TAG_subprogram:
7678     case DW_TAG_inlined_subroutine:
7679       read_func_scope (die, cu);
7680       break;
7681     case DW_TAG_lexical_block:
7682     case DW_TAG_try_block:
7683     case DW_TAG_catch_block:
7684       read_lexical_block_scope (die, cu);
7685       break;
7686     case DW_TAG_GNU_call_site:
7687       read_call_site_scope (die, cu);
7688       break;
7689     case DW_TAG_class_type:
7690     case DW_TAG_interface_type:
7691     case DW_TAG_structure_type:
7692     case DW_TAG_union_type:
7693       process_structure_scope (die, cu);
7694       break;
7695     case DW_TAG_enumeration_type:
7696       process_enumeration_scope (die, cu);
7697       break;
7698
7699     /* These dies have a type, but processing them does not create
7700        a symbol or recurse to process the children.  Therefore we can
7701        read them on-demand through read_type_die.  */
7702     case DW_TAG_subroutine_type:
7703     case DW_TAG_set_type:
7704     case DW_TAG_array_type:
7705     case DW_TAG_pointer_type:
7706     case DW_TAG_ptr_to_member_type:
7707     case DW_TAG_reference_type:
7708     case DW_TAG_string_type:
7709       break;
7710
7711     case DW_TAG_base_type:
7712     case DW_TAG_subrange_type:
7713     case DW_TAG_typedef:
7714       /* Add a typedef symbol for the type definition, if it has a
7715          DW_AT_name.  */
7716       new_symbol (die, read_type_die (die, cu), cu);
7717       break;
7718     case DW_TAG_common_block:
7719       read_common_block (die, cu);
7720       break;
7721     case DW_TAG_common_inclusion:
7722       break;
7723     case DW_TAG_namespace:
7724       cu->processing_has_namespace_info = 1;
7725       read_namespace (die, cu);
7726       break;
7727     case DW_TAG_module:
7728       cu->processing_has_namespace_info = 1;
7729       read_module (die, cu);
7730       break;
7731     case DW_TAG_imported_declaration:
7732     case DW_TAG_imported_module:
7733       cu->processing_has_namespace_info = 1;
7734       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7735                                  || cu->language != language_fortran))
7736         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7737                    dwarf_tag_name (die->tag));
7738       read_import_statement (die, cu);
7739       break;
7740
7741     case DW_TAG_imported_unit:
7742       process_imported_unit_die (die, cu);
7743       break;
7744
7745     default:
7746       new_symbol (die, NULL, cu);
7747       break;
7748     }
7749 }
7750 \f
7751 /* DWARF name computation.  */
7752
7753 /* A helper function for dwarf2_compute_name which determines whether DIE
7754    needs to have the name of the scope prepended to the name listed in the
7755    die.  */
7756
7757 static int
7758 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7759 {
7760   struct attribute *attr;
7761
7762   switch (die->tag)
7763     {
7764     case DW_TAG_namespace:
7765     case DW_TAG_typedef:
7766     case DW_TAG_class_type:
7767     case DW_TAG_interface_type:
7768     case DW_TAG_structure_type:
7769     case DW_TAG_union_type:
7770     case DW_TAG_enumeration_type:
7771     case DW_TAG_enumerator:
7772     case DW_TAG_subprogram:
7773     case DW_TAG_member:
7774       return 1;
7775
7776     case DW_TAG_variable:
7777     case DW_TAG_constant:
7778       /* We only need to prefix "globally" visible variables.  These include
7779          any variable marked with DW_AT_external or any variable that
7780          lives in a namespace.  [Variables in anonymous namespaces
7781          require prefixing, but they are not DW_AT_external.]  */
7782
7783       if (dwarf2_attr (die, DW_AT_specification, cu))
7784         {
7785           struct dwarf2_cu *spec_cu = cu;
7786
7787           return die_needs_namespace (die_specification (die, &spec_cu),
7788                                       spec_cu);
7789         }
7790
7791       attr = dwarf2_attr (die, DW_AT_external, cu);
7792       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7793           && die->parent->tag != DW_TAG_module)
7794         return 0;
7795       /* A variable in a lexical block of some kind does not need a
7796          namespace, even though in C++ such variables may be external
7797          and have a mangled name.  */
7798       if (die->parent->tag ==  DW_TAG_lexical_block
7799           || die->parent->tag ==  DW_TAG_try_block
7800           || die->parent->tag ==  DW_TAG_catch_block
7801           || die->parent->tag == DW_TAG_subprogram)
7802         return 0;
7803       return 1;
7804
7805     default:
7806       return 0;
7807     }
7808 }
7809
7810 /* Retrieve the last character from a mem_file.  */
7811
7812 static void
7813 do_ui_file_peek_last (void *object, const char *buffer, long length)
7814 {
7815   char *last_char_p = (char *) object;
7816
7817   if (length > 0)
7818     *last_char_p = buffer[length - 1];
7819 }
7820
7821 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7822    compute the physname for the object, which include a method's:
7823    - formal parameters (C++/Java),
7824    - receiver type (Go),
7825    - return type (Java).
7826
7827    The term "physname" is a bit confusing.
7828    For C++, for example, it is the demangled name.
7829    For Go, for example, it's the mangled name.
7830
7831    For Ada, return the DIE's linkage name rather than the fully qualified
7832    name.  PHYSNAME is ignored..
7833
7834    The result is allocated on the objfile_obstack and canonicalized.  */
7835
7836 static const char *
7837 dwarf2_compute_name (const char *name,
7838                      struct die_info *die, struct dwarf2_cu *cu,
7839                      int physname)
7840 {
7841   struct objfile *objfile = cu->objfile;
7842
7843   if (name == NULL)
7844     name = dwarf2_name (die, cu);
7845
7846   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7847      compute it by typename_concat inside GDB.  */
7848   if (cu->language == language_ada
7849       || (cu->language == language_fortran && physname))
7850     {
7851       /* For Ada unit, we prefer the linkage name over the name, as
7852          the former contains the exported name, which the user expects
7853          to be able to reference.  Ideally, we want the user to be able
7854          to reference this entity using either natural or linkage name,
7855          but we haven't started looking at this enhancement yet.  */
7856       struct attribute *attr;
7857
7858       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7859       if (attr == NULL)
7860         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7861       if (attr && DW_STRING (attr))
7862         return DW_STRING (attr);
7863     }
7864
7865   /* These are the only languages we know how to qualify names in.  */
7866   if (name != NULL
7867       && (cu->language == language_cplus || cu->language == language_java
7868           || cu->language == language_fortran))
7869     {
7870       if (die_needs_namespace (die, cu))
7871         {
7872           long length;
7873           const char *prefix;
7874           struct ui_file *buf;
7875
7876           prefix = determine_prefix (die, cu);
7877           buf = mem_fileopen ();
7878           if (*prefix != '\0')
7879             {
7880               char *prefixed_name = typename_concat (NULL, prefix, name,
7881                                                      physname, cu);
7882
7883               fputs_unfiltered (prefixed_name, buf);
7884               xfree (prefixed_name);
7885             }
7886           else
7887             fputs_unfiltered (name, buf);
7888
7889           /* Template parameters may be specified in the DIE's DW_AT_name, or
7890              as children with DW_TAG_template_type_param or
7891              DW_TAG_value_type_param.  If the latter, add them to the name
7892              here.  If the name already has template parameters, then
7893              skip this step; some versions of GCC emit both, and
7894              it is more efficient to use the pre-computed name.
7895
7896              Something to keep in mind about this process: it is very
7897              unlikely, or in some cases downright impossible, to produce
7898              something that will match the mangled name of a function.
7899              If the definition of the function has the same debug info,
7900              we should be able to match up with it anyway.  But fallbacks
7901              using the minimal symbol, for instance to find a method
7902              implemented in a stripped copy of libstdc++, will not work.
7903              If we do not have debug info for the definition, we will have to
7904              match them up some other way.
7905
7906              When we do name matching there is a related problem with function
7907              templates; two instantiated function templates are allowed to
7908              differ only by their return types, which we do not add here.  */
7909
7910           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7911             {
7912               struct attribute *attr;
7913               struct die_info *child;
7914               int first = 1;
7915
7916               die->building_fullname = 1;
7917
7918               for (child = die->child; child != NULL; child = child->sibling)
7919                 {
7920                   struct type *type;
7921                   LONGEST value;
7922                   const gdb_byte *bytes;
7923                   struct dwarf2_locexpr_baton *baton;
7924                   struct value *v;
7925
7926                   if (child->tag != DW_TAG_template_type_param
7927                       && child->tag != DW_TAG_template_value_param)
7928                     continue;
7929
7930                   if (first)
7931                     {
7932                       fputs_unfiltered ("<", buf);
7933                       first = 0;
7934                     }
7935                   else
7936                     fputs_unfiltered (", ", buf);
7937
7938                   attr = dwarf2_attr (child, DW_AT_type, cu);
7939                   if (attr == NULL)
7940                     {
7941                       complaint (&symfile_complaints,
7942                                  _("template parameter missing DW_AT_type"));
7943                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7944                       continue;
7945                     }
7946                   type = die_type (child, cu);
7947
7948                   if (child->tag == DW_TAG_template_type_param)
7949                     {
7950                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7951                       continue;
7952                     }
7953
7954                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7955                   if (attr == NULL)
7956                     {
7957                       complaint (&symfile_complaints,
7958                                  _("template parameter missing "
7959                                    "DW_AT_const_value"));
7960                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7961                       continue;
7962                     }
7963
7964                   dwarf2_const_value_attr (attr, type, name,
7965                                            &cu->comp_unit_obstack, cu,
7966                                            &value, &bytes, &baton);
7967
7968                   if (TYPE_NOSIGN (type))
7969                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7970                        changed, this can use value_print instead.  */
7971                     c_printchar (value, type, buf);
7972                   else
7973                     {
7974                       struct value_print_options opts;
7975
7976                       if (baton != NULL)
7977                         v = dwarf2_evaluate_loc_desc (type, NULL,
7978                                                       baton->data,
7979                                                       baton->size,
7980                                                       baton->per_cu);
7981                       else if (bytes != NULL)
7982                         {
7983                           v = allocate_value (type);
7984                           memcpy (value_contents_writeable (v), bytes,
7985                                   TYPE_LENGTH (type));
7986                         }
7987                       else
7988                         v = value_from_longest (type, value);
7989
7990                       /* Specify decimal so that we do not depend on
7991                          the radix.  */
7992                       get_formatted_print_options (&opts, 'd');
7993                       opts.raw = 1;
7994                       value_print (v, buf, &opts);
7995                       release_value (v);
7996                       value_free (v);
7997                     }
7998                 }
7999
8000               die->building_fullname = 0;
8001
8002               if (!first)
8003                 {
8004                   /* Close the argument list, with a space if necessary
8005                      (nested templates).  */
8006                   char last_char = '\0';
8007                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8008                   if (last_char == '>')
8009                     fputs_unfiltered (" >", buf);
8010                   else
8011                     fputs_unfiltered (">", buf);
8012                 }
8013             }
8014
8015           /* For Java and C++ methods, append formal parameter type
8016              information, if PHYSNAME.  */
8017
8018           if (physname && die->tag == DW_TAG_subprogram
8019               && (cu->language == language_cplus
8020                   || cu->language == language_java))
8021             {
8022               struct type *type = read_type_die (die, cu);
8023
8024               c_type_print_args (type, buf, 1, cu->language,
8025                                  &type_print_raw_options);
8026
8027               if (cu->language == language_java)
8028                 {
8029                   /* For java, we must append the return type to method
8030                      names.  */
8031                   if (die->tag == DW_TAG_subprogram)
8032                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8033                                      0, 0, &type_print_raw_options);
8034                 }
8035               else if (cu->language == language_cplus)
8036                 {
8037                   /* Assume that an artificial first parameter is
8038                      "this", but do not crash if it is not.  RealView
8039                      marks unnamed (and thus unused) parameters as
8040                      artificial; there is no way to differentiate
8041                      the two cases.  */
8042                   if (TYPE_NFIELDS (type) > 0
8043                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8044                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8045                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8046                                                                         0))))
8047                     fputs_unfiltered (" const", buf);
8048                 }
8049             }
8050
8051           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8052                                        &length);
8053           ui_file_delete (buf);
8054
8055           if (cu->language == language_cplus)
8056             {
8057               const char *cname
8058                 = dwarf2_canonicalize_name (name, cu,
8059                                             &objfile->objfile_obstack);
8060
8061               if (cname != NULL)
8062                 name = cname;
8063             }
8064         }
8065     }
8066
8067   return name;
8068 }
8069
8070 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8071    If scope qualifiers are appropriate they will be added.  The result
8072    will be allocated on the objfile_obstack, or NULL if the DIE does
8073    not have a name.  NAME may either be from a previous call to
8074    dwarf2_name or NULL.
8075
8076    The output string will be canonicalized (if C++/Java).  */
8077
8078 static const char *
8079 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8080 {
8081   return dwarf2_compute_name (name, die, cu, 0);
8082 }
8083
8084 /* Construct a physname for the given DIE in CU.  NAME may either be
8085    from a previous call to dwarf2_name or NULL.  The result will be
8086    allocated on the objfile_objstack or NULL if the DIE does not have a
8087    name.
8088
8089    The output string will be canonicalized (if C++/Java).  */
8090
8091 static const char *
8092 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8093 {
8094   struct objfile *objfile = cu->objfile;
8095   struct attribute *attr;
8096   const char *retval, *mangled = NULL, *canon = NULL;
8097   struct cleanup *back_to;
8098   int need_copy = 1;
8099
8100   /* In this case dwarf2_compute_name is just a shortcut not building anything
8101      on its own.  */
8102   if (!die_needs_namespace (die, cu))
8103     return dwarf2_compute_name (name, die, cu, 1);
8104
8105   back_to = make_cleanup (null_cleanup, NULL);
8106
8107   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8108   if (!attr)
8109     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8110
8111   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8112      has computed.  */
8113   if (attr && DW_STRING (attr))
8114     {
8115       char *demangled;
8116
8117       mangled = DW_STRING (attr);
8118
8119       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8120          type.  It is easier for GDB users to search for such functions as
8121          `name(params)' than `long name(params)'.  In such case the minimal
8122          symbol names do not match the full symbol names but for template
8123          functions there is never a need to look up their definition from their
8124          declaration so the only disadvantage remains the minimal symbol
8125          variant `long name(params)' does not have the proper inferior type.
8126          */
8127
8128       if (cu->language == language_go)
8129         {
8130           /* This is a lie, but we already lie to the caller new_symbol_full.
8131              new_symbol_full assumes we return the mangled name.
8132              This just undoes that lie until things are cleaned up.  */
8133           demangled = NULL;
8134         }
8135       else
8136         {
8137           demangled = gdb_demangle (mangled,
8138                                     (DMGL_PARAMS | DMGL_ANSI
8139                                      | (cu->language == language_java
8140                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8141                                         : DMGL_RET_DROP)));
8142         }
8143       if (demangled)
8144         {
8145           make_cleanup (xfree, demangled);
8146           canon = demangled;
8147         }
8148       else
8149         {
8150           canon = mangled;
8151           need_copy = 0;
8152         }
8153     }
8154
8155   if (canon == NULL || check_physname)
8156     {
8157       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8158
8159       if (canon != NULL && strcmp (physname, canon) != 0)
8160         {
8161           /* It may not mean a bug in GDB.  The compiler could also
8162              compute DW_AT_linkage_name incorrectly.  But in such case
8163              GDB would need to be bug-to-bug compatible.  */
8164
8165           complaint (&symfile_complaints,
8166                      _("Computed physname <%s> does not match demangled <%s> "
8167                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8168                      physname, canon, mangled, die->offset.sect_off, objfile->name);
8169
8170           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8171              is available here - over computed PHYSNAME.  It is safer
8172              against both buggy GDB and buggy compilers.  */
8173
8174           retval = canon;
8175         }
8176       else
8177         {
8178           retval = physname;
8179           need_copy = 0;
8180         }
8181     }
8182   else
8183     retval = canon;
8184
8185   if (need_copy)
8186     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8187
8188   do_cleanups (back_to);
8189   return retval;
8190 }
8191
8192 /* Read the import statement specified by the given die and record it.  */
8193
8194 static void
8195 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8196 {
8197   struct objfile *objfile = cu->objfile;
8198   struct attribute *import_attr;
8199   struct die_info *imported_die, *child_die;
8200   struct dwarf2_cu *imported_cu;
8201   const char *imported_name;
8202   const char *imported_name_prefix;
8203   const char *canonical_name;
8204   const char *import_alias;
8205   const char *imported_declaration = NULL;
8206   const char *import_prefix;
8207   VEC (const_char_ptr) *excludes = NULL;
8208   struct cleanup *cleanups;
8209
8210   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8211   if (import_attr == NULL)
8212     {
8213       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8214                  dwarf_tag_name (die->tag));
8215       return;
8216     }
8217
8218   imported_cu = cu;
8219   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8220   imported_name = dwarf2_name (imported_die, imported_cu);
8221   if (imported_name == NULL)
8222     {
8223       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8224
8225         The import in the following code:
8226         namespace A
8227           {
8228             typedef int B;
8229           }
8230
8231         int main ()
8232           {
8233             using A::B;
8234             B b;
8235             return b;
8236           }
8237
8238         ...
8239          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8240             <52>   DW_AT_decl_file   : 1
8241             <53>   DW_AT_decl_line   : 6
8242             <54>   DW_AT_import      : <0x75>
8243          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8244             <59>   DW_AT_name        : B
8245             <5b>   DW_AT_decl_file   : 1
8246             <5c>   DW_AT_decl_line   : 2
8247             <5d>   DW_AT_type        : <0x6e>
8248         ...
8249          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8250             <76>   DW_AT_byte_size   : 4
8251             <77>   DW_AT_encoding    : 5        (signed)
8252
8253         imports the wrong die ( 0x75 instead of 0x58 ).
8254         This case will be ignored until the gcc bug is fixed.  */
8255       return;
8256     }
8257
8258   /* Figure out the local name after import.  */
8259   import_alias = dwarf2_name (die, cu);
8260
8261   /* Figure out where the statement is being imported to.  */
8262   import_prefix = determine_prefix (die, cu);
8263
8264   /* Figure out what the scope of the imported die is and prepend it
8265      to the name of the imported die.  */
8266   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8267
8268   if (imported_die->tag != DW_TAG_namespace
8269       && imported_die->tag != DW_TAG_module)
8270     {
8271       imported_declaration = imported_name;
8272       canonical_name = imported_name_prefix;
8273     }
8274   else if (strlen (imported_name_prefix) > 0)
8275     canonical_name = obconcat (&objfile->objfile_obstack,
8276                                imported_name_prefix, "::", imported_name,
8277                                (char *) NULL);
8278   else
8279     canonical_name = imported_name;
8280
8281   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8282
8283   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8284     for (child_die = die->child; child_die && child_die->tag;
8285          child_die = sibling_die (child_die))
8286       {
8287         /* DWARF-4: A Fortran use statement with a “rename list” may be
8288            represented by an imported module entry with an import attribute
8289            referring to the module and owned entries corresponding to those
8290            entities that are renamed as part of being imported.  */
8291
8292         if (child_die->tag != DW_TAG_imported_declaration)
8293           {
8294             complaint (&symfile_complaints,
8295                        _("child DW_TAG_imported_declaration expected "
8296                          "- DIE at 0x%x [in module %s]"),
8297                        child_die->offset.sect_off, objfile->name);
8298             continue;
8299           }
8300
8301         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8302         if (import_attr == NULL)
8303           {
8304             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8305                        dwarf_tag_name (child_die->tag));
8306             continue;
8307           }
8308
8309         imported_cu = cu;
8310         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8311                                               &imported_cu);
8312         imported_name = dwarf2_name (imported_die, imported_cu);
8313         if (imported_name == NULL)
8314           {
8315             complaint (&symfile_complaints,
8316                        _("child DW_TAG_imported_declaration has unknown "
8317                          "imported name - DIE at 0x%x [in module %s]"),
8318                        child_die->offset.sect_off, objfile->name);
8319             continue;
8320           }
8321
8322         VEC_safe_push (const_char_ptr, excludes, imported_name);
8323
8324         process_die (child_die, cu);
8325       }
8326
8327   cp_add_using_directive (import_prefix,
8328                           canonical_name,
8329                           import_alias,
8330                           imported_declaration,
8331                           excludes,
8332                           0,
8333                           &objfile->objfile_obstack);
8334
8335   do_cleanups (cleanups);
8336 }
8337
8338 /* Cleanup function for handle_DW_AT_stmt_list.  */
8339
8340 static void
8341 free_cu_line_header (void *arg)
8342 {
8343   struct dwarf2_cu *cu = arg;
8344
8345   free_line_header (cu->line_header);
8346   cu->line_header = NULL;
8347 }
8348
8349 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8350    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8351    this, it was first present in GCC release 4.3.0.  */
8352
8353 static int
8354 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8355 {
8356   if (!cu->checked_producer)
8357     check_producer (cu);
8358
8359   return cu->producer_is_gcc_lt_4_3;
8360 }
8361
8362 static void
8363 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8364                          const char **name, const char **comp_dir)
8365 {
8366   struct attribute *attr;
8367
8368   *name = NULL;
8369   *comp_dir = NULL;
8370
8371   /* Find the filename.  Do not use dwarf2_name here, since the filename
8372      is not a source language identifier.  */
8373   attr = dwarf2_attr (die, DW_AT_name, cu);
8374   if (attr)
8375     {
8376       *name = DW_STRING (attr);
8377     }
8378
8379   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8380   if (attr)
8381     *comp_dir = DW_STRING (attr);
8382   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8383            && IS_ABSOLUTE_PATH (*name))
8384     {
8385       char *d = ldirname (*name);
8386
8387       *comp_dir = d;
8388       if (d != NULL)
8389         make_cleanup (xfree, d);
8390     }
8391   if (*comp_dir != NULL)
8392     {
8393       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8394          directory, get rid of it.  */
8395       char *cp = strchr (*comp_dir, ':');
8396
8397       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8398         *comp_dir = cp + 1;
8399     }
8400
8401   if (*name == NULL)
8402     *name = "<unknown>";
8403 }
8404
8405 /* Handle DW_AT_stmt_list for a compilation unit.
8406    DIE is the DW_TAG_compile_unit die for CU.
8407    COMP_DIR is the compilation directory.
8408    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8409
8410 static void
8411 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8412                         const char *comp_dir) /* ARI: editCase function */
8413 {
8414   struct attribute *attr;
8415
8416   gdb_assert (! cu->per_cu->is_debug_types);
8417
8418   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8419   if (attr)
8420     {
8421       unsigned int line_offset = DW_UNSND (attr);
8422       struct line_header *line_header
8423         = dwarf_decode_line_header (line_offset, cu);
8424
8425       if (line_header)
8426         {
8427           cu->line_header = line_header;
8428           make_cleanup (free_cu_line_header, cu);
8429           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8430         }
8431     }
8432 }
8433
8434 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8435
8436 static void
8437 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8438 {
8439   struct objfile *objfile = dwarf2_per_objfile->objfile;
8440   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8441   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8442   CORE_ADDR highpc = ((CORE_ADDR) 0);
8443   struct attribute *attr;
8444   const char *name = NULL;
8445   const char *comp_dir = NULL;
8446   struct die_info *child_die;
8447   bfd *abfd = objfile->obfd;
8448   CORE_ADDR baseaddr;
8449
8450   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8451
8452   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8453
8454   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8455      from finish_block.  */
8456   if (lowpc == ((CORE_ADDR) -1))
8457     lowpc = highpc;
8458   lowpc += baseaddr;
8459   highpc += baseaddr;
8460
8461   find_file_and_directory (die, cu, &name, &comp_dir);
8462
8463   prepare_one_comp_unit (cu, die, cu->language);
8464
8465   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8466      standardised yet.  As a workaround for the language detection we fall
8467      back to the DW_AT_producer string.  */
8468   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8469     cu->language = language_opencl;
8470
8471   /* Similar hack for Go.  */
8472   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8473     set_cu_language (DW_LANG_Go, cu);
8474
8475   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8476
8477   /* Decode line number information if present.  We do this before
8478      processing child DIEs, so that the line header table is available
8479      for DW_AT_decl_file.  */
8480   handle_DW_AT_stmt_list (die, cu, comp_dir);
8481
8482   /* Process all dies in compilation unit.  */
8483   if (die->child != NULL)
8484     {
8485       child_die = die->child;
8486       while (child_die && child_die->tag)
8487         {
8488           process_die (child_die, cu);
8489           child_die = sibling_die (child_die);
8490         }
8491     }
8492
8493   /* Decode macro information, if present.  Dwarf 2 macro information
8494      refers to information in the line number info statement program
8495      header, so we can only read it if we've read the header
8496      successfully.  */
8497   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8498   if (attr && cu->line_header)
8499     {
8500       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8501         complaint (&symfile_complaints,
8502                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8503
8504       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8505     }
8506   else
8507     {
8508       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8509       if (attr && cu->line_header)
8510         {
8511           unsigned int macro_offset = DW_UNSND (attr);
8512
8513           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8514         }
8515     }
8516
8517   do_cleanups (back_to);
8518 }
8519
8520 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8521    Create the set of symtabs used by this TU, or if this TU is sharing
8522    symtabs with another TU and the symtabs have already been created
8523    then restore those symtabs in the line header.
8524    We don't need the pc/line-number mapping for type units.  */
8525
8526 static void
8527 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8528 {
8529   struct objfile *objfile = dwarf2_per_objfile->objfile;
8530   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8531   struct type_unit_group *tu_group;
8532   int first_time;
8533   struct line_header *lh;
8534   struct attribute *attr;
8535   unsigned int i, line_offset;
8536   struct signatured_type *sig_type;
8537
8538   gdb_assert (per_cu->is_debug_types);
8539   sig_type = (struct signatured_type *) per_cu;
8540
8541   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8542
8543   /* If we're using .gdb_index (includes -readnow) then
8544      per_cu->type_unit_group may not have been set up yet.  */
8545   if (sig_type->type_unit_group == NULL)
8546     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8547   tu_group = sig_type->type_unit_group;
8548
8549   /* If we've already processed this stmt_list there's no real need to
8550      do it again, we could fake it and just recreate the part we need
8551      (file name,index -> symtab mapping).  If data shows this optimization
8552      is useful we can do it then.  */
8553   first_time = tu_group->primary_symtab == NULL;
8554
8555   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8556      debug info.  */
8557   lh = NULL;
8558   if (attr != NULL)
8559     {
8560       line_offset = DW_UNSND (attr);
8561       lh = dwarf_decode_line_header (line_offset, cu);
8562     }
8563   if (lh == NULL)
8564     {
8565       if (first_time)
8566         dwarf2_start_symtab (cu, "", NULL, 0);
8567       else
8568         {
8569           gdb_assert (tu_group->symtabs == NULL);
8570           restart_symtab (0);
8571         }
8572       /* Note: The primary symtab will get allocated at the end.  */
8573       return;
8574     }
8575
8576   cu->line_header = lh;
8577   make_cleanup (free_cu_line_header, cu);
8578
8579   if (first_time)
8580     {
8581       dwarf2_start_symtab (cu, "", NULL, 0);
8582
8583       tu_group->num_symtabs = lh->num_file_names;
8584       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8585
8586       for (i = 0; i < lh->num_file_names; ++i)
8587         {
8588           const char *dir = NULL;
8589           struct file_entry *fe = &lh->file_names[i];
8590
8591           if (fe->dir_index)
8592             dir = lh->include_dirs[fe->dir_index - 1];
8593           dwarf2_start_subfile (fe->name, dir, NULL);
8594
8595           /* Note: We don't have to watch for the main subfile here, type units
8596              don't have DW_AT_name.  */
8597
8598           if (current_subfile->symtab == NULL)
8599             {
8600               /* NOTE: start_subfile will recognize when it's been passed
8601                  a file it has already seen.  So we can't assume there's a
8602                  simple mapping from lh->file_names to subfiles,
8603                  lh->file_names may contain dups.  */
8604               current_subfile->symtab = allocate_symtab (current_subfile->name,
8605                                                          objfile);
8606             }
8607
8608           fe->symtab = current_subfile->symtab;
8609           tu_group->symtabs[i] = fe->symtab;
8610         }
8611     }
8612   else
8613     {
8614       restart_symtab (0);
8615
8616       for (i = 0; i < lh->num_file_names; ++i)
8617         {
8618           struct file_entry *fe = &lh->file_names[i];
8619
8620           fe->symtab = tu_group->symtabs[i];
8621         }
8622     }
8623
8624   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8625      so they don't have a "real" (so to speak) symtab anyway.
8626      There is later code that will assign the main symtab to all symbols
8627      that don't have one.  We need to handle the case of a symbol with a
8628      missing symtab (DW_AT_decl_file) anyway.  */
8629 }
8630
8631 /* Process DW_TAG_type_unit.
8632    For TUs we want to skip the first top level sibling if it's not the
8633    actual type being defined by this TU.  In this case the first top
8634    level sibling is there to provide context only.  */
8635
8636 static void
8637 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8638 {
8639   struct die_info *child_die;
8640
8641   prepare_one_comp_unit (cu, die, language_minimal);
8642
8643   /* Initialize (or reinitialize) the machinery for building symtabs.
8644      We do this before processing child DIEs, so that the line header table
8645      is available for DW_AT_decl_file.  */
8646   setup_type_unit_groups (die, cu);
8647
8648   if (die->child != NULL)
8649     {
8650       child_die = die->child;
8651       while (child_die && child_die->tag)
8652         {
8653           process_die (child_die, cu);
8654           child_die = sibling_die (child_die);
8655         }
8656     }
8657 }
8658 \f
8659 /* DWO/DWP files.
8660
8661    http://gcc.gnu.org/wiki/DebugFission
8662    http://gcc.gnu.org/wiki/DebugFissionDWP
8663
8664    To simplify handling of both DWO files ("object" files with the DWARF info)
8665    and DWP files (a file with the DWOs packaged up into one file), we treat
8666    DWP files as having a collection of virtual DWO files.  */
8667
8668 static hashval_t
8669 hash_dwo_file (const void *item)
8670 {
8671   const struct dwo_file *dwo_file = item;
8672   hashval_t hash;
8673
8674   hash = htab_hash_string (dwo_file->dwo_name);
8675   if (dwo_file->comp_dir != NULL)
8676     hash += htab_hash_string (dwo_file->comp_dir);
8677   return hash;
8678 }
8679
8680 static int
8681 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8682 {
8683   const struct dwo_file *lhs = item_lhs;
8684   const struct dwo_file *rhs = item_rhs;
8685
8686   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8687     return 0;
8688   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8689     return lhs->comp_dir == rhs->comp_dir;
8690   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8691 }
8692
8693 /* Allocate a hash table for DWO files.  */
8694
8695 static htab_t
8696 allocate_dwo_file_hash_table (void)
8697 {
8698   struct objfile *objfile = dwarf2_per_objfile->objfile;
8699
8700   return htab_create_alloc_ex (41,
8701                                hash_dwo_file,
8702                                eq_dwo_file,
8703                                NULL,
8704                                &objfile->objfile_obstack,
8705                                hashtab_obstack_allocate,
8706                                dummy_obstack_deallocate);
8707 }
8708
8709 /* Lookup DWO file DWO_NAME.  */
8710
8711 static void **
8712 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8713 {
8714   struct dwo_file find_entry;
8715   void **slot;
8716
8717   if (dwarf2_per_objfile->dwo_files == NULL)
8718     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8719
8720   memset (&find_entry, 0, sizeof (find_entry));
8721   find_entry.dwo_name = dwo_name;
8722   find_entry.comp_dir = comp_dir;
8723   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8724
8725   return slot;
8726 }
8727
8728 static hashval_t
8729 hash_dwo_unit (const void *item)
8730 {
8731   const struct dwo_unit *dwo_unit = item;
8732
8733   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8734   return dwo_unit->signature;
8735 }
8736
8737 static int
8738 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8739 {
8740   const struct dwo_unit *lhs = item_lhs;
8741   const struct dwo_unit *rhs = item_rhs;
8742
8743   /* The signature is assumed to be unique within the DWO file.
8744      So while object file CU dwo_id's always have the value zero,
8745      that's OK, assuming each object file DWO file has only one CU,
8746      and that's the rule for now.  */
8747   return lhs->signature == rhs->signature;
8748 }
8749
8750 /* Allocate a hash table for DWO CUs,TUs.
8751    There is one of these tables for each of CUs,TUs for each DWO file.  */
8752
8753 static htab_t
8754 allocate_dwo_unit_table (struct objfile *objfile)
8755 {
8756   /* Start out with a pretty small number.
8757      Generally DWO files contain only one CU and maybe some TUs.  */
8758   return htab_create_alloc_ex (3,
8759                                hash_dwo_unit,
8760                                eq_dwo_unit,
8761                                NULL,
8762                                &objfile->objfile_obstack,
8763                                hashtab_obstack_allocate,
8764                                dummy_obstack_deallocate);
8765 }
8766
8767 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8768
8769 struct create_dwo_cu_data
8770 {
8771   struct dwo_file *dwo_file;
8772   struct dwo_unit dwo_unit;
8773 };
8774
8775 /* die_reader_func for create_dwo_cu.  */
8776
8777 static void
8778 create_dwo_cu_reader (const struct die_reader_specs *reader,
8779                       const gdb_byte *info_ptr,
8780                       struct die_info *comp_unit_die,
8781                       int has_children,
8782                       void *datap)
8783 {
8784   struct dwarf2_cu *cu = reader->cu;
8785   struct objfile *objfile = dwarf2_per_objfile->objfile;
8786   sect_offset offset = cu->per_cu->offset;
8787   struct dwarf2_section_info *section = cu->per_cu->section;
8788   struct create_dwo_cu_data *data = datap;
8789   struct dwo_file *dwo_file = data->dwo_file;
8790   struct dwo_unit *dwo_unit = &data->dwo_unit;
8791   struct attribute *attr;
8792
8793   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8794   if (attr == NULL)
8795     {
8796       complaint (&symfile_complaints,
8797                  _("Dwarf Error: debug entry at offset 0x%x is missing"
8798                    " its dwo_id [in module %s]"),
8799                  offset.sect_off, dwo_file->dwo_name);
8800       return;
8801     }
8802
8803   dwo_unit->dwo_file = dwo_file;
8804   dwo_unit->signature = DW_UNSND (attr);
8805   dwo_unit->section = section;
8806   dwo_unit->offset = offset;
8807   dwo_unit->length = cu->per_cu->length;
8808
8809   if (dwarf2_read_debug)
8810     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8811                         offset.sect_off, hex_string (dwo_unit->signature));
8812 }
8813
8814 /* Create the dwo_unit for the lone CU in DWO_FILE.
8815    Note: This function processes DWO files only, not DWP files.  */
8816
8817 static struct dwo_unit *
8818 create_dwo_cu (struct dwo_file *dwo_file)
8819 {
8820   struct objfile *objfile = dwarf2_per_objfile->objfile;
8821   struct dwarf2_section_info *section = &dwo_file->sections.info;
8822   bfd *abfd;
8823   htab_t cu_htab;
8824   const gdb_byte *info_ptr, *end_ptr;
8825   struct create_dwo_cu_data create_dwo_cu_data;
8826   struct dwo_unit *dwo_unit;
8827
8828   dwarf2_read_section (objfile, section);
8829   info_ptr = section->buffer;
8830
8831   if (info_ptr == NULL)
8832     return NULL;
8833
8834   /* We can't set abfd until now because the section may be empty or
8835      not present, in which case section->asection will be NULL.  */
8836   abfd = section->asection->owner;
8837
8838   if (dwarf2_read_debug)
8839     {
8840       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
8841                           bfd_section_name (abfd, section->asection),
8842                           bfd_get_filename (abfd));
8843     }
8844
8845   create_dwo_cu_data.dwo_file = dwo_file;
8846   dwo_unit = NULL;
8847
8848   end_ptr = info_ptr + section->size;
8849   while (info_ptr < end_ptr)
8850     {
8851       struct dwarf2_per_cu_data per_cu;
8852
8853       memset (&create_dwo_cu_data.dwo_unit, 0,
8854               sizeof (create_dwo_cu_data.dwo_unit));
8855       memset (&per_cu, 0, sizeof (per_cu));
8856       per_cu.objfile = objfile;
8857       per_cu.is_debug_types = 0;
8858       per_cu.offset.sect_off = info_ptr - section->buffer;
8859       per_cu.section = section;
8860
8861       init_cutu_and_read_dies_no_follow (&per_cu,
8862                                          &dwo_file->sections.abbrev,
8863                                          dwo_file,
8864                                          create_dwo_cu_reader,
8865                                          &create_dwo_cu_data);
8866
8867       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
8868         {
8869           /* If we've already found one, complain.  We only support one
8870              because having more than one requires hacking the dwo_name of
8871              each to match, which is highly unlikely to happen.  */
8872           if (dwo_unit != NULL)
8873             {
8874               complaint (&symfile_complaints,
8875                          _("Multiple CUs in DWO file %s [in module %s]"),
8876                          dwo_file->dwo_name, objfile->name);
8877               break;
8878             }
8879
8880           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8881           *dwo_unit = create_dwo_cu_data.dwo_unit;
8882         }
8883
8884       info_ptr += per_cu.length;
8885     }
8886
8887   return dwo_unit;
8888 }
8889
8890 /* DWP file .debug_{cu,tu}_index section format:
8891    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8892
8893    DWP Version 1:
8894
8895    Both index sections have the same format, and serve to map a 64-bit
8896    signature to a set of section numbers.  Each section begins with a header,
8897    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8898    indexes, and a pool of 32-bit section numbers.  The index sections will be
8899    aligned at 8-byte boundaries in the file.
8900
8901    The index section header consists of:
8902
8903     V, 32 bit version number
8904     -, 32 bits unused
8905     N, 32 bit number of compilation units or type units in the index
8906     M, 32 bit number of slots in the hash table
8907
8908    Numbers are recorded using the byte order of the application binary.
8909
8910    We assume that N and M will not exceed 2^32 - 1.
8911
8912    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8913
8914    The hash table begins at offset 16 in the section, and consists of an array
8915    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8916    order of the application binary).  Unused slots in the hash table are 0.
8917    (We rely on the extreme unlikeliness of a signature being exactly 0.)
8918
8919    The parallel table begins immediately after the hash table
8920    (at offset 16 + 8 * M from the beginning of the section), and consists of an
8921    array of 32-bit indexes (using the byte order of the application binary),
8922    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8923    table contains a 32-bit index into the pool of section numbers.  For unused
8924    hash table slots, the corresponding entry in the parallel table will be 0.
8925
8926    Given a 64-bit compilation unit signature or a type signature S, an entry
8927    in the hash table is located as follows:
8928
8929    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8930       the low-order k bits all set to 1.
8931
8932    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8933
8934    3) If the hash table entry at index H matches the signature, use that
8935       entry.  If the hash table entry at index H is unused (all zeroes),
8936       terminate the search: the signature is not present in the table.
8937
8938    4) Let H = (H + H') modulo M. Repeat at Step 3.
8939
8940    Because M > N and H' and M are relatively prime, the search is guaranteed
8941    to stop at an unused slot or find the match.
8942
8943    The pool of section numbers begins immediately following the hash table
8944    (at offset 16 + 12 * M from the beginning of the section).  The pool of
8945    section numbers consists of an array of 32-bit words (using the byte order
8946    of the application binary).  Each item in the array is indexed starting
8947    from 0.  The hash table entry provides the index of the first section
8948    number in the set.  Additional section numbers in the set follow, and the
8949    set is terminated by a 0 entry (section number 0 is not used in ELF).
8950
8951    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8952    section must be the first entry in the set, and the .debug_abbrev.dwo must
8953    be the second entry. Other members of the set may follow in any order.  */
8954
8955 /* Create a hash table to map DWO IDs to their CU/TU entry in
8956    .debug_{info,types}.dwo in DWP_FILE.
8957    Returns NULL if there isn't one.
8958    Note: This function processes DWP files only, not DWO files.  */
8959
8960 static struct dwp_hash_table *
8961 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8962 {
8963   struct objfile *objfile = dwarf2_per_objfile->objfile;
8964   bfd *dbfd = dwp_file->dbfd;
8965   const gdb_byte *index_ptr, *index_end;
8966   struct dwarf2_section_info *index;
8967   uint32_t version, nr_units, nr_slots;
8968   struct dwp_hash_table *htab;
8969
8970   if (is_debug_types)
8971     index = &dwp_file->sections.tu_index;
8972   else
8973     index = &dwp_file->sections.cu_index;
8974
8975   if (dwarf2_section_empty_p (index))
8976     return NULL;
8977   dwarf2_read_section (objfile, index);
8978
8979   index_ptr = index->buffer;
8980   index_end = index_ptr + index->size;
8981
8982   version = read_4_bytes (dbfd, index_ptr);
8983   index_ptr += 8; /* Skip the unused word.  */
8984   nr_units = read_4_bytes (dbfd, index_ptr);
8985   index_ptr += 4;
8986   nr_slots = read_4_bytes (dbfd, index_ptr);
8987   index_ptr += 4;
8988
8989   if (version != 1)
8990     {
8991       error (_("Dwarf Error: unsupported DWP file version (%s)"
8992                " [in module %s]"),
8993              pulongest (version), dwp_file->name);
8994     }
8995   if (nr_slots != (nr_slots & -nr_slots))
8996     {
8997       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
8998                " is not power of 2 [in module %s]"),
8999              pulongest (nr_slots), dwp_file->name);
9000     }
9001
9002   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9003   htab->nr_units = nr_units;
9004   htab->nr_slots = nr_slots;
9005   htab->hash_table = index_ptr;
9006   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9007   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
9008
9009   return htab;
9010 }
9011
9012 /* Update SECTIONS with the data from SECTP.
9013
9014    This function is like the other "locate" section routines that are
9015    passed to bfd_map_over_sections, but in this context the sections to
9016    read comes from the DWP hash table, not the full ELF section table.
9017
9018    The result is non-zero for success, or zero if an error was found.  */
9019
9020 static int
9021 locate_virtual_dwo_sections (asection *sectp,
9022                              struct virtual_dwo_sections *sections)
9023 {
9024   const struct dwop_section_names *names = &dwop_section_names;
9025
9026   if (section_is_p (sectp->name, &names->abbrev_dwo))
9027     {
9028       /* There can be only one.  */
9029       if (sections->abbrev.asection != NULL)
9030         return 0;
9031       sections->abbrev.asection = sectp;
9032       sections->abbrev.size = bfd_get_section_size (sectp);
9033     }
9034   else if (section_is_p (sectp->name, &names->info_dwo)
9035            || section_is_p (sectp->name, &names->types_dwo))
9036     {
9037       /* There can be only one.  */
9038       if (sections->info_or_types.asection != NULL)
9039         return 0;
9040       sections->info_or_types.asection = sectp;
9041       sections->info_or_types.size = bfd_get_section_size (sectp);
9042     }
9043   else if (section_is_p (sectp->name, &names->line_dwo))
9044     {
9045       /* There can be only one.  */
9046       if (sections->line.asection != NULL)
9047         return 0;
9048       sections->line.asection = sectp;
9049       sections->line.size = bfd_get_section_size (sectp);
9050     }
9051   else if (section_is_p (sectp->name, &names->loc_dwo))
9052     {
9053       /* There can be only one.  */
9054       if (sections->loc.asection != NULL)
9055         return 0;
9056       sections->loc.asection = sectp;
9057       sections->loc.size = bfd_get_section_size (sectp);
9058     }
9059   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9060     {
9061       /* There can be only one.  */
9062       if (sections->macinfo.asection != NULL)
9063         return 0;
9064       sections->macinfo.asection = sectp;
9065       sections->macinfo.size = bfd_get_section_size (sectp);
9066     }
9067   else if (section_is_p (sectp->name, &names->macro_dwo))
9068     {
9069       /* There can be only one.  */
9070       if (sections->macro.asection != NULL)
9071         return 0;
9072       sections->macro.asection = sectp;
9073       sections->macro.size = bfd_get_section_size (sectp);
9074     }
9075   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9076     {
9077       /* There can be only one.  */
9078       if (sections->str_offsets.asection != NULL)
9079         return 0;
9080       sections->str_offsets.asection = sectp;
9081       sections->str_offsets.size = bfd_get_section_size (sectp);
9082     }
9083   else
9084     {
9085       /* No other kind of section is valid.  */
9086       return 0;
9087     }
9088
9089   return 1;
9090 }
9091
9092 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
9093    HTAB is the hash table from the DWP file.
9094    SECTION_INDEX is the index of the DWO in HTAB.
9095    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
9096
9097 static struct dwo_unit *
9098 create_dwo_in_dwp (struct dwp_file *dwp_file,
9099                    const struct dwp_hash_table *htab,
9100                    uint32_t section_index,
9101                    const char *comp_dir,
9102                    ULONGEST signature, int is_debug_types)
9103 {
9104   struct objfile *objfile = dwarf2_per_objfile->objfile;
9105   bfd *dbfd = dwp_file->dbfd;
9106   const char *kind = is_debug_types ? "TU" : "CU";
9107   struct dwo_file *dwo_file;
9108   struct dwo_unit *dwo_unit;
9109   struct virtual_dwo_sections sections;
9110   void **dwo_file_slot;
9111   char *virtual_dwo_name;
9112   struct dwarf2_section_info *cutu;
9113   struct cleanup *cleanups;
9114   int i;
9115
9116   if (dwarf2_read_debug)
9117     {
9118       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP file: %s\n",
9119                           kind,
9120                           pulongest (section_index), hex_string (signature),
9121                           dwp_file->name);
9122     }
9123
9124   /* Fetch the sections of this DWO.
9125      Put a limit on the number of sections we look for so that bad data
9126      doesn't cause us to loop forever.  */
9127
9128 #define MAX_NR_DWO_SECTIONS \
9129   (1 /* .debug_info or .debug_types */ \
9130    + 1 /* .debug_abbrev */ \
9131    + 1 /* .debug_line */ \
9132    + 1 /* .debug_loc */ \
9133    + 1 /* .debug_str_offsets */ \
9134    + 1 /* .debug_macro */ \
9135    + 1 /* .debug_macinfo */ \
9136    + 1 /* trailing zero */)
9137
9138   memset (&sections, 0, sizeof (sections));
9139   cleanups = make_cleanup (null_cleanup, 0);
9140
9141   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
9142     {
9143       asection *sectp;
9144       uint32_t section_nr =
9145         read_4_bytes (dbfd,
9146                       htab->section_pool
9147                       + (section_index + i) * sizeof (uint32_t));
9148
9149       if (section_nr == 0)
9150         break;
9151       if (section_nr >= dwp_file->num_sections)
9152         {
9153           error (_("Dwarf Error: bad DWP hash table, section number too large"
9154                    " [in module %s]"),
9155                  dwp_file->name);
9156         }
9157
9158       sectp = dwp_file->elf_sections[section_nr];
9159       if (! locate_virtual_dwo_sections (sectp, &sections))
9160         {
9161           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9162                    " [in module %s]"),
9163                  dwp_file->name);
9164         }
9165     }
9166
9167   if (i < 2
9168       || sections.info_or_types.asection == NULL
9169       || sections.abbrev.asection == NULL)
9170     {
9171       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9172                " [in module %s]"),
9173              dwp_file->name);
9174     }
9175   if (i == MAX_NR_DWO_SECTIONS)
9176     {
9177       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9178                " [in module %s]"),
9179              dwp_file->name);
9180     }
9181
9182   /* It's easier for the rest of the code if we fake a struct dwo_file and
9183      have dwo_unit "live" in that.  At least for now.
9184
9185      The DWP file can be made up of a random collection of CUs and TUs.
9186      However, for each CU + set of TUs that came from the same original DWO
9187      file, we want to combine them back into a virtual DWO file to save space
9188      (fewer struct dwo_file objects to allocated).  Remember that for really
9189      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9190
9191   virtual_dwo_name =
9192     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9193                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
9194                 sections.line.asection ? sections.line.asection->id : 0,
9195                 sections.loc.asection ? sections.loc.asection->id : 0,
9196                 (sections.str_offsets.asection
9197                 ? sections.str_offsets.asection->id
9198                 : 0));
9199   make_cleanup (xfree, virtual_dwo_name);
9200   /* Can we use an existing virtual DWO file?  */
9201   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9202   /* Create one if necessary.  */
9203   if (*dwo_file_slot == NULL)
9204     {
9205       if (dwarf2_read_debug)
9206         {
9207           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9208                               virtual_dwo_name);
9209         }
9210       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9211       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9212                                           virtual_dwo_name,
9213                                           strlen (virtual_dwo_name));
9214       dwo_file->comp_dir = comp_dir;
9215       dwo_file->sections.abbrev = sections.abbrev;
9216       dwo_file->sections.line = sections.line;
9217       dwo_file->sections.loc = sections.loc;
9218       dwo_file->sections.macinfo = sections.macinfo;
9219       dwo_file->sections.macro = sections.macro;
9220       dwo_file->sections.str_offsets = sections.str_offsets;
9221       /* The "str" section is global to the entire DWP file.  */
9222       dwo_file->sections.str = dwp_file->sections.str;
9223       /* The info or types section is assigned later to dwo_unit,
9224          there's no need to record it in dwo_file.
9225          Also, we can't simply record type sections in dwo_file because
9226          we record a pointer into the vector in dwo_unit.  As we collect more
9227          types we'll grow the vector and eventually have to reallocate space
9228          for it, invalidating all the pointers into the current copy.  */
9229       *dwo_file_slot = dwo_file;
9230     }
9231   else
9232     {
9233       if (dwarf2_read_debug)
9234         {
9235           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9236                               virtual_dwo_name);
9237         }
9238       dwo_file = *dwo_file_slot;
9239     }
9240   do_cleanups (cleanups);
9241
9242   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9243   dwo_unit->dwo_file = dwo_file;
9244   dwo_unit->signature = signature;
9245   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9246                                      sizeof (struct dwarf2_section_info));
9247   *dwo_unit->section = sections.info_or_types;
9248   /* offset, length, type_offset_in_tu are set later.  */
9249
9250   return dwo_unit;
9251 }
9252
9253 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
9254
9255 static struct dwo_unit *
9256 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
9257                    const struct dwp_hash_table *htab,
9258                    const char *comp_dir,
9259                    ULONGEST signature, int is_debug_types)
9260 {
9261   bfd *dbfd = dwp_file->dbfd;
9262   uint32_t mask = htab->nr_slots - 1;
9263   uint32_t hash = signature & mask;
9264   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9265   unsigned int i;
9266   void **slot;
9267   struct dwo_unit find_dwo_cu, *dwo_cu;
9268
9269   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9270   find_dwo_cu.signature = signature;
9271   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
9272
9273   if (*slot != NULL)
9274     return *slot;
9275
9276   /* Use a for loop so that we don't loop forever on bad debug info.  */
9277   for (i = 0; i < htab->nr_slots; ++i)
9278     {
9279       ULONGEST signature_in_table;
9280
9281       signature_in_table =
9282         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
9283       if (signature_in_table == signature)
9284         {
9285           uint32_t section_index =
9286             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
9287
9288           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
9289                                      comp_dir, signature, is_debug_types);
9290           return *slot;
9291         }
9292       if (signature_in_table == 0)
9293         return NULL;
9294       hash = (hash + hash2) & mask;
9295     }
9296
9297   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9298            " [in module %s]"),
9299          dwp_file->name);
9300 }
9301
9302 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9303    Open the file specified by FILE_NAME and hand it off to BFD for
9304    preliminary analysis.  Return a newly initialized bfd *, which
9305    includes a canonicalized copy of FILE_NAME.
9306    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9307    In case of trouble, return NULL.
9308    NOTE: This function is derived from symfile_bfd_open.  */
9309
9310 static bfd *
9311 try_open_dwop_file (const char *file_name, int is_dwp)
9312 {
9313   bfd *sym_bfd;
9314   int desc, flags;
9315   char *absolute_name;
9316   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
9317      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
9318      to debug_file_directory.  */
9319   char *search_path;
9320   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
9321
9322   if (*debug_file_directory != '\0')
9323     search_path = concat (".", dirname_separator_string, debug_file_directory,
9324                           NULL);
9325   else
9326     search_path = xstrdup (".");
9327
9328   flags = 0;
9329   if (is_dwp)
9330     flags |= OPF_SEARCH_IN_PATH;
9331   desc = openp (search_path, flags, file_name,
9332                 O_RDONLY | O_BINARY, &absolute_name);
9333   xfree (search_path);
9334   if (desc < 0)
9335     return NULL;
9336
9337   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
9338   xfree (absolute_name);
9339   if (sym_bfd == NULL)
9340     return NULL;
9341   bfd_set_cacheable (sym_bfd, 1);
9342
9343   if (!bfd_check_format (sym_bfd, bfd_object))
9344     {
9345       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
9346       return NULL;
9347     }
9348
9349   return sym_bfd;
9350 }
9351
9352 /* Try to open DWO file FILE_NAME.
9353    COMP_DIR is the DW_AT_comp_dir attribute.
9354    The result is the bfd handle of the file.
9355    If there is a problem finding or opening the file, return NULL.
9356    Upon success, the canonicalized path of the file is stored in the bfd,
9357    same as symfile_bfd_open.  */
9358
9359 static bfd *
9360 open_dwo_file (const char *file_name, const char *comp_dir)
9361 {
9362   bfd *abfd;
9363
9364   if (IS_ABSOLUTE_PATH (file_name))
9365     return try_open_dwop_file (file_name, 0 /*is_dwp*/);
9366
9367   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
9368
9369   if (comp_dir != NULL)
9370     {
9371       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
9372
9373       /* NOTE: If comp_dir is a relative path, this will also try the
9374          search path, which seems useful.  */
9375       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/);
9376       xfree (path_to_try);
9377       if (abfd != NULL)
9378         return abfd;
9379     }
9380
9381   /* That didn't work, try debug-file-directory, which, despite its name,
9382      is a list of paths.  */
9383
9384   if (*debug_file_directory == '\0')
9385     return NULL;
9386
9387   return try_open_dwop_file (file_name, 0 /*is_dwp*/);
9388 }
9389
9390 /* This function is mapped across the sections and remembers the offset and
9391    size of each of the DWO debugging sections we are interested in.  */
9392
9393 static void
9394 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9395 {
9396   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9397   const struct dwop_section_names *names = &dwop_section_names;
9398
9399   if (section_is_p (sectp->name, &names->abbrev_dwo))
9400     {
9401       dwo_sections->abbrev.asection = sectp;
9402       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9403     }
9404   else if (section_is_p (sectp->name, &names->info_dwo))
9405     {
9406       dwo_sections->info.asection = sectp;
9407       dwo_sections->info.size = bfd_get_section_size (sectp);
9408     }
9409   else if (section_is_p (sectp->name, &names->line_dwo))
9410     {
9411       dwo_sections->line.asection = sectp;
9412       dwo_sections->line.size = bfd_get_section_size (sectp);
9413     }
9414   else if (section_is_p (sectp->name, &names->loc_dwo))
9415     {
9416       dwo_sections->loc.asection = sectp;
9417       dwo_sections->loc.size = bfd_get_section_size (sectp);
9418     }
9419   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9420     {
9421       dwo_sections->macinfo.asection = sectp;
9422       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9423     }
9424   else if (section_is_p (sectp->name, &names->macro_dwo))
9425     {
9426       dwo_sections->macro.asection = sectp;
9427       dwo_sections->macro.size = bfd_get_section_size (sectp);
9428     }
9429   else if (section_is_p (sectp->name, &names->str_dwo))
9430     {
9431       dwo_sections->str.asection = sectp;
9432       dwo_sections->str.size = bfd_get_section_size (sectp);
9433     }
9434   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9435     {
9436       dwo_sections->str_offsets.asection = sectp;
9437       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9438     }
9439   else if (section_is_p (sectp->name, &names->types_dwo))
9440     {
9441       struct dwarf2_section_info type_section;
9442
9443       memset (&type_section, 0, sizeof (type_section));
9444       type_section.asection = sectp;
9445       type_section.size = bfd_get_section_size (sectp);
9446       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9447                      &type_section);
9448     }
9449 }
9450
9451 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9452    by PER_CU.  This is for the non-DWP case.
9453    The result is NULL if DWO_NAME can't be found.  */
9454
9455 static struct dwo_file *
9456 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9457                         const char *dwo_name, const char *comp_dir)
9458 {
9459   struct objfile *objfile = dwarf2_per_objfile->objfile;
9460   struct dwo_file *dwo_file;
9461   bfd *dbfd;
9462   struct cleanup *cleanups;
9463
9464   dbfd = open_dwo_file (dwo_name, comp_dir);
9465   if (dbfd == NULL)
9466     {
9467       if (dwarf2_read_debug)
9468         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9469       return NULL;
9470     }
9471   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9472   dwo_file->dwo_name = dwo_name;
9473   dwo_file->comp_dir = comp_dir;
9474   dwo_file->dbfd = dbfd;
9475
9476   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9477
9478   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9479
9480   dwo_file->cu = create_dwo_cu (dwo_file);
9481
9482   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9483                                                  dwo_file->sections.types);
9484
9485   discard_cleanups (cleanups);
9486
9487   if (dwarf2_read_debug)
9488     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9489
9490   return dwo_file;
9491 }
9492
9493 /* This function is mapped across the sections and remembers the offset and
9494    size of each of the DWP debugging sections we are interested in.  */
9495
9496 static void
9497 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9498 {
9499   struct dwp_file *dwp_file = dwp_file_ptr;
9500   const struct dwop_section_names *names = &dwop_section_names;
9501   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9502
9503   /* Record the ELF section number for later lookup: this is what the
9504      .debug_cu_index,.debug_tu_index tables use.  */
9505   gdb_assert (elf_section_nr < dwp_file->num_sections);
9506   dwp_file->elf_sections[elf_section_nr] = sectp;
9507
9508   /* Look for specific sections that we need.  */
9509   if (section_is_p (sectp->name, &names->str_dwo))
9510     {
9511       dwp_file->sections.str.asection = sectp;
9512       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9513     }
9514   else if (section_is_p (sectp->name, &names->cu_index))
9515     {
9516       dwp_file->sections.cu_index.asection = sectp;
9517       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9518     }
9519   else if (section_is_p (sectp->name, &names->tu_index))
9520     {
9521       dwp_file->sections.tu_index.asection = sectp;
9522       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9523     }
9524 }
9525
9526 /* Hash function for dwp_file loaded CUs/TUs.  */
9527
9528 static hashval_t
9529 hash_dwp_loaded_cutus (const void *item)
9530 {
9531   const struct dwo_unit *dwo_unit = item;
9532
9533   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9534   return dwo_unit->signature;
9535 }
9536
9537 /* Equality function for dwp_file loaded CUs/TUs.  */
9538
9539 static int
9540 eq_dwp_loaded_cutus (const void *a, const void *b)
9541 {
9542   const struct dwo_unit *dua = a;
9543   const struct dwo_unit *dub = b;
9544
9545   return dua->signature == dub->signature;
9546 }
9547
9548 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9549
9550 static htab_t
9551 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9552 {
9553   return htab_create_alloc_ex (3,
9554                                hash_dwp_loaded_cutus,
9555                                eq_dwp_loaded_cutus,
9556                                NULL,
9557                                &objfile->objfile_obstack,
9558                                hashtab_obstack_allocate,
9559                                dummy_obstack_deallocate);
9560 }
9561
9562 /* Try to open DWP file FILE_NAME.
9563    The result is the bfd handle of the file.
9564    If there is a problem finding or opening the file, return NULL.
9565    Upon success, the canonicalized path of the file is stored in the bfd,
9566    same as symfile_bfd_open.  */
9567
9568 static bfd *
9569 open_dwp_file (const char *file_name)
9570 {
9571   return try_open_dwop_file (file_name, 1 /*is_dwp*/);
9572 }
9573
9574 /* Initialize the use of the DWP file for the current objfile.
9575    By convention the name of the DWP file is ${objfile}.dwp.
9576    The result is NULL if it can't be found.  */
9577
9578 static struct dwp_file *
9579 open_and_init_dwp_file (void)
9580 {
9581   struct objfile *objfile = dwarf2_per_objfile->objfile;
9582   struct dwp_file *dwp_file;
9583   char *dwp_name;
9584   bfd *dbfd;
9585   struct cleanup *cleanups;
9586
9587   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9588   cleanups = make_cleanup (xfree, dwp_name);
9589
9590   dbfd = open_dwp_file (dwp_name);
9591   if (dbfd == NULL)
9592     {
9593       if (dwarf2_read_debug)
9594         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9595       do_cleanups (cleanups);
9596       return NULL;
9597     }
9598   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9599   dwp_file->name = bfd_get_filename (dbfd);
9600   dwp_file->dbfd = dbfd;
9601   do_cleanups (cleanups);
9602
9603   /* +1: section 0 is unused */
9604   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9605   dwp_file->elf_sections =
9606     OBSTACK_CALLOC (&objfile->objfile_obstack,
9607                     dwp_file->num_sections, asection *);
9608
9609   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9610
9611   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9612
9613   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9614
9615   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9616
9617   if (dwarf2_read_debug)
9618     {
9619       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9620       fprintf_unfiltered (gdb_stdlog,
9621                           "    %s CUs, %s TUs\n",
9622                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
9623                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
9624     }
9625
9626   return dwp_file;
9627 }
9628
9629 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9630
9631 static struct dwp_file *
9632 get_dwp_file (void)
9633 {
9634   if (! dwarf2_per_objfile->dwp_checked)
9635     {
9636       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9637       dwarf2_per_objfile->dwp_checked = 1;
9638     }
9639   return dwarf2_per_objfile->dwp_file;
9640 }
9641
9642 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9643    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9644    or in the DWP file for the objfile, referenced by THIS_UNIT.
9645    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9646    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9647
9648    This is called, for example, when wanting to read a variable with a
9649    complex location.  Therefore we don't want to do file i/o for every call.
9650    Therefore we don't want to look for a DWO file on every call.
9651    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9652    then we check if we've already seen DWO_NAME, and only THEN do we check
9653    for a DWO file.
9654
9655    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9656    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9657
9658 static struct dwo_unit *
9659 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9660                  const char *dwo_name, const char *comp_dir,
9661                  ULONGEST signature, int is_debug_types)
9662 {
9663   struct objfile *objfile = dwarf2_per_objfile->objfile;
9664   const char *kind = is_debug_types ? "TU" : "CU";
9665   void **dwo_file_slot;
9666   struct dwo_file *dwo_file;
9667   struct dwp_file *dwp_file;
9668
9669   /* First see if there's a DWP file.
9670      If we have a DWP file but didn't find the DWO inside it, don't
9671      look for the original DWO file.  It makes gdb behave differently
9672      depending on whether one is debugging in the build tree.  */
9673
9674   dwp_file = get_dwp_file ();
9675   if (dwp_file != NULL)
9676     {
9677       const struct dwp_hash_table *dwp_htab =
9678         is_debug_types ? dwp_file->tus : dwp_file->cus;
9679
9680       if (dwp_htab != NULL)
9681         {
9682           struct dwo_unit *dwo_cutu =
9683             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9684                                signature, is_debug_types);
9685
9686           if (dwo_cutu != NULL)
9687             {
9688               if (dwarf2_read_debug)
9689                 {
9690                   fprintf_unfiltered (gdb_stdlog,
9691                                       "Virtual DWO %s %s found: @%s\n",
9692                                       kind, hex_string (signature),
9693                                       host_address_to_string (dwo_cutu));
9694                 }
9695               return dwo_cutu;
9696             }
9697         }
9698     }
9699   else
9700     {
9701       /* No DWP file, look for the DWO file.  */
9702
9703       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9704       if (*dwo_file_slot == NULL)
9705         {
9706           /* Read in the file and build a table of the CUs/TUs it contains.  */
9707           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9708         }
9709       /* NOTE: This will be NULL if unable to open the file.  */
9710       dwo_file = *dwo_file_slot;
9711
9712       if (dwo_file != NULL)
9713         {
9714           struct dwo_unit *dwo_cutu = NULL;
9715
9716           if (is_debug_types && dwo_file->tus)
9717             {
9718               struct dwo_unit find_dwo_cutu;
9719
9720               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9721               find_dwo_cutu.signature = signature;
9722               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
9723             }
9724           else if (!is_debug_types && dwo_file->cu)
9725             {
9726               if (signature == dwo_file->cu->signature)
9727                 dwo_cutu = dwo_file->cu;
9728             }
9729
9730           if (dwo_cutu != NULL)
9731             {
9732               if (dwarf2_read_debug)
9733                 {
9734                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9735                                       kind, dwo_name, hex_string (signature),
9736                                       host_address_to_string (dwo_cutu));
9737                 }
9738               return dwo_cutu;
9739             }
9740         }
9741     }
9742
9743   /* We didn't find it.  This could mean a dwo_id mismatch, or
9744      someone deleted the DWO/DWP file, or the search path isn't set up
9745      correctly to find the file.  */
9746
9747   if (dwarf2_read_debug)
9748     {
9749       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9750                           kind, dwo_name, hex_string (signature));
9751     }
9752
9753   complaint (&symfile_complaints,
9754              _("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
9755                " [in module %s]"),
9756              kind, dwo_name, hex_string (signature),
9757              this_unit->is_debug_types ? "TU" : "CU",
9758              this_unit->offset.sect_off, objfile->name);
9759   return NULL;
9760 }
9761
9762 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9763    See lookup_dwo_cutu_unit for details.  */
9764
9765 static struct dwo_unit *
9766 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9767                       const char *dwo_name, const char *comp_dir,
9768                       ULONGEST signature)
9769 {
9770   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9771 }
9772
9773 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9774    See lookup_dwo_cutu_unit for details.  */
9775
9776 static struct dwo_unit *
9777 lookup_dwo_type_unit (struct signatured_type *this_tu,
9778                       const char *dwo_name, const char *comp_dir)
9779 {
9780   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9781 }
9782
9783 /* Free all resources associated with DWO_FILE.
9784    Close the DWO file and munmap the sections.
9785    All memory should be on the objfile obstack.  */
9786
9787 static void
9788 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9789 {
9790   int ix;
9791   struct dwarf2_section_info *section;
9792
9793   /* Note: dbfd is NULL for virtual DWO files.  */
9794   gdb_bfd_unref (dwo_file->dbfd);
9795
9796   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9797 }
9798
9799 /* Wrapper for free_dwo_file for use in cleanups.  */
9800
9801 static void
9802 free_dwo_file_cleanup (void *arg)
9803 {
9804   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9805   struct objfile *objfile = dwarf2_per_objfile->objfile;
9806
9807   free_dwo_file (dwo_file, objfile);
9808 }
9809
9810 /* Traversal function for free_dwo_files.  */
9811
9812 static int
9813 free_dwo_file_from_slot (void **slot, void *info)
9814 {
9815   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9816   struct objfile *objfile = (struct objfile *) info;
9817
9818   free_dwo_file (dwo_file, objfile);
9819
9820   return 1;
9821 }
9822
9823 /* Free all resources associated with DWO_FILES.  */
9824
9825 static void
9826 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9827 {
9828   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9829 }
9830 \f
9831 /* Read in various DIEs.  */
9832
9833 /* qsort helper for inherit_abstract_dies.  */
9834
9835 static int
9836 unsigned_int_compar (const void *ap, const void *bp)
9837 {
9838   unsigned int a = *(unsigned int *) ap;
9839   unsigned int b = *(unsigned int *) bp;
9840
9841   return (a > b) - (b > a);
9842 }
9843
9844 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9845    Inherit only the children of the DW_AT_abstract_origin DIE not being
9846    already referenced by DW_AT_abstract_origin from the children of the
9847    current DIE.  */
9848
9849 static void
9850 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9851 {
9852   struct die_info *child_die;
9853   unsigned die_children_count;
9854   /* CU offsets which were referenced by children of the current DIE.  */
9855   sect_offset *offsets;
9856   sect_offset *offsets_end, *offsetp;
9857   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9858   struct die_info *origin_die;
9859   /* Iterator of the ORIGIN_DIE children.  */
9860   struct die_info *origin_child_die;
9861   struct cleanup *cleanups;
9862   struct attribute *attr;
9863   struct dwarf2_cu *origin_cu;
9864   struct pending **origin_previous_list_in_scope;
9865
9866   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9867   if (!attr)
9868     return;
9869
9870   /* Note that following die references may follow to a die in a
9871      different cu.  */
9872
9873   origin_cu = cu;
9874   origin_die = follow_die_ref (die, attr, &origin_cu);
9875
9876   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9877      symbols in.  */
9878   origin_previous_list_in_scope = origin_cu->list_in_scope;
9879   origin_cu->list_in_scope = cu->list_in_scope;
9880
9881   if (die->tag != origin_die->tag
9882       && !(die->tag == DW_TAG_inlined_subroutine
9883            && origin_die->tag == DW_TAG_subprogram))
9884     complaint (&symfile_complaints,
9885                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9886                die->offset.sect_off, origin_die->offset.sect_off);
9887
9888   child_die = die->child;
9889   die_children_count = 0;
9890   while (child_die && child_die->tag)
9891     {
9892       child_die = sibling_die (child_die);
9893       die_children_count++;
9894     }
9895   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9896   cleanups = make_cleanup (xfree, offsets);
9897
9898   offsets_end = offsets;
9899   child_die = die->child;
9900   while (child_die && child_die->tag)
9901     {
9902       /* For each CHILD_DIE, find the corresponding child of
9903          ORIGIN_DIE.  If there is more than one layer of
9904          DW_AT_abstract_origin, follow them all; there shouldn't be,
9905          but GCC versions at least through 4.4 generate this (GCC PR
9906          40573).  */
9907       struct die_info *child_origin_die = child_die;
9908       struct dwarf2_cu *child_origin_cu = cu;
9909
9910       while (1)
9911         {
9912           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9913                               child_origin_cu);
9914           if (attr == NULL)
9915             break;
9916           child_origin_die = follow_die_ref (child_origin_die, attr,
9917                                              &child_origin_cu);
9918         }
9919
9920       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9921          counterpart may exist.  */
9922       if (child_origin_die != child_die)
9923         {
9924           if (child_die->tag != child_origin_die->tag
9925               && !(child_die->tag == DW_TAG_inlined_subroutine
9926                    && child_origin_die->tag == DW_TAG_subprogram))
9927             complaint (&symfile_complaints,
9928                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9929                          "different tags"), child_die->offset.sect_off,
9930                        child_origin_die->offset.sect_off);
9931           if (child_origin_die->parent != origin_die)
9932             complaint (&symfile_complaints,
9933                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9934                          "different parents"), child_die->offset.sect_off,
9935                        child_origin_die->offset.sect_off);
9936           else
9937             *offsets_end++ = child_origin_die->offset;
9938         }
9939       child_die = sibling_die (child_die);
9940     }
9941   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9942          unsigned_int_compar);
9943   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9944     if (offsetp[-1].sect_off == offsetp->sect_off)
9945       complaint (&symfile_complaints,
9946                  _("Multiple children of DIE 0x%x refer "
9947                    "to DIE 0x%x as their abstract origin"),
9948                  die->offset.sect_off, offsetp->sect_off);
9949
9950   offsetp = offsets;
9951   origin_child_die = origin_die->child;
9952   while (origin_child_die && origin_child_die->tag)
9953     {
9954       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9955       while (offsetp < offsets_end
9956              && offsetp->sect_off < origin_child_die->offset.sect_off)
9957         offsetp++;
9958       if (offsetp >= offsets_end
9959           || offsetp->sect_off > origin_child_die->offset.sect_off)
9960         {
9961           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9962           process_die (origin_child_die, origin_cu);
9963         }
9964       origin_child_die = sibling_die (origin_child_die);
9965     }
9966   origin_cu->list_in_scope = origin_previous_list_in_scope;
9967
9968   do_cleanups (cleanups);
9969 }
9970
9971 static void
9972 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9973 {
9974   struct objfile *objfile = cu->objfile;
9975   struct context_stack *new;
9976   CORE_ADDR lowpc;
9977   CORE_ADDR highpc;
9978   struct die_info *child_die;
9979   struct attribute *attr, *call_line, *call_file;
9980   const char *name;
9981   CORE_ADDR baseaddr;
9982   struct block *block;
9983   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9984   VEC (symbolp) *template_args = NULL;
9985   struct template_symbol *templ_func = NULL;
9986
9987   if (inlined_func)
9988     {
9989       /* If we do not have call site information, we can't show the
9990          caller of this inlined function.  That's too confusing, so
9991          only use the scope for local variables.  */
9992       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9993       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9994       if (call_line == NULL || call_file == NULL)
9995         {
9996           read_lexical_block_scope (die, cu);
9997           return;
9998         }
9999     }
10000
10001   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10002
10003   name = dwarf2_name (die, cu);
10004
10005   /* Ignore functions with missing or empty names.  These are actually
10006      illegal according to the DWARF standard.  */
10007   if (name == NULL)
10008     {
10009       complaint (&symfile_complaints,
10010                  _("missing name for subprogram DIE at %d"),
10011                  die->offset.sect_off);
10012       return;
10013     }
10014
10015   /* Ignore functions with missing or invalid low and high pc attributes.  */
10016   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10017     {
10018       attr = dwarf2_attr (die, DW_AT_external, cu);
10019       if (!attr || !DW_UNSND (attr))
10020         complaint (&symfile_complaints,
10021                    _("cannot get low and high bounds "
10022                      "for subprogram DIE at %d"),
10023                    die->offset.sect_off);
10024       return;
10025     }
10026
10027   lowpc += baseaddr;
10028   highpc += baseaddr;
10029
10030   /* If we have any template arguments, then we must allocate a
10031      different sort of symbol.  */
10032   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10033     {
10034       if (child_die->tag == DW_TAG_template_type_param
10035           || child_die->tag == DW_TAG_template_value_param)
10036         {
10037           templ_func = allocate_template_symbol (objfile);
10038           templ_func->base.is_cplus_template_function = 1;
10039           break;
10040         }
10041     }
10042
10043   new = push_context (0, lowpc);
10044   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10045                                (struct symbol *) templ_func);
10046
10047   /* If there is a location expression for DW_AT_frame_base, record
10048      it.  */
10049   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10050   if (attr)
10051     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10052
10053   cu->list_in_scope = &local_symbols;
10054
10055   if (die->child != NULL)
10056     {
10057       child_die = die->child;
10058       while (child_die && child_die->tag)
10059         {
10060           if (child_die->tag == DW_TAG_template_type_param
10061               || child_die->tag == DW_TAG_template_value_param)
10062             {
10063               struct symbol *arg = new_symbol (child_die, NULL, cu);
10064
10065               if (arg != NULL)
10066                 VEC_safe_push (symbolp, template_args, arg);
10067             }
10068           else
10069             process_die (child_die, cu);
10070           child_die = sibling_die (child_die);
10071         }
10072     }
10073
10074   inherit_abstract_dies (die, cu);
10075
10076   /* If we have a DW_AT_specification, we might need to import using
10077      directives from the context of the specification DIE.  See the
10078      comment in determine_prefix.  */
10079   if (cu->language == language_cplus
10080       && dwarf2_attr (die, DW_AT_specification, cu))
10081     {
10082       struct dwarf2_cu *spec_cu = cu;
10083       struct die_info *spec_die = die_specification (die, &spec_cu);
10084
10085       while (spec_die)
10086         {
10087           child_die = spec_die->child;
10088           while (child_die && child_die->tag)
10089             {
10090               if (child_die->tag == DW_TAG_imported_module)
10091                 process_die (child_die, spec_cu);
10092               child_die = sibling_die (child_die);
10093             }
10094
10095           /* In some cases, GCC generates specification DIEs that
10096              themselves contain DW_AT_specification attributes.  */
10097           spec_die = die_specification (spec_die, &spec_cu);
10098         }
10099     }
10100
10101   new = pop_context ();
10102   /* Make a block for the local symbols within.  */
10103   block = finish_block (new->name, &local_symbols, new->old_blocks,
10104                         lowpc, highpc, objfile);
10105
10106   /* For C++, set the block's scope.  */
10107   if ((cu->language == language_cplus || cu->language == language_fortran)
10108       && cu->processing_has_namespace_info)
10109     block_set_scope (block, determine_prefix (die, cu),
10110                      &objfile->objfile_obstack);
10111
10112   /* If we have address ranges, record them.  */
10113   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10114
10115   /* Attach template arguments to function.  */
10116   if (! VEC_empty (symbolp, template_args))
10117     {
10118       gdb_assert (templ_func != NULL);
10119
10120       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10121       templ_func->template_arguments
10122         = obstack_alloc (&objfile->objfile_obstack,
10123                          (templ_func->n_template_arguments
10124                           * sizeof (struct symbol *)));
10125       memcpy (templ_func->template_arguments,
10126               VEC_address (symbolp, template_args),
10127               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10128       VEC_free (symbolp, template_args);
10129     }
10130
10131   /* In C++, we can have functions nested inside functions (e.g., when
10132      a function declares a class that has methods).  This means that
10133      when we finish processing a function scope, we may need to go
10134      back to building a containing block's symbol lists.  */
10135   local_symbols = new->locals;
10136   using_directives = new->using_directives;
10137
10138   /* If we've finished processing a top-level function, subsequent
10139      symbols go in the file symbol list.  */
10140   if (outermost_context_p ())
10141     cu->list_in_scope = &file_symbols;
10142 }
10143
10144 /* Process all the DIES contained within a lexical block scope.  Start
10145    a new scope, process the dies, and then close the scope.  */
10146
10147 static void
10148 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
10149 {
10150   struct objfile *objfile = cu->objfile;
10151   struct context_stack *new;
10152   CORE_ADDR lowpc, highpc;
10153   struct die_info *child_die;
10154   CORE_ADDR baseaddr;
10155
10156   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10157
10158   /* Ignore blocks with missing or invalid low and high pc attributes.  */
10159   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
10160      as multiple lexical blocks?  Handling children in a sane way would
10161      be nasty.  Might be easier to properly extend generic blocks to
10162      describe ranges.  */
10163   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10164     return;
10165   lowpc += baseaddr;
10166   highpc += baseaddr;
10167
10168   push_context (0, lowpc);
10169   if (die->child != NULL)
10170     {
10171       child_die = die->child;
10172       while (child_die && child_die->tag)
10173         {
10174           process_die (child_die, cu);
10175           child_die = sibling_die (child_die);
10176         }
10177     }
10178   new = pop_context ();
10179
10180   if (local_symbols != NULL || using_directives != NULL)
10181     {
10182       struct block *block
10183         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
10184                         highpc, objfile);
10185
10186       /* Note that recording ranges after traversing children, as we
10187          do here, means that recording a parent's ranges entails
10188          walking across all its children's ranges as they appear in
10189          the address map, which is quadratic behavior.
10190
10191          It would be nicer to record the parent's ranges before
10192          traversing its children, simply overriding whatever you find
10193          there.  But since we don't even decide whether to create a
10194          block until after we've traversed its children, that's hard
10195          to do.  */
10196       dwarf2_record_block_ranges (die, block, baseaddr, cu);
10197     }
10198   local_symbols = new->locals;
10199   using_directives = new->using_directives;
10200 }
10201
10202 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
10203
10204 static void
10205 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
10206 {
10207   struct objfile *objfile = cu->objfile;
10208   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10209   CORE_ADDR pc, baseaddr;
10210   struct attribute *attr;
10211   struct call_site *call_site, call_site_local;
10212   void **slot;
10213   int nparams;
10214   struct die_info *child_die;
10215
10216   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10217
10218   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10219   if (!attr)
10220     {
10221       complaint (&symfile_complaints,
10222                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
10223                    "DIE 0x%x [in module %s]"),
10224                  die->offset.sect_off, objfile->name);
10225       return;
10226     }
10227   pc = DW_ADDR (attr) + baseaddr;
10228
10229   if (cu->call_site_htab == NULL)
10230     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
10231                                                NULL, &objfile->objfile_obstack,
10232                                                hashtab_obstack_allocate, NULL);
10233   call_site_local.pc = pc;
10234   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
10235   if (*slot != NULL)
10236     {
10237       complaint (&symfile_complaints,
10238                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
10239                    "DIE 0x%x [in module %s]"),
10240                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
10241       return;
10242     }
10243
10244   /* Count parameters at the caller.  */
10245
10246   nparams = 0;
10247   for (child_die = die->child; child_die && child_die->tag;
10248        child_die = sibling_die (child_die))
10249     {
10250       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10251         {
10252           complaint (&symfile_complaints,
10253                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
10254                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10255                      child_die->tag, child_die->offset.sect_off, objfile->name);
10256           continue;
10257         }
10258
10259       nparams++;
10260     }
10261
10262   call_site = obstack_alloc (&objfile->objfile_obstack,
10263                              (sizeof (*call_site)
10264                               + (sizeof (*call_site->parameter)
10265                                  * (nparams - 1))));
10266   *slot = call_site;
10267   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
10268   call_site->pc = pc;
10269
10270   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
10271     {
10272       struct die_info *func_die;
10273
10274       /* Skip also over DW_TAG_inlined_subroutine.  */
10275       for (func_die = die->parent;
10276            func_die && func_die->tag != DW_TAG_subprogram
10277            && func_die->tag != DW_TAG_subroutine_type;
10278            func_die = func_die->parent);
10279
10280       /* DW_AT_GNU_all_call_sites is a superset
10281          of DW_AT_GNU_all_tail_call_sites.  */
10282       if (func_die
10283           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
10284           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
10285         {
10286           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
10287              not complete.  But keep CALL_SITE for look ups via call_site_htab,
10288              both the initial caller containing the real return address PC and
10289              the final callee containing the current PC of a chain of tail
10290              calls do not need to have the tail call list complete.  But any
10291              function candidate for a virtual tail call frame searched via
10292              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
10293              determined unambiguously.  */
10294         }
10295       else
10296         {
10297           struct type *func_type = NULL;
10298
10299           if (func_die)
10300             func_type = get_die_type (func_die, cu);
10301           if (func_type != NULL)
10302             {
10303               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
10304
10305               /* Enlist this call site to the function.  */
10306               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
10307               TYPE_TAIL_CALL_LIST (func_type) = call_site;
10308             }
10309           else
10310             complaint (&symfile_complaints,
10311                        _("Cannot find function owning DW_TAG_GNU_call_site "
10312                          "DIE 0x%x [in module %s]"),
10313                        die->offset.sect_off, objfile->name);
10314         }
10315     }
10316
10317   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
10318   if (attr == NULL)
10319     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10320   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
10321   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
10322     /* Keep NULL DWARF_BLOCK.  */;
10323   else if (attr_form_is_block (attr))
10324     {
10325       struct dwarf2_locexpr_baton *dlbaton;
10326
10327       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
10328       dlbaton->data = DW_BLOCK (attr)->data;
10329       dlbaton->size = DW_BLOCK (attr)->size;
10330       dlbaton->per_cu = cu->per_cu;
10331
10332       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
10333     }
10334   else if (is_ref_attr (attr))
10335     {
10336       struct dwarf2_cu *target_cu = cu;
10337       struct die_info *target_die;
10338
10339       target_die = follow_die_ref (die, attr, &target_cu);
10340       gdb_assert (target_cu->objfile == objfile);
10341       if (die_is_declaration (target_die, target_cu))
10342         {
10343           const char *target_physname = NULL;
10344           struct attribute *target_attr;
10345
10346           /* Prefer the mangled name; otherwise compute the demangled one.  */
10347           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
10348           if (target_attr == NULL)
10349             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
10350                                        target_cu);
10351           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
10352             target_physname = DW_STRING (target_attr);
10353           else
10354             target_physname = dwarf2_physname (NULL, target_die, target_cu);
10355           if (target_physname == NULL)
10356             complaint (&symfile_complaints,
10357                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10358                          "physname, for referencing DIE 0x%x [in module %s]"),
10359                        die->offset.sect_off, objfile->name);
10360           else
10361             SET_FIELD_PHYSNAME (call_site->target, target_physname);
10362         }
10363       else
10364         {
10365           CORE_ADDR lowpc;
10366
10367           /* DW_AT_entry_pc should be preferred.  */
10368           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
10369             complaint (&symfile_complaints,
10370                        _("DW_AT_GNU_call_site_target target DIE has invalid "
10371                          "low pc, for referencing DIE 0x%x [in module %s]"),
10372                        die->offset.sect_off, objfile->name);
10373           else
10374             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
10375         }
10376     }
10377   else
10378     complaint (&symfile_complaints,
10379                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
10380                  "block nor reference, for DIE 0x%x [in module %s]"),
10381                die->offset.sect_off, objfile->name);
10382
10383   call_site->per_cu = cu->per_cu;
10384
10385   for (child_die = die->child;
10386        child_die && child_die->tag;
10387        child_die = sibling_die (child_die))
10388     {
10389       struct call_site_parameter *parameter;
10390       struct attribute *loc, *origin;
10391
10392       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
10393         {
10394           /* Already printed the complaint above.  */
10395           continue;
10396         }
10397
10398       gdb_assert (call_site->parameter_count < nparams);
10399       parameter = &call_site->parameter[call_site->parameter_count];
10400
10401       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10402          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10403          register is contained in DW_AT_GNU_call_site_value.  */
10404
10405       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10406       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10407       if (loc == NULL && origin != NULL && is_ref_attr (origin))
10408         {
10409           sect_offset offset;
10410
10411           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10412           offset = dwarf2_get_ref_die_offset (origin);
10413           if (!offset_in_cu_p (&cu->header, offset))
10414             {
10415               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10416                  binding can be done only inside one CU.  Such referenced DIE
10417                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10418               complaint (&symfile_complaints,
10419                          _("DW_AT_abstract_origin offset is not in CU for "
10420                            "DW_TAG_GNU_call_site child DIE 0x%x "
10421                            "[in module %s]"),
10422                          child_die->offset.sect_off, objfile->name);
10423               continue;
10424             }
10425           parameter->u.param_offset.cu_off = (offset.sect_off
10426                                               - cu->header.offset.sect_off);
10427         }
10428       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10429         {
10430           complaint (&symfile_complaints,
10431                      _("No DW_FORM_block* DW_AT_location for "
10432                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10433                      child_die->offset.sect_off, objfile->name);
10434           continue;
10435         }
10436       else
10437         {
10438           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10439             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10440           if (parameter->u.dwarf_reg != -1)
10441             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10442           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10443                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10444                                              &parameter->u.fb_offset))
10445             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10446           else
10447             {
10448               complaint (&symfile_complaints,
10449                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10450                            "for DW_FORM_block* DW_AT_location is supported for "
10451                            "DW_TAG_GNU_call_site child DIE 0x%x "
10452                            "[in module %s]"),
10453                          child_die->offset.sect_off, objfile->name);
10454               continue;
10455             }
10456         }
10457
10458       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10459       if (!attr_form_is_block (attr))
10460         {
10461           complaint (&symfile_complaints,
10462                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10463                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10464                      child_die->offset.sect_off, objfile->name);
10465           continue;
10466         }
10467       parameter->value = DW_BLOCK (attr)->data;
10468       parameter->value_size = DW_BLOCK (attr)->size;
10469
10470       /* Parameters are not pre-cleared by memset above.  */
10471       parameter->data_value = NULL;
10472       parameter->data_value_size = 0;
10473       call_site->parameter_count++;
10474
10475       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10476       if (attr)
10477         {
10478           if (!attr_form_is_block (attr))
10479             complaint (&symfile_complaints,
10480                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10481                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10482                        child_die->offset.sect_off, objfile->name);
10483           else
10484             {
10485               parameter->data_value = DW_BLOCK (attr)->data;
10486               parameter->data_value_size = DW_BLOCK (attr)->size;
10487             }
10488         }
10489     }
10490 }
10491
10492 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10493    Return 1 if the attributes are present and valid, otherwise, return 0.
10494    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10495
10496 static int
10497 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10498                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10499                     struct partial_symtab *ranges_pst)
10500 {
10501   struct objfile *objfile = cu->objfile;
10502   struct comp_unit_head *cu_header = &cu->header;
10503   bfd *obfd = objfile->obfd;
10504   unsigned int addr_size = cu_header->addr_size;
10505   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10506   /* Base address selection entry.  */
10507   CORE_ADDR base;
10508   int found_base;
10509   unsigned int dummy;
10510   const gdb_byte *buffer;
10511   CORE_ADDR marker;
10512   int low_set;
10513   CORE_ADDR low = 0;
10514   CORE_ADDR high = 0;
10515   CORE_ADDR baseaddr;
10516
10517   found_base = cu->base_known;
10518   base = cu->base_address;
10519
10520   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10521   if (offset >= dwarf2_per_objfile->ranges.size)
10522     {
10523       complaint (&symfile_complaints,
10524                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10525                  offset);
10526       return 0;
10527     }
10528   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10529
10530   /* Read in the largest possible address.  */
10531   marker = read_address (obfd, buffer, cu, &dummy);
10532   if ((marker & mask) == mask)
10533     {
10534       /* If we found the largest possible address, then
10535          read the base address.  */
10536       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10537       buffer += 2 * addr_size;
10538       offset += 2 * addr_size;
10539       found_base = 1;
10540     }
10541
10542   low_set = 0;
10543
10544   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10545
10546   while (1)
10547     {
10548       CORE_ADDR range_beginning, range_end;
10549
10550       range_beginning = read_address (obfd, buffer, cu, &dummy);
10551       buffer += addr_size;
10552       range_end = read_address (obfd, buffer, cu, &dummy);
10553       buffer += addr_size;
10554       offset += 2 * addr_size;
10555
10556       /* An end of list marker is a pair of zero addresses.  */
10557       if (range_beginning == 0 && range_end == 0)
10558         /* Found the end of list entry.  */
10559         break;
10560
10561       /* Each base address selection entry is a pair of 2 values.
10562          The first is the largest possible address, the second is
10563          the base address.  Check for a base address here.  */
10564       if ((range_beginning & mask) == mask)
10565         {
10566           /* If we found the largest possible address, then
10567              read the base address.  */
10568           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10569           found_base = 1;
10570           continue;
10571         }
10572
10573       if (!found_base)
10574         {
10575           /* We have no valid base address for the ranges
10576              data.  */
10577           complaint (&symfile_complaints,
10578                      _("Invalid .debug_ranges data (no base address)"));
10579           return 0;
10580         }
10581
10582       if (range_beginning > range_end)
10583         {
10584           /* Inverted range entries are invalid.  */
10585           complaint (&symfile_complaints,
10586                      _("Invalid .debug_ranges data (inverted range)"));
10587           return 0;
10588         }
10589
10590       /* Empty range entries have no effect.  */
10591       if (range_beginning == range_end)
10592         continue;
10593
10594       range_beginning += base;
10595       range_end += base;
10596
10597       /* A not-uncommon case of bad debug info.
10598          Don't pollute the addrmap with bad data.  */
10599       if (range_beginning + baseaddr == 0
10600           && !dwarf2_per_objfile->has_section_at_zero)
10601         {
10602           complaint (&symfile_complaints,
10603                      _(".debug_ranges entry has start address of zero"
10604                        " [in module %s]"), objfile->name);
10605           continue;
10606         }
10607
10608       if (ranges_pst != NULL)
10609         addrmap_set_empty (objfile->psymtabs_addrmap,
10610                            range_beginning + baseaddr,
10611                            range_end - 1 + baseaddr,
10612                            ranges_pst);
10613
10614       /* FIXME: This is recording everything as a low-high
10615          segment of consecutive addresses.  We should have a
10616          data structure for discontiguous block ranges
10617          instead.  */
10618       if (! low_set)
10619         {
10620           low = range_beginning;
10621           high = range_end;
10622           low_set = 1;
10623         }
10624       else
10625         {
10626           if (range_beginning < low)
10627             low = range_beginning;
10628           if (range_end > high)
10629             high = range_end;
10630         }
10631     }
10632
10633   if (! low_set)
10634     /* If the first entry is an end-of-list marker, the range
10635        describes an empty scope, i.e. no instructions.  */
10636     return 0;
10637
10638   if (low_return)
10639     *low_return = low;
10640   if (high_return)
10641     *high_return = high;
10642   return 1;
10643 }
10644
10645 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10646    are present and valid, otherwise, return 0.  Return -1 if the range is
10647    discontinuous, i.e. derived from DW_AT_ranges information.  */
10648
10649 static int
10650 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10651                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10652                       struct partial_symtab *pst)
10653 {
10654   struct attribute *attr;
10655   struct attribute *attr_high;
10656   CORE_ADDR low = 0;
10657   CORE_ADDR high = 0;
10658   int ret = 0;
10659
10660   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10661   if (attr_high)
10662     {
10663       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10664       if (attr)
10665         {
10666           low = DW_ADDR (attr);
10667           if (attr_high->form == DW_FORM_addr
10668               || attr_high->form == DW_FORM_GNU_addr_index)
10669             high = DW_ADDR (attr_high);
10670           else
10671             high = low + DW_UNSND (attr_high);
10672         }
10673       else
10674         /* Found high w/o low attribute.  */
10675         return 0;
10676
10677       /* Found consecutive range of addresses.  */
10678       ret = 1;
10679     }
10680   else
10681     {
10682       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10683       if (attr != NULL)
10684         {
10685           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10686              We take advantage of the fact that DW_AT_ranges does not appear
10687              in DW_TAG_compile_unit of DWO files.  */
10688           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10689           unsigned int ranges_offset = (DW_UNSND (attr)
10690                                         + (need_ranges_base
10691                                            ? cu->ranges_base
10692                                            : 0));
10693
10694           /* Value of the DW_AT_ranges attribute is the offset in the
10695              .debug_ranges section.  */
10696           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10697             return 0;
10698           /* Found discontinuous range of addresses.  */
10699           ret = -1;
10700         }
10701     }
10702
10703   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10704   if (high <= low)
10705     return 0;
10706
10707   /* When using the GNU linker, .gnu.linkonce. sections are used to
10708      eliminate duplicate copies of functions and vtables and such.
10709      The linker will arbitrarily choose one and discard the others.
10710      The AT_*_pc values for such functions refer to local labels in
10711      these sections.  If the section from that file was discarded, the
10712      labels are not in the output, so the relocs get a value of 0.
10713      If this is a discarded function, mark the pc bounds as invalid,
10714      so that GDB will ignore it.  */
10715   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10716     return 0;
10717
10718   *lowpc = low;
10719   if (highpc)
10720     *highpc = high;
10721   return ret;
10722 }
10723
10724 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10725    its low and high PC addresses.  Do nothing if these addresses could not
10726    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10727    and HIGHPC to the high address if greater than HIGHPC.  */
10728
10729 static void
10730 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10731                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10732                                  struct dwarf2_cu *cu)
10733 {
10734   CORE_ADDR low, high;
10735   struct die_info *child = die->child;
10736
10737   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10738     {
10739       *lowpc = min (*lowpc, low);
10740       *highpc = max (*highpc, high);
10741     }
10742
10743   /* If the language does not allow nested subprograms (either inside
10744      subprograms or lexical blocks), we're done.  */
10745   if (cu->language != language_ada)
10746     return;
10747
10748   /* Check all the children of the given DIE.  If it contains nested
10749      subprograms, then check their pc bounds.  Likewise, we need to
10750      check lexical blocks as well, as they may also contain subprogram
10751      definitions.  */
10752   while (child && child->tag)
10753     {
10754       if (child->tag == DW_TAG_subprogram
10755           || child->tag == DW_TAG_lexical_block)
10756         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10757       child = sibling_die (child);
10758     }
10759 }
10760
10761 /* Get the low and high pc's represented by the scope DIE, and store
10762    them in *LOWPC and *HIGHPC.  If the correct values can't be
10763    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10764
10765 static void
10766 get_scope_pc_bounds (struct die_info *die,
10767                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10768                      struct dwarf2_cu *cu)
10769 {
10770   CORE_ADDR best_low = (CORE_ADDR) -1;
10771   CORE_ADDR best_high = (CORE_ADDR) 0;
10772   CORE_ADDR current_low, current_high;
10773
10774   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10775     {
10776       best_low = current_low;
10777       best_high = current_high;
10778     }
10779   else
10780     {
10781       struct die_info *child = die->child;
10782
10783       while (child && child->tag)
10784         {
10785           switch (child->tag) {
10786           case DW_TAG_subprogram:
10787             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10788             break;
10789           case DW_TAG_namespace:
10790           case DW_TAG_module:
10791             /* FIXME: carlton/2004-01-16: Should we do this for
10792                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10793                that current GCC's always emit the DIEs corresponding
10794                to definitions of methods of classes as children of a
10795                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10796                the DIEs giving the declarations, which could be
10797                anywhere).  But I don't see any reason why the
10798                standards says that they have to be there.  */
10799             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10800
10801             if (current_low != ((CORE_ADDR) -1))
10802               {
10803                 best_low = min (best_low, current_low);
10804                 best_high = max (best_high, current_high);
10805               }
10806             break;
10807           default:
10808             /* Ignore.  */
10809             break;
10810           }
10811
10812           child = sibling_die (child);
10813         }
10814     }
10815
10816   *lowpc = best_low;
10817   *highpc = best_high;
10818 }
10819
10820 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10821    in DIE.  */
10822
10823 static void
10824 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10825                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10826 {
10827   struct objfile *objfile = cu->objfile;
10828   struct attribute *attr;
10829   struct attribute *attr_high;
10830
10831   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10832   if (attr_high)
10833     {
10834       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10835       if (attr)
10836         {
10837           CORE_ADDR low = DW_ADDR (attr);
10838           CORE_ADDR high;
10839           if (attr_high->form == DW_FORM_addr
10840               || attr_high->form == DW_FORM_GNU_addr_index)
10841             high = DW_ADDR (attr_high);
10842           else
10843             high = low + DW_UNSND (attr_high);
10844
10845           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10846         }
10847     }
10848
10849   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10850   if (attr)
10851     {
10852       bfd *obfd = objfile->obfd;
10853       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10854          We take advantage of the fact that DW_AT_ranges does not appear
10855          in DW_TAG_compile_unit of DWO files.  */
10856       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10857
10858       /* The value of the DW_AT_ranges attribute is the offset of the
10859          address range list in the .debug_ranges section.  */
10860       unsigned long offset = (DW_UNSND (attr)
10861                               + (need_ranges_base ? cu->ranges_base : 0));
10862       const gdb_byte *buffer;
10863
10864       /* For some target architectures, but not others, the
10865          read_address function sign-extends the addresses it returns.
10866          To recognize base address selection entries, we need a
10867          mask.  */
10868       unsigned int addr_size = cu->header.addr_size;
10869       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10870
10871       /* The base address, to which the next pair is relative.  Note
10872          that this 'base' is a DWARF concept: most entries in a range
10873          list are relative, to reduce the number of relocs against the
10874          debugging information.  This is separate from this function's
10875          'baseaddr' argument, which GDB uses to relocate debugging
10876          information from a shared library based on the address at
10877          which the library was loaded.  */
10878       CORE_ADDR base = cu->base_address;
10879       int base_known = cu->base_known;
10880
10881       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10882       if (offset >= dwarf2_per_objfile->ranges.size)
10883         {
10884           complaint (&symfile_complaints,
10885                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10886                      offset);
10887           return;
10888         }
10889       buffer = dwarf2_per_objfile->ranges.buffer + offset;
10890
10891       for (;;)
10892         {
10893           unsigned int bytes_read;
10894           CORE_ADDR start, end;
10895
10896           start = read_address (obfd, buffer, cu, &bytes_read);
10897           buffer += bytes_read;
10898           end = read_address (obfd, buffer, cu, &bytes_read);
10899           buffer += bytes_read;
10900
10901           /* Did we find the end of the range list?  */
10902           if (start == 0 && end == 0)
10903             break;
10904
10905           /* Did we find a base address selection entry?  */
10906           else if ((start & base_select_mask) == base_select_mask)
10907             {
10908               base = end;
10909               base_known = 1;
10910             }
10911
10912           /* We found an ordinary address range.  */
10913           else
10914             {
10915               if (!base_known)
10916                 {
10917                   complaint (&symfile_complaints,
10918                              _("Invalid .debug_ranges data "
10919                                "(no base address)"));
10920                   return;
10921                 }
10922
10923               if (start > end)
10924                 {
10925                   /* Inverted range entries are invalid.  */
10926                   complaint (&symfile_complaints,
10927                              _("Invalid .debug_ranges data "
10928                                "(inverted range)"));
10929                   return;
10930                 }
10931
10932               /* Empty range entries have no effect.  */
10933               if (start == end)
10934                 continue;
10935
10936               start += base + baseaddr;
10937               end += base + baseaddr;
10938
10939               /* A not-uncommon case of bad debug info.
10940                  Don't pollute the addrmap with bad data.  */
10941               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10942                 {
10943                   complaint (&symfile_complaints,
10944                              _(".debug_ranges entry has start address of zero"
10945                                " [in module %s]"), objfile->name);
10946                   continue;
10947                 }
10948
10949               record_block_range (block, start, end - 1);
10950             }
10951         }
10952     }
10953 }
10954
10955 /* Check whether the producer field indicates either of GCC < 4.6, or the
10956    Intel C/C++ compiler, and cache the result in CU.  */
10957
10958 static void
10959 check_producer (struct dwarf2_cu *cu)
10960 {
10961   const char *cs;
10962   int major, minor, release;
10963
10964   if (cu->producer == NULL)
10965     {
10966       /* For unknown compilers expect their behavior is DWARF version
10967          compliant.
10968
10969          GCC started to support .debug_types sections by -gdwarf-4 since
10970          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10971          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10972          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10973          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10974     }
10975   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10976     {
10977       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10978
10979       cs = &cu->producer[strlen ("GNU ")];
10980       while (*cs && !isdigit (*cs))
10981         cs++;
10982       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10983         {
10984           /* Not recognized as GCC.  */
10985         }
10986       else
10987         {
10988           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10989           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10990         }
10991     }
10992   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10993     cu->producer_is_icc = 1;
10994   else
10995     {
10996       /* For other non-GCC compilers, expect their behavior is DWARF version
10997          compliant.  */
10998     }
10999
11000   cu->checked_producer = 1;
11001 }
11002
11003 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11004    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11005    during 4.6.0 experimental.  */
11006
11007 static int
11008 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11009 {
11010   if (!cu->checked_producer)
11011     check_producer (cu);
11012
11013   return cu->producer_is_gxx_lt_4_6;
11014 }
11015
11016 /* Return the default accessibility type if it is not overriden by
11017    DW_AT_accessibility.  */
11018
11019 static enum dwarf_access_attribute
11020 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11021 {
11022   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11023     {
11024       /* The default DWARF 2 accessibility for members is public, the default
11025          accessibility for inheritance is private.  */
11026
11027       if (die->tag != DW_TAG_inheritance)
11028         return DW_ACCESS_public;
11029       else
11030         return DW_ACCESS_private;
11031     }
11032   else
11033     {
11034       /* DWARF 3+ defines the default accessibility a different way.  The same
11035          rules apply now for DW_TAG_inheritance as for the members and it only
11036          depends on the container kind.  */
11037
11038       if (die->parent->tag == DW_TAG_class_type)
11039         return DW_ACCESS_private;
11040       else
11041         return DW_ACCESS_public;
11042     }
11043 }
11044
11045 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11046    offset.  If the attribute was not found return 0, otherwise return
11047    1.  If it was found but could not properly be handled, set *OFFSET
11048    to 0.  */
11049
11050 static int
11051 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11052                              LONGEST *offset)
11053 {
11054   struct attribute *attr;
11055
11056   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11057   if (attr != NULL)
11058     {
11059       *offset = 0;
11060
11061       /* Note that we do not check for a section offset first here.
11062          This is because DW_AT_data_member_location is new in DWARF 4,
11063          so if we see it, we can assume that a constant form is really
11064          a constant and not a section offset.  */
11065       if (attr_form_is_constant (attr))
11066         *offset = dwarf2_get_attr_constant_value (attr, 0);
11067       else if (attr_form_is_section_offset (attr))
11068         dwarf2_complex_location_expr_complaint ();
11069       else if (attr_form_is_block (attr))
11070         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11071       else
11072         dwarf2_complex_location_expr_complaint ();
11073
11074       return 1;
11075     }
11076
11077   return 0;
11078 }
11079
11080 /* Add an aggregate field to the field list.  */
11081
11082 static void
11083 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11084                   struct dwarf2_cu *cu)
11085 {
11086   struct objfile *objfile = cu->objfile;
11087   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11088   struct nextfield *new_field;
11089   struct attribute *attr;
11090   struct field *fp;
11091   const char *fieldname = "";
11092
11093   /* Allocate a new field list entry and link it in.  */
11094   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11095   make_cleanup (xfree, new_field);
11096   memset (new_field, 0, sizeof (struct nextfield));
11097
11098   if (die->tag == DW_TAG_inheritance)
11099     {
11100       new_field->next = fip->baseclasses;
11101       fip->baseclasses = new_field;
11102     }
11103   else
11104     {
11105       new_field->next = fip->fields;
11106       fip->fields = new_field;
11107     }
11108   fip->nfields++;
11109
11110   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11111   if (attr)
11112     new_field->accessibility = DW_UNSND (attr);
11113   else
11114     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11115   if (new_field->accessibility != DW_ACCESS_public)
11116     fip->non_public_fields = 1;
11117
11118   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11119   if (attr)
11120     new_field->virtuality = DW_UNSND (attr);
11121   else
11122     new_field->virtuality = DW_VIRTUALITY_none;
11123
11124   fp = &new_field->field;
11125
11126   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11127     {
11128       LONGEST offset;
11129
11130       /* Data member other than a C++ static data member.  */
11131
11132       /* Get type of field.  */
11133       fp->type = die_type (die, cu);
11134
11135       SET_FIELD_BITPOS (*fp, 0);
11136
11137       /* Get bit size of field (zero if none).  */
11138       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11139       if (attr)
11140         {
11141           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11142         }
11143       else
11144         {
11145           FIELD_BITSIZE (*fp) = 0;
11146         }
11147
11148       /* Get bit offset of field.  */
11149       if (handle_data_member_location (die, cu, &offset))
11150         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11151       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
11152       if (attr)
11153         {
11154           if (gdbarch_bits_big_endian (gdbarch))
11155             {
11156               /* For big endian bits, the DW_AT_bit_offset gives the
11157                  additional bit offset from the MSB of the containing
11158                  anonymous object to the MSB of the field.  We don't
11159                  have to do anything special since we don't need to
11160                  know the size of the anonymous object.  */
11161               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
11162             }
11163           else
11164             {
11165               /* For little endian bits, compute the bit offset to the
11166                  MSB of the anonymous object, subtract off the number of
11167                  bits from the MSB of the field to the MSB of the
11168                  object, and then subtract off the number of bits of
11169                  the field itself.  The result is the bit offset of
11170                  the LSB of the field.  */
11171               int anonymous_size;
11172               int bit_offset = DW_UNSND (attr);
11173
11174               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11175               if (attr)
11176                 {
11177                   /* The size of the anonymous object containing
11178                      the bit field is explicit, so use the
11179                      indicated size (in bytes).  */
11180                   anonymous_size = DW_UNSND (attr);
11181                 }
11182               else
11183                 {
11184                   /* The size of the anonymous object containing
11185                      the bit field must be inferred from the type
11186                      attribute of the data member containing the
11187                      bit field.  */
11188                   anonymous_size = TYPE_LENGTH (fp->type);
11189                 }
11190               SET_FIELD_BITPOS (*fp,
11191                                 (FIELD_BITPOS (*fp)
11192                                  + anonymous_size * bits_per_byte
11193                                  - bit_offset - FIELD_BITSIZE (*fp)));
11194             }
11195         }
11196
11197       /* Get name of field.  */
11198       fieldname = dwarf2_name (die, cu);
11199       if (fieldname == NULL)
11200         fieldname = "";
11201
11202       /* The name is already allocated along with this objfile, so we don't
11203          need to duplicate it for the type.  */
11204       fp->name = fieldname;
11205
11206       /* Change accessibility for artificial fields (e.g. virtual table
11207          pointer or virtual base class pointer) to private.  */
11208       if (dwarf2_attr (die, DW_AT_artificial, cu))
11209         {
11210           FIELD_ARTIFICIAL (*fp) = 1;
11211           new_field->accessibility = DW_ACCESS_private;
11212           fip->non_public_fields = 1;
11213         }
11214     }
11215   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
11216     {
11217       /* C++ static member.  */
11218
11219       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
11220          is a declaration, but all versions of G++ as of this writing
11221          (so through at least 3.2.1) incorrectly generate
11222          DW_TAG_variable tags.  */
11223
11224       const char *physname;
11225
11226       /* Get name of field.  */
11227       fieldname = dwarf2_name (die, cu);
11228       if (fieldname == NULL)
11229         return;
11230
11231       attr = dwarf2_attr (die, DW_AT_const_value, cu);
11232       if (attr
11233           /* Only create a symbol if this is an external value.
11234              new_symbol checks this and puts the value in the global symbol
11235              table, which we want.  If it is not external, new_symbol
11236              will try to put the value in cu->list_in_scope which is wrong.  */
11237           && dwarf2_flag_true_p (die, DW_AT_external, cu))
11238         {
11239           /* A static const member, not much different than an enum as far as
11240              we're concerned, except that we can support more types.  */
11241           new_symbol (die, NULL, cu);
11242         }
11243
11244       /* Get physical name.  */
11245       physname = dwarf2_physname (fieldname, die, cu);
11246
11247       /* The name is already allocated along with this objfile, so we don't
11248          need to duplicate it for the type.  */
11249       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
11250       FIELD_TYPE (*fp) = die_type (die, cu);
11251       FIELD_NAME (*fp) = fieldname;
11252     }
11253   else if (die->tag == DW_TAG_inheritance)
11254     {
11255       LONGEST offset;
11256
11257       /* C++ base class field.  */
11258       if (handle_data_member_location (die, cu, &offset))
11259         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
11260       FIELD_BITSIZE (*fp) = 0;
11261       FIELD_TYPE (*fp) = die_type (die, cu);
11262       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
11263       fip->nbaseclasses++;
11264     }
11265 }
11266
11267 /* Add a typedef defined in the scope of the FIP's class.  */
11268
11269 static void
11270 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
11271                     struct dwarf2_cu *cu)
11272 {
11273   struct objfile *objfile = cu->objfile;
11274   struct typedef_field_list *new_field;
11275   struct attribute *attr;
11276   struct typedef_field *fp;
11277   char *fieldname = "";
11278
11279   /* Allocate a new field list entry and link it in.  */
11280   new_field = xzalloc (sizeof (*new_field));
11281   make_cleanup (xfree, new_field);
11282
11283   gdb_assert (die->tag == DW_TAG_typedef);
11284
11285   fp = &new_field->field;
11286
11287   /* Get name of field.  */
11288   fp->name = dwarf2_name (die, cu);
11289   if (fp->name == NULL)
11290     return;
11291
11292   fp->type = read_type_die (die, cu);
11293
11294   new_field->next = fip->typedef_field_list;
11295   fip->typedef_field_list = new_field;
11296   fip->typedef_field_list_count++;
11297 }
11298
11299 /* Create the vector of fields, and attach it to the type.  */
11300
11301 static void
11302 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
11303                               struct dwarf2_cu *cu)
11304 {
11305   int nfields = fip->nfields;
11306
11307   /* Record the field count, allocate space for the array of fields,
11308      and create blank accessibility bitfields if necessary.  */
11309   TYPE_NFIELDS (type) = nfields;
11310   TYPE_FIELDS (type) = (struct field *)
11311     TYPE_ALLOC (type, sizeof (struct field) * nfields);
11312   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
11313
11314   if (fip->non_public_fields && cu->language != language_ada)
11315     {
11316       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11317
11318       TYPE_FIELD_PRIVATE_BITS (type) =
11319         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11320       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
11321
11322       TYPE_FIELD_PROTECTED_BITS (type) =
11323         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11324       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
11325
11326       TYPE_FIELD_IGNORE_BITS (type) =
11327         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
11328       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
11329     }
11330
11331   /* If the type has baseclasses, allocate and clear a bit vector for
11332      TYPE_FIELD_VIRTUAL_BITS.  */
11333   if (fip->nbaseclasses && cu->language != language_ada)
11334     {
11335       int num_bytes = B_BYTES (fip->nbaseclasses);
11336       unsigned char *pointer;
11337
11338       ALLOCATE_CPLUS_STRUCT_TYPE (type);
11339       pointer = TYPE_ALLOC (type, num_bytes);
11340       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
11341       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
11342       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
11343     }
11344
11345   /* Copy the saved-up fields into the field vector.  Start from the head of
11346      the list, adding to the tail of the field array, so that they end up in
11347      the same order in the array in which they were added to the list.  */
11348   while (nfields-- > 0)
11349     {
11350       struct nextfield *fieldp;
11351
11352       if (fip->fields)
11353         {
11354           fieldp = fip->fields;
11355           fip->fields = fieldp->next;
11356         }
11357       else
11358         {
11359           fieldp = fip->baseclasses;
11360           fip->baseclasses = fieldp->next;
11361         }
11362
11363       TYPE_FIELD (type, nfields) = fieldp->field;
11364       switch (fieldp->accessibility)
11365         {
11366         case DW_ACCESS_private:
11367           if (cu->language != language_ada)
11368             SET_TYPE_FIELD_PRIVATE (type, nfields);
11369           break;
11370
11371         case DW_ACCESS_protected:
11372           if (cu->language != language_ada)
11373             SET_TYPE_FIELD_PROTECTED (type, nfields);
11374           break;
11375
11376         case DW_ACCESS_public:
11377           break;
11378
11379         default:
11380           /* Unknown accessibility.  Complain and treat it as public.  */
11381           {
11382             complaint (&symfile_complaints, _("unsupported accessibility %d"),
11383                        fieldp->accessibility);
11384           }
11385           break;
11386         }
11387       if (nfields < fip->nbaseclasses)
11388         {
11389           switch (fieldp->virtuality)
11390             {
11391             case DW_VIRTUALITY_virtual:
11392             case DW_VIRTUALITY_pure_virtual:
11393               if (cu->language == language_ada)
11394                 error (_("unexpected virtuality in component of Ada type"));
11395               SET_TYPE_FIELD_VIRTUAL (type, nfields);
11396               break;
11397             }
11398         }
11399     }
11400 }
11401
11402 /* Return true if this member function is a constructor, false
11403    otherwise.  */
11404
11405 static int
11406 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11407 {
11408   const char *fieldname;
11409   const char *typename;
11410   int len;
11411
11412   if (die->parent == NULL)
11413     return 0;
11414
11415   if (die->parent->tag != DW_TAG_structure_type
11416       && die->parent->tag != DW_TAG_union_type
11417       && die->parent->tag != DW_TAG_class_type)
11418     return 0;
11419
11420   fieldname = dwarf2_name (die, cu);
11421   typename = dwarf2_name (die->parent, cu);
11422   if (fieldname == NULL || typename == NULL)
11423     return 0;
11424
11425   len = strlen (fieldname);
11426   return (strncmp (fieldname, typename, len) == 0
11427           && (typename[len] == '\0' || typename[len] == '<'));
11428 }
11429
11430 /* Add a member function to the proper fieldlist.  */
11431
11432 static void
11433 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11434                       struct type *type, struct dwarf2_cu *cu)
11435 {
11436   struct objfile *objfile = cu->objfile;
11437   struct attribute *attr;
11438   struct fnfieldlist *flp;
11439   int i;
11440   struct fn_field *fnp;
11441   const char *fieldname;
11442   struct nextfnfield *new_fnfield;
11443   struct type *this_type;
11444   enum dwarf_access_attribute accessibility;
11445
11446   if (cu->language == language_ada)
11447     error (_("unexpected member function in Ada type"));
11448
11449   /* Get name of member function.  */
11450   fieldname = dwarf2_name (die, cu);
11451   if (fieldname == NULL)
11452     return;
11453
11454   /* Look up member function name in fieldlist.  */
11455   for (i = 0; i < fip->nfnfields; i++)
11456     {
11457       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11458         break;
11459     }
11460
11461   /* Create new list element if necessary.  */
11462   if (i < fip->nfnfields)
11463     flp = &fip->fnfieldlists[i];
11464   else
11465     {
11466       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11467         {
11468           fip->fnfieldlists = (struct fnfieldlist *)
11469             xrealloc (fip->fnfieldlists,
11470                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11471                       * sizeof (struct fnfieldlist));
11472           if (fip->nfnfields == 0)
11473             make_cleanup (free_current_contents, &fip->fnfieldlists);
11474         }
11475       flp = &fip->fnfieldlists[fip->nfnfields];
11476       flp->name = fieldname;
11477       flp->length = 0;
11478       flp->head = NULL;
11479       i = fip->nfnfields++;
11480     }
11481
11482   /* Create a new member function field and chain it to the field list
11483      entry.  */
11484   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11485   make_cleanup (xfree, new_fnfield);
11486   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11487   new_fnfield->next = flp->head;
11488   flp->head = new_fnfield;
11489   flp->length++;
11490
11491   /* Fill in the member function field info.  */
11492   fnp = &new_fnfield->fnfield;
11493
11494   /* Delay processing of the physname until later.  */
11495   if (cu->language == language_cplus || cu->language == language_java)
11496     {
11497       add_to_method_list (type, i, flp->length - 1, fieldname,
11498                           die, cu);
11499     }
11500   else
11501     {
11502       const char *physname = dwarf2_physname (fieldname, die, cu);
11503       fnp->physname = physname ? physname : "";
11504     }
11505
11506   fnp->type = alloc_type (objfile);
11507   this_type = read_type_die (die, cu);
11508   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11509     {
11510       int nparams = TYPE_NFIELDS (this_type);
11511
11512       /* TYPE is the domain of this method, and THIS_TYPE is the type
11513            of the method itself (TYPE_CODE_METHOD).  */
11514       smash_to_method_type (fnp->type, type,
11515                             TYPE_TARGET_TYPE (this_type),
11516                             TYPE_FIELDS (this_type),
11517                             TYPE_NFIELDS (this_type),
11518                             TYPE_VARARGS (this_type));
11519
11520       /* Handle static member functions.
11521          Dwarf2 has no clean way to discern C++ static and non-static
11522          member functions.  G++ helps GDB by marking the first
11523          parameter for non-static member functions (which is the this
11524          pointer) as artificial.  We obtain this information from
11525          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11526       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11527         fnp->voffset = VOFFSET_STATIC;
11528     }
11529   else
11530     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11531                dwarf2_full_name (fieldname, die, cu));
11532
11533   /* Get fcontext from DW_AT_containing_type if present.  */
11534   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11535     fnp->fcontext = die_containing_type (die, cu);
11536
11537   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11538      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11539
11540   /* Get accessibility.  */
11541   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11542   if (attr)
11543     accessibility = DW_UNSND (attr);
11544   else
11545     accessibility = dwarf2_default_access_attribute (die, cu);
11546   switch (accessibility)
11547     {
11548     case DW_ACCESS_private:
11549       fnp->is_private = 1;
11550       break;
11551     case DW_ACCESS_protected:
11552       fnp->is_protected = 1;
11553       break;
11554     }
11555
11556   /* Check for artificial methods.  */
11557   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11558   if (attr && DW_UNSND (attr) != 0)
11559     fnp->is_artificial = 1;
11560
11561   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11562
11563   /* Get index in virtual function table if it is a virtual member
11564      function.  For older versions of GCC, this is an offset in the
11565      appropriate virtual table, as specified by DW_AT_containing_type.
11566      For everyone else, it is an expression to be evaluated relative
11567      to the object address.  */
11568
11569   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11570   if (attr)
11571     {
11572       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11573         {
11574           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11575             {
11576               /* Old-style GCC.  */
11577               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11578             }
11579           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11580                    || (DW_BLOCK (attr)->size > 1
11581                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11582                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11583             {
11584               struct dwarf_block blk;
11585               int offset;
11586
11587               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11588                         ? 1 : 2);
11589               blk.size = DW_BLOCK (attr)->size - offset;
11590               blk.data = DW_BLOCK (attr)->data + offset;
11591               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11592               if ((fnp->voffset % cu->header.addr_size) != 0)
11593                 dwarf2_complex_location_expr_complaint ();
11594               else
11595                 fnp->voffset /= cu->header.addr_size;
11596               fnp->voffset += 2;
11597             }
11598           else
11599             dwarf2_complex_location_expr_complaint ();
11600
11601           if (!fnp->fcontext)
11602             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11603         }
11604       else if (attr_form_is_section_offset (attr))
11605         {
11606           dwarf2_complex_location_expr_complaint ();
11607         }
11608       else
11609         {
11610           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11611                                                  fieldname);
11612         }
11613     }
11614   else
11615     {
11616       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11617       if (attr && DW_UNSND (attr))
11618         {
11619           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11620           complaint (&symfile_complaints,
11621                      _("Member function \"%s\" (offset %d) is virtual "
11622                        "but the vtable offset is not specified"),
11623                      fieldname, die->offset.sect_off);
11624           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11625           TYPE_CPLUS_DYNAMIC (type) = 1;
11626         }
11627     }
11628 }
11629
11630 /* Create the vector of member function fields, and attach it to the type.  */
11631
11632 static void
11633 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11634                                  struct dwarf2_cu *cu)
11635 {
11636   struct fnfieldlist *flp;
11637   int i;
11638
11639   if (cu->language == language_ada)
11640     error (_("unexpected member functions in Ada type"));
11641
11642   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11643   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11644     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11645
11646   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11647     {
11648       struct nextfnfield *nfp = flp->head;
11649       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11650       int k;
11651
11652       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11653       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11654       fn_flp->fn_fields = (struct fn_field *)
11655         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11656       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11657         fn_flp->fn_fields[k] = nfp->fnfield;
11658     }
11659
11660   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11661 }
11662
11663 /* Returns non-zero if NAME is the name of a vtable member in CU's
11664    language, zero otherwise.  */
11665 static int
11666 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11667 {
11668   static const char vptr[] = "_vptr";
11669   static const char vtable[] = "vtable";
11670
11671   /* Look for the C++ and Java forms of the vtable.  */
11672   if ((cu->language == language_java
11673        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11674        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11675        && is_cplus_marker (name[sizeof (vptr) - 1])))
11676     return 1;
11677
11678   return 0;
11679 }
11680
11681 /* GCC outputs unnamed structures that are really pointers to member
11682    functions, with the ABI-specified layout.  If TYPE describes
11683    such a structure, smash it into a member function type.
11684
11685    GCC shouldn't do this; it should just output pointer to member DIEs.
11686    This is GCC PR debug/28767.  */
11687
11688 static void
11689 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11690 {
11691   struct type *pfn_type, *domain_type, *new_type;
11692
11693   /* Check for a structure with no name and two children.  */
11694   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11695     return;
11696
11697   /* Check for __pfn and __delta members.  */
11698   if (TYPE_FIELD_NAME (type, 0) == NULL
11699       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11700       || TYPE_FIELD_NAME (type, 1) == NULL
11701       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11702     return;
11703
11704   /* Find the type of the method.  */
11705   pfn_type = TYPE_FIELD_TYPE (type, 0);
11706   if (pfn_type == NULL
11707       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11708       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11709     return;
11710
11711   /* Look for the "this" argument.  */
11712   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11713   if (TYPE_NFIELDS (pfn_type) == 0
11714       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11715       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11716     return;
11717
11718   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11719   new_type = alloc_type (objfile);
11720   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11721                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11722                         TYPE_VARARGS (pfn_type));
11723   smash_to_methodptr_type (type, new_type);
11724 }
11725
11726 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11727    (icc).  */
11728
11729 static int
11730 producer_is_icc (struct dwarf2_cu *cu)
11731 {
11732   if (!cu->checked_producer)
11733     check_producer (cu);
11734
11735   return cu->producer_is_icc;
11736 }
11737
11738 /* Called when we find the DIE that starts a structure or union scope
11739    (definition) to create a type for the structure or union.  Fill in
11740    the type's name and general properties; the members will not be
11741    processed until process_structure_scope.
11742
11743    NOTE: we need to call these functions regardless of whether or not the
11744    DIE has a DW_AT_name attribute, since it might be an anonymous
11745    structure or union.  This gets the type entered into our set of
11746    user defined types.
11747
11748    However, if the structure is incomplete (an opaque struct/union)
11749    then suppress creating a symbol table entry for it since gdb only
11750    wants to find the one with the complete definition.  Note that if
11751    it is complete, we just call new_symbol, which does it's own
11752    checking about whether the struct/union is anonymous or not (and
11753    suppresses creating a symbol table entry itself).  */
11754
11755 static struct type *
11756 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11757 {
11758   struct objfile *objfile = cu->objfile;
11759   struct type *type;
11760   struct attribute *attr;
11761   const char *name;
11762
11763   /* If the definition of this type lives in .debug_types, read that type.
11764      Don't follow DW_AT_specification though, that will take us back up
11765      the chain and we want to go down.  */
11766   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11767   if (attr)
11768     {
11769       type = get_DW_AT_signature_type (die, attr, cu);
11770
11771       /* The type's CU may not be the same as CU.
11772          Ensure TYPE is recorded with CU in die_type_hash.  */
11773       return set_die_type (die, type, cu);
11774     }
11775
11776   type = alloc_type (objfile);
11777   INIT_CPLUS_SPECIFIC (type);
11778
11779   name = dwarf2_name (die, cu);
11780   if (name != NULL)
11781     {
11782       if (cu->language == language_cplus
11783           || cu->language == language_java)
11784         {
11785           const char *full_name = dwarf2_full_name (name, die, cu);
11786
11787           /* dwarf2_full_name might have already finished building the DIE's
11788              type.  If so, there is no need to continue.  */
11789           if (get_die_type (die, cu) != NULL)
11790             return get_die_type (die, cu);
11791
11792           TYPE_TAG_NAME (type) = full_name;
11793           if (die->tag == DW_TAG_structure_type
11794               || die->tag == DW_TAG_class_type)
11795             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11796         }
11797       else
11798         {
11799           /* The name is already allocated along with this objfile, so
11800              we don't need to duplicate it for the type.  */
11801           TYPE_TAG_NAME (type) = name;
11802           if (die->tag == DW_TAG_class_type)
11803             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11804         }
11805     }
11806
11807   if (die->tag == DW_TAG_structure_type)
11808     {
11809       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11810     }
11811   else if (die->tag == DW_TAG_union_type)
11812     {
11813       TYPE_CODE (type) = TYPE_CODE_UNION;
11814     }
11815   else
11816     {
11817       TYPE_CODE (type) = TYPE_CODE_CLASS;
11818     }
11819
11820   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11821     TYPE_DECLARED_CLASS (type) = 1;
11822
11823   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11824   if (attr)
11825     {
11826       TYPE_LENGTH (type) = DW_UNSND (attr);
11827     }
11828   else
11829     {
11830       TYPE_LENGTH (type) = 0;
11831     }
11832
11833   if (producer_is_icc (cu))
11834     {
11835       /* ICC does not output the required DW_AT_declaration
11836          on incomplete types, but gives them a size of zero.  */
11837     }
11838   else
11839     TYPE_STUB_SUPPORTED (type) = 1;
11840
11841   if (die_is_declaration (die, cu))
11842     TYPE_STUB (type) = 1;
11843   else if (attr == NULL && die->child == NULL
11844            && producer_is_realview (cu->producer))
11845     /* RealView does not output the required DW_AT_declaration
11846        on incomplete types.  */
11847     TYPE_STUB (type) = 1;
11848
11849   /* We need to add the type field to the die immediately so we don't
11850      infinitely recurse when dealing with pointers to the structure
11851      type within the structure itself.  */
11852   set_die_type (die, type, cu);
11853
11854   /* set_die_type should be already done.  */
11855   set_descriptive_type (type, die, cu);
11856
11857   return type;
11858 }
11859
11860 /* Finish creating a structure or union type, including filling in
11861    its members and creating a symbol for it.  */
11862
11863 static void
11864 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11865 {
11866   struct objfile *objfile = cu->objfile;
11867   struct die_info *child_die = die->child;
11868   struct type *type;
11869
11870   type = get_die_type (die, cu);
11871   if (type == NULL)
11872     type = read_structure_type (die, cu);
11873
11874   if (die->child != NULL && ! die_is_declaration (die, cu))
11875     {
11876       struct field_info fi;
11877       struct die_info *child_die;
11878       VEC (symbolp) *template_args = NULL;
11879       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11880
11881       memset (&fi, 0, sizeof (struct field_info));
11882
11883       child_die = die->child;
11884
11885       while (child_die && child_die->tag)
11886         {
11887           if (child_die->tag == DW_TAG_member
11888               || child_die->tag == DW_TAG_variable)
11889             {
11890               /* NOTE: carlton/2002-11-05: A C++ static data member
11891                  should be a DW_TAG_member that is a declaration, but
11892                  all versions of G++ as of this writing (so through at
11893                  least 3.2.1) incorrectly generate DW_TAG_variable
11894                  tags for them instead.  */
11895               dwarf2_add_field (&fi, child_die, cu);
11896             }
11897           else if (child_die->tag == DW_TAG_subprogram)
11898             {
11899               /* C++ member function.  */
11900               dwarf2_add_member_fn (&fi, child_die, type, cu);
11901             }
11902           else if (child_die->tag == DW_TAG_inheritance)
11903             {
11904               /* C++ base class field.  */
11905               dwarf2_add_field (&fi, child_die, cu);
11906             }
11907           else if (child_die->tag == DW_TAG_typedef)
11908             dwarf2_add_typedef (&fi, child_die, cu);
11909           else if (child_die->tag == DW_TAG_template_type_param
11910                    || child_die->tag == DW_TAG_template_value_param)
11911             {
11912               struct symbol *arg = new_symbol (child_die, NULL, cu);
11913
11914               if (arg != NULL)
11915                 VEC_safe_push (symbolp, template_args, arg);
11916             }
11917
11918           child_die = sibling_die (child_die);
11919         }
11920
11921       /* Attach template arguments to type.  */
11922       if (! VEC_empty (symbolp, template_args))
11923         {
11924           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11925           TYPE_N_TEMPLATE_ARGUMENTS (type)
11926             = VEC_length (symbolp, template_args);
11927           TYPE_TEMPLATE_ARGUMENTS (type)
11928             = obstack_alloc (&objfile->objfile_obstack,
11929                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11930                               * sizeof (struct symbol *)));
11931           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11932                   VEC_address (symbolp, template_args),
11933                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11934                    * sizeof (struct symbol *)));
11935           VEC_free (symbolp, template_args);
11936         }
11937
11938       /* Attach fields and member functions to the type.  */
11939       if (fi.nfields)
11940         dwarf2_attach_fields_to_type (&fi, type, cu);
11941       if (fi.nfnfields)
11942         {
11943           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11944
11945           /* Get the type which refers to the base class (possibly this
11946              class itself) which contains the vtable pointer for the current
11947              class from the DW_AT_containing_type attribute.  This use of
11948              DW_AT_containing_type is a GNU extension.  */
11949
11950           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11951             {
11952               struct type *t = die_containing_type (die, cu);
11953
11954               TYPE_VPTR_BASETYPE (type) = t;
11955               if (type == t)
11956                 {
11957                   int i;
11958
11959                   /* Our own class provides vtbl ptr.  */
11960                   for (i = TYPE_NFIELDS (t) - 1;
11961                        i >= TYPE_N_BASECLASSES (t);
11962                        --i)
11963                     {
11964                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11965
11966                       if (is_vtable_name (fieldname, cu))
11967                         {
11968                           TYPE_VPTR_FIELDNO (type) = i;
11969                           break;
11970                         }
11971                     }
11972
11973                   /* Complain if virtual function table field not found.  */
11974                   if (i < TYPE_N_BASECLASSES (t))
11975                     complaint (&symfile_complaints,
11976                                _("virtual function table pointer "
11977                                  "not found when defining class '%s'"),
11978                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11979                                "");
11980                 }
11981               else
11982                 {
11983                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11984                 }
11985             }
11986           else if (cu->producer
11987                    && strncmp (cu->producer,
11988                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11989             {
11990               /* The IBM XLC compiler does not provide direct indication
11991                  of the containing type, but the vtable pointer is
11992                  always named __vfp.  */
11993
11994               int i;
11995
11996               for (i = TYPE_NFIELDS (type) - 1;
11997                    i >= TYPE_N_BASECLASSES (type);
11998                    --i)
11999                 {
12000                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12001                     {
12002                       TYPE_VPTR_FIELDNO (type) = i;
12003                       TYPE_VPTR_BASETYPE (type) = type;
12004                       break;
12005                     }
12006                 }
12007             }
12008         }
12009
12010       /* Copy fi.typedef_field_list linked list elements content into the
12011          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12012       if (fi.typedef_field_list)
12013         {
12014           int i = fi.typedef_field_list_count;
12015
12016           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12017           TYPE_TYPEDEF_FIELD_ARRAY (type)
12018             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12019           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12020
12021           /* Reverse the list order to keep the debug info elements order.  */
12022           while (--i >= 0)
12023             {
12024               struct typedef_field *dest, *src;
12025
12026               dest = &TYPE_TYPEDEF_FIELD (type, i);
12027               src = &fi.typedef_field_list->field;
12028               fi.typedef_field_list = fi.typedef_field_list->next;
12029               *dest = *src;
12030             }
12031         }
12032
12033       do_cleanups (back_to);
12034
12035       if (HAVE_CPLUS_STRUCT (type))
12036         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12037     }
12038
12039   quirk_gcc_member_function_pointer (type, objfile);
12040
12041   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12042      snapshots) has been known to create a die giving a declaration
12043      for a class that has, as a child, a die giving a definition for a
12044      nested class.  So we have to process our children even if the
12045      current die is a declaration.  Normally, of course, a declaration
12046      won't have any children at all.  */
12047
12048   while (child_die != NULL && child_die->tag)
12049     {
12050       if (child_die->tag == DW_TAG_member
12051           || child_die->tag == DW_TAG_variable
12052           || child_die->tag == DW_TAG_inheritance
12053           || child_die->tag == DW_TAG_template_value_param
12054           || child_die->tag == DW_TAG_template_type_param)
12055         {
12056           /* Do nothing.  */
12057         }
12058       else
12059         process_die (child_die, cu);
12060
12061       child_die = sibling_die (child_die);
12062     }
12063
12064   /* Do not consider external references.  According to the DWARF standard,
12065      these DIEs are identified by the fact that they have no byte_size
12066      attribute, and a declaration attribute.  */
12067   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12068       || !die_is_declaration (die, cu))
12069     new_symbol (die, type, cu);
12070 }
12071
12072 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12073    complete the type's fields yet, or create any symbols.  */
12074
12075 static struct type *
12076 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12077 {
12078   struct objfile *objfile = cu->objfile;
12079   struct type *type;
12080   struct attribute *attr;
12081   const char *name;
12082
12083   /* If the definition of this type lives in .debug_types, read that type.
12084      Don't follow DW_AT_specification though, that will take us back up
12085      the chain and we want to go down.  */
12086   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12087   if (attr)
12088     {
12089       type = get_DW_AT_signature_type (die, attr, cu);
12090
12091       /* The type's CU may not be the same as CU.
12092          Ensure TYPE is recorded with CU in die_type_hash.  */
12093       return set_die_type (die, type, cu);
12094     }
12095
12096   type = alloc_type (objfile);
12097
12098   TYPE_CODE (type) = TYPE_CODE_ENUM;
12099   name = dwarf2_full_name (NULL, die, cu);
12100   if (name != NULL)
12101     TYPE_TAG_NAME (type) = name;
12102
12103   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12104   if (attr)
12105     {
12106       TYPE_LENGTH (type) = DW_UNSND (attr);
12107     }
12108   else
12109     {
12110       TYPE_LENGTH (type) = 0;
12111     }
12112
12113   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12114      declared as private in the package spec, and then defined only
12115      inside the package body.  Such types are known as Taft Amendment
12116      Types.  When another package uses such a type, an incomplete DIE
12117      may be generated by the compiler.  */
12118   if (die_is_declaration (die, cu))
12119     TYPE_STUB (type) = 1;
12120
12121   return set_die_type (die, type, cu);
12122 }
12123
12124 /* Given a pointer to a die which begins an enumeration, process all
12125    the dies that define the members of the enumeration, and create the
12126    symbol for the enumeration type.
12127
12128    NOTE: We reverse the order of the element list.  */
12129
12130 static void
12131 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12132 {
12133   struct type *this_type;
12134
12135   this_type = get_die_type (die, cu);
12136   if (this_type == NULL)
12137     this_type = read_enumeration_type (die, cu);
12138
12139   if (die->child != NULL)
12140     {
12141       struct die_info *child_die;
12142       struct symbol *sym;
12143       struct field *fields = NULL;
12144       int num_fields = 0;
12145       int unsigned_enum = 1;
12146       const char *name;
12147       int flag_enum = 1;
12148       ULONGEST mask = 0;
12149
12150       child_die = die->child;
12151       while (child_die && child_die->tag)
12152         {
12153           if (child_die->tag != DW_TAG_enumerator)
12154             {
12155               process_die (child_die, cu);
12156             }
12157           else
12158             {
12159               name = dwarf2_name (child_die, cu);
12160               if (name)
12161                 {
12162                   sym = new_symbol (child_die, this_type, cu);
12163                   if (SYMBOL_VALUE (sym) < 0)
12164                     {
12165                       unsigned_enum = 0;
12166                       flag_enum = 0;
12167                     }
12168                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
12169                     flag_enum = 0;
12170                   else
12171                     mask |= SYMBOL_VALUE (sym);
12172
12173                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
12174                     {
12175                       fields = (struct field *)
12176                         xrealloc (fields,
12177                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
12178                                   * sizeof (struct field));
12179                     }
12180
12181                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
12182                   FIELD_TYPE (fields[num_fields]) = NULL;
12183                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
12184                   FIELD_BITSIZE (fields[num_fields]) = 0;
12185
12186                   num_fields++;
12187                 }
12188             }
12189
12190           child_die = sibling_die (child_die);
12191         }
12192
12193       if (num_fields)
12194         {
12195           TYPE_NFIELDS (this_type) = num_fields;
12196           TYPE_FIELDS (this_type) = (struct field *)
12197             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
12198           memcpy (TYPE_FIELDS (this_type), fields,
12199                   sizeof (struct field) * num_fields);
12200           xfree (fields);
12201         }
12202       if (unsigned_enum)
12203         TYPE_UNSIGNED (this_type) = 1;
12204       if (flag_enum)
12205         TYPE_FLAG_ENUM (this_type) = 1;
12206     }
12207
12208   /* If we are reading an enum from a .debug_types unit, and the enum
12209      is a declaration, and the enum is not the signatured type in the
12210      unit, then we do not want to add a symbol for it.  Adding a
12211      symbol would in some cases obscure the true definition of the
12212      enum, giving users an incomplete type when the definition is
12213      actually available.  Note that we do not want to do this for all
12214      enums which are just declarations, because C++0x allows forward
12215      enum declarations.  */
12216   if (cu->per_cu->is_debug_types
12217       && die_is_declaration (die, cu))
12218     {
12219       struct signatured_type *sig_type;
12220
12221       sig_type = (struct signatured_type *) cu->per_cu;
12222       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
12223       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
12224         return;
12225     }
12226
12227   new_symbol (die, this_type, cu);
12228 }
12229
12230 /* Extract all information from a DW_TAG_array_type DIE and put it in
12231    the DIE's type field.  For now, this only handles one dimensional
12232    arrays.  */
12233
12234 static struct type *
12235 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
12236 {
12237   struct objfile *objfile = cu->objfile;
12238   struct die_info *child_die;
12239   struct type *type;
12240   struct type *element_type, *range_type, *index_type;
12241   struct type **range_types = NULL;
12242   struct attribute *attr;
12243   int ndim = 0;
12244   struct cleanup *back_to;
12245   const char *name;
12246
12247   element_type = die_type (die, cu);
12248
12249   /* The die_type call above may have already set the type for this DIE.  */
12250   type = get_die_type (die, cu);
12251   if (type)
12252     return type;
12253
12254   /* Irix 6.2 native cc creates array types without children for
12255      arrays with unspecified length.  */
12256   if (die->child == NULL)
12257     {
12258       index_type = objfile_type (objfile)->builtin_int;
12259       range_type = create_range_type (NULL, index_type, 0, -1);
12260       type = create_array_type (NULL, element_type, range_type);
12261       return set_die_type (die, type, cu);
12262     }
12263
12264   back_to = make_cleanup (null_cleanup, NULL);
12265   child_die = die->child;
12266   while (child_die && child_die->tag)
12267     {
12268       if (child_die->tag == DW_TAG_subrange_type)
12269         {
12270           struct type *child_type = read_type_die (child_die, cu);
12271
12272           if (child_type != NULL)
12273             {
12274               /* The range type was succesfully read.  Save it for the
12275                  array type creation.  */
12276               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
12277                 {
12278                   range_types = (struct type **)
12279                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
12280                               * sizeof (struct type *));
12281                   if (ndim == 0)
12282                     make_cleanup (free_current_contents, &range_types);
12283                 }
12284               range_types[ndim++] = child_type;
12285             }
12286         }
12287       child_die = sibling_die (child_die);
12288     }
12289
12290   /* Dwarf2 dimensions are output from left to right, create the
12291      necessary array types in backwards order.  */
12292
12293   type = element_type;
12294
12295   if (read_array_order (die, cu) == DW_ORD_col_major)
12296     {
12297       int i = 0;
12298
12299       while (i < ndim)
12300         type = create_array_type (NULL, type, range_types[i++]);
12301     }
12302   else
12303     {
12304       while (ndim-- > 0)
12305         type = create_array_type (NULL, type, range_types[ndim]);
12306     }
12307
12308   /* Understand Dwarf2 support for vector types (like they occur on
12309      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
12310      array type.  This is not part of the Dwarf2/3 standard yet, but a
12311      custom vendor extension.  The main difference between a regular
12312      array and the vector variant is that vectors are passed by value
12313      to functions.  */
12314   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
12315   if (attr)
12316     make_vector_type (type);
12317
12318   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
12319      implementation may choose to implement triple vectors using this
12320      attribute.  */
12321   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12322   if (attr)
12323     {
12324       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
12325         TYPE_LENGTH (type) = DW_UNSND (attr);
12326       else
12327         complaint (&symfile_complaints,
12328                    _("DW_AT_byte_size for array type smaller "
12329                      "than the total size of elements"));
12330     }
12331
12332   name = dwarf2_name (die, cu);
12333   if (name)
12334     TYPE_NAME (type) = name;
12335
12336   /* Install the type in the die.  */
12337   set_die_type (die, type, cu);
12338
12339   /* set_die_type should be already done.  */
12340   set_descriptive_type (type, die, cu);
12341
12342   do_cleanups (back_to);
12343
12344   return type;
12345 }
12346
12347 static enum dwarf_array_dim_ordering
12348 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
12349 {
12350   struct attribute *attr;
12351
12352   attr = dwarf2_attr (die, DW_AT_ordering, cu);
12353
12354   if (attr) return DW_SND (attr);
12355
12356   /* GNU F77 is a special case, as at 08/2004 array type info is the
12357      opposite order to the dwarf2 specification, but data is still
12358      laid out as per normal fortran.
12359
12360      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
12361      version checking.  */
12362
12363   if (cu->language == language_fortran
12364       && cu->producer && strstr (cu->producer, "GNU F77"))
12365     {
12366       return DW_ORD_row_major;
12367     }
12368
12369   switch (cu->language_defn->la_array_ordering)
12370     {
12371     case array_column_major:
12372       return DW_ORD_col_major;
12373     case array_row_major:
12374     default:
12375       return DW_ORD_row_major;
12376     };
12377 }
12378
12379 /* Extract all information from a DW_TAG_set_type DIE and put it in
12380    the DIE's type field.  */
12381
12382 static struct type *
12383 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
12384 {
12385   struct type *domain_type, *set_type;
12386   struct attribute *attr;
12387
12388   domain_type = die_type (die, cu);
12389
12390   /* The die_type call above may have already set the type for this DIE.  */
12391   set_type = get_die_type (die, cu);
12392   if (set_type)
12393     return set_type;
12394
12395   set_type = create_set_type (NULL, domain_type);
12396
12397   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12398   if (attr)
12399     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12400
12401   return set_die_type (die, set_type, cu);
12402 }
12403
12404 /* A helper for read_common_block that creates a locexpr baton.
12405    SYM is the symbol which we are marking as computed.
12406    COMMON_DIE is the DIE for the common block.
12407    COMMON_LOC is the location expression attribute for the common
12408    block itself.
12409    MEMBER_LOC is the location expression attribute for the particular
12410    member of the common block that we are processing.
12411    CU is the CU from which the above come.  */
12412
12413 static void
12414 mark_common_block_symbol_computed (struct symbol *sym,
12415                                    struct die_info *common_die,
12416                                    struct attribute *common_loc,
12417                                    struct attribute *member_loc,
12418                                    struct dwarf2_cu *cu)
12419 {
12420   struct objfile *objfile = dwarf2_per_objfile->objfile;
12421   struct dwarf2_locexpr_baton *baton;
12422   gdb_byte *ptr;
12423   unsigned int cu_off;
12424   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12425   LONGEST offset = 0;
12426
12427   gdb_assert (common_loc && member_loc);
12428   gdb_assert (attr_form_is_block (common_loc));
12429   gdb_assert (attr_form_is_block (member_loc)
12430               || attr_form_is_constant (member_loc));
12431
12432   baton = obstack_alloc (&objfile->objfile_obstack,
12433                          sizeof (struct dwarf2_locexpr_baton));
12434   baton->per_cu = cu->per_cu;
12435   gdb_assert (baton->per_cu);
12436
12437   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12438
12439   if (attr_form_is_constant (member_loc))
12440     {
12441       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12442       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12443     }
12444   else
12445     baton->size += DW_BLOCK (member_loc)->size;
12446
12447   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12448   baton->data = ptr;
12449
12450   *ptr++ = DW_OP_call4;
12451   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12452   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12453   ptr += 4;
12454
12455   if (attr_form_is_constant (member_loc))
12456     {
12457       *ptr++ = DW_OP_addr;
12458       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12459       ptr += cu->header.addr_size;
12460     }
12461   else
12462     {
12463       /* We have to copy the data here, because DW_OP_call4 will only
12464          use a DW_AT_location attribute.  */
12465       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12466       ptr += DW_BLOCK (member_loc)->size;
12467     }
12468
12469   *ptr++ = DW_OP_plus;
12470   gdb_assert (ptr - baton->data == baton->size);
12471
12472   SYMBOL_LOCATION_BATON (sym) = baton;
12473   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12474 }
12475
12476 /* Create appropriate locally-scoped variables for all the
12477    DW_TAG_common_block entries.  Also create a struct common_block
12478    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12479    is used to sepate the common blocks name namespace from regular
12480    variable names.  */
12481
12482 static void
12483 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12484 {
12485   struct attribute *attr;
12486
12487   attr = dwarf2_attr (die, DW_AT_location, cu);
12488   if (attr)
12489     {
12490       /* Support the .debug_loc offsets.  */
12491       if (attr_form_is_block (attr))
12492         {
12493           /* Ok.  */
12494         }
12495       else if (attr_form_is_section_offset (attr))
12496         {
12497           dwarf2_complex_location_expr_complaint ();
12498           attr = NULL;
12499         }
12500       else
12501         {
12502           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12503                                                  "common block member");
12504           attr = NULL;
12505         }
12506     }
12507
12508   if (die->child != NULL)
12509     {
12510       struct objfile *objfile = cu->objfile;
12511       struct die_info *child_die;
12512       size_t n_entries = 0, size;
12513       struct common_block *common_block;
12514       struct symbol *sym;
12515
12516       for (child_die = die->child;
12517            child_die && child_die->tag;
12518            child_die = sibling_die (child_die))
12519         ++n_entries;
12520
12521       size = (sizeof (struct common_block)
12522               + (n_entries - 1) * sizeof (struct symbol *));
12523       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12524       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12525       common_block->n_entries = 0;
12526
12527       for (child_die = die->child;
12528            child_die && child_die->tag;
12529            child_die = sibling_die (child_die))
12530         {
12531           /* Create the symbol in the DW_TAG_common_block block in the current
12532              symbol scope.  */
12533           sym = new_symbol (child_die, NULL, cu);
12534           if (sym != NULL)
12535             {
12536               struct attribute *member_loc;
12537
12538               common_block->contents[common_block->n_entries++] = sym;
12539
12540               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12541                                         cu);
12542               if (member_loc)
12543                 {
12544                   /* GDB has handled this for a long time, but it is
12545                      not specified by DWARF.  It seems to have been
12546                      emitted by gfortran at least as recently as:
12547                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12548                   complaint (&symfile_complaints,
12549                              _("Variable in common block has "
12550                                "DW_AT_data_member_location "
12551                                "- DIE at 0x%x [in module %s]"),
12552                              child_die->offset.sect_off, cu->objfile->name);
12553
12554                   if (attr_form_is_section_offset (member_loc))
12555                     dwarf2_complex_location_expr_complaint ();
12556                   else if (attr_form_is_constant (member_loc)
12557                            || attr_form_is_block (member_loc))
12558                     {
12559                       if (attr)
12560                         mark_common_block_symbol_computed (sym, die, attr,
12561                                                            member_loc, cu);
12562                     }
12563                   else
12564                     dwarf2_complex_location_expr_complaint ();
12565                 }
12566             }
12567         }
12568
12569       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12570       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12571     }
12572 }
12573
12574 /* Create a type for a C++ namespace.  */
12575
12576 static struct type *
12577 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12578 {
12579   struct objfile *objfile = cu->objfile;
12580   const char *previous_prefix, *name;
12581   int is_anonymous;
12582   struct type *type;
12583
12584   /* For extensions, reuse the type of the original namespace.  */
12585   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12586     {
12587       struct die_info *ext_die;
12588       struct dwarf2_cu *ext_cu = cu;
12589
12590       ext_die = dwarf2_extension (die, &ext_cu);
12591       type = read_type_die (ext_die, ext_cu);
12592
12593       /* EXT_CU may not be the same as CU.
12594          Ensure TYPE is recorded with CU in die_type_hash.  */
12595       return set_die_type (die, type, cu);
12596     }
12597
12598   name = namespace_name (die, &is_anonymous, cu);
12599
12600   /* Now build the name of the current namespace.  */
12601
12602   previous_prefix = determine_prefix (die, cu);
12603   if (previous_prefix[0] != '\0')
12604     name = typename_concat (&objfile->objfile_obstack,
12605                             previous_prefix, name, 0, cu);
12606
12607   /* Create the type.  */
12608   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12609                     objfile);
12610   TYPE_NAME (type) = name;
12611   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12612
12613   return set_die_type (die, type, cu);
12614 }
12615
12616 /* Read a C++ namespace.  */
12617
12618 static void
12619 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12620 {
12621   struct objfile *objfile = cu->objfile;
12622   int is_anonymous;
12623
12624   /* Add a symbol associated to this if we haven't seen the namespace
12625      before.  Also, add a using directive if it's an anonymous
12626      namespace.  */
12627
12628   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12629     {
12630       struct type *type;
12631
12632       type = read_type_die (die, cu);
12633       new_symbol (die, type, cu);
12634
12635       namespace_name (die, &is_anonymous, cu);
12636       if (is_anonymous)
12637         {
12638           const char *previous_prefix = determine_prefix (die, cu);
12639
12640           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12641                                   NULL, NULL, 0, &objfile->objfile_obstack);
12642         }
12643     }
12644
12645   if (die->child != NULL)
12646     {
12647       struct die_info *child_die = die->child;
12648
12649       while (child_die && child_die->tag)
12650         {
12651           process_die (child_die, cu);
12652           child_die = sibling_die (child_die);
12653         }
12654     }
12655 }
12656
12657 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12658    imported module.  Still we need that type as local Fortran "use ... only"
12659    declaration imports depend on the created type in determine_prefix.  */
12660
12661 static struct type *
12662 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12663 {
12664   struct objfile *objfile = cu->objfile;
12665   const char *module_name;
12666   struct type *type;
12667
12668   module_name = dwarf2_name (die, cu);
12669   if (!module_name)
12670     complaint (&symfile_complaints,
12671                _("DW_TAG_module has no name, offset 0x%x"),
12672                die->offset.sect_off);
12673   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12674
12675   /* determine_prefix uses TYPE_TAG_NAME.  */
12676   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12677
12678   return set_die_type (die, type, cu);
12679 }
12680
12681 /* Read a Fortran module.  */
12682
12683 static void
12684 read_module (struct die_info *die, struct dwarf2_cu *cu)
12685 {
12686   struct die_info *child_die = die->child;
12687
12688   while (child_die && child_die->tag)
12689     {
12690       process_die (child_die, cu);
12691       child_die = sibling_die (child_die);
12692     }
12693 }
12694
12695 /* Return the name of the namespace represented by DIE.  Set
12696    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12697    namespace.  */
12698
12699 static const char *
12700 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12701 {
12702   struct die_info *current_die;
12703   const char *name = NULL;
12704
12705   /* Loop through the extensions until we find a name.  */
12706
12707   for (current_die = die;
12708        current_die != NULL;
12709        current_die = dwarf2_extension (die, &cu))
12710     {
12711       name = dwarf2_name (current_die, cu);
12712       if (name != NULL)
12713         break;
12714     }
12715
12716   /* Is it an anonymous namespace?  */
12717
12718   *is_anonymous = (name == NULL);
12719   if (*is_anonymous)
12720     name = CP_ANONYMOUS_NAMESPACE_STR;
12721
12722   return name;
12723 }
12724
12725 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12726    the user defined type vector.  */
12727
12728 static struct type *
12729 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12730 {
12731   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12732   struct comp_unit_head *cu_header = &cu->header;
12733   struct type *type;
12734   struct attribute *attr_byte_size;
12735   struct attribute *attr_address_class;
12736   int byte_size, addr_class;
12737   struct type *target_type;
12738
12739   target_type = die_type (die, cu);
12740
12741   /* The die_type call above may have already set the type for this DIE.  */
12742   type = get_die_type (die, cu);
12743   if (type)
12744     return type;
12745
12746   type = lookup_pointer_type (target_type);
12747
12748   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12749   if (attr_byte_size)
12750     byte_size = DW_UNSND (attr_byte_size);
12751   else
12752     byte_size = cu_header->addr_size;
12753
12754   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12755   if (attr_address_class)
12756     addr_class = DW_UNSND (attr_address_class);
12757   else
12758     addr_class = DW_ADDR_none;
12759
12760   /* If the pointer size or address class is different than the
12761      default, create a type variant marked as such and set the
12762      length accordingly.  */
12763   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12764     {
12765       if (gdbarch_address_class_type_flags_p (gdbarch))
12766         {
12767           int type_flags;
12768
12769           type_flags = gdbarch_address_class_type_flags
12770                          (gdbarch, byte_size, addr_class);
12771           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12772                       == 0);
12773           type = make_type_with_address_space (type, type_flags);
12774         }
12775       else if (TYPE_LENGTH (type) != byte_size)
12776         {
12777           complaint (&symfile_complaints,
12778                      _("invalid pointer size %d"), byte_size);
12779         }
12780       else
12781         {
12782           /* Should we also complain about unhandled address classes?  */
12783         }
12784     }
12785
12786   TYPE_LENGTH (type) = byte_size;
12787   return set_die_type (die, type, cu);
12788 }
12789
12790 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12791    the user defined type vector.  */
12792
12793 static struct type *
12794 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12795 {
12796   struct type *type;
12797   struct type *to_type;
12798   struct type *domain;
12799
12800   to_type = die_type (die, cu);
12801   domain = die_containing_type (die, cu);
12802
12803   /* The calls above may have already set the type for this DIE.  */
12804   type = get_die_type (die, cu);
12805   if (type)
12806     return type;
12807
12808   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12809     type = lookup_methodptr_type (to_type);
12810   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12811     {
12812       struct type *new_type = alloc_type (cu->objfile);
12813
12814       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12815                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12816                             TYPE_VARARGS (to_type));
12817       type = lookup_methodptr_type (new_type);
12818     }
12819   else
12820     type = lookup_memberptr_type (to_type, domain);
12821
12822   return set_die_type (die, type, cu);
12823 }
12824
12825 /* Extract all information from a DW_TAG_reference_type DIE and add to
12826    the user defined type vector.  */
12827
12828 static struct type *
12829 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12830 {
12831   struct comp_unit_head *cu_header = &cu->header;
12832   struct type *type, *target_type;
12833   struct attribute *attr;
12834
12835   target_type = die_type (die, cu);
12836
12837   /* The die_type call above may have already set the type for this DIE.  */
12838   type = get_die_type (die, cu);
12839   if (type)
12840     return type;
12841
12842   type = lookup_reference_type (target_type);
12843   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12844   if (attr)
12845     {
12846       TYPE_LENGTH (type) = DW_UNSND (attr);
12847     }
12848   else
12849     {
12850       TYPE_LENGTH (type) = cu_header->addr_size;
12851     }
12852   return set_die_type (die, type, cu);
12853 }
12854
12855 static struct type *
12856 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12857 {
12858   struct type *base_type, *cv_type;
12859
12860   base_type = die_type (die, cu);
12861
12862   /* The die_type call above may have already set the type for this DIE.  */
12863   cv_type = get_die_type (die, cu);
12864   if (cv_type)
12865     return cv_type;
12866
12867   /* In case the const qualifier is applied to an array type, the element type
12868      is so qualified, not the array type (section 6.7.3 of C99).  */
12869   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12870     {
12871       struct type *el_type, *inner_array;
12872
12873       base_type = copy_type (base_type);
12874       inner_array = base_type;
12875
12876       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12877         {
12878           TYPE_TARGET_TYPE (inner_array) =
12879             copy_type (TYPE_TARGET_TYPE (inner_array));
12880           inner_array = TYPE_TARGET_TYPE (inner_array);
12881         }
12882
12883       el_type = TYPE_TARGET_TYPE (inner_array);
12884       TYPE_TARGET_TYPE (inner_array) =
12885         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12886
12887       return set_die_type (die, base_type, cu);
12888     }
12889
12890   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12891   return set_die_type (die, cv_type, cu);
12892 }
12893
12894 static struct type *
12895 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12896 {
12897   struct type *base_type, *cv_type;
12898
12899   base_type = die_type (die, cu);
12900
12901   /* The die_type call above may have already set the type for this DIE.  */
12902   cv_type = get_die_type (die, cu);
12903   if (cv_type)
12904     return cv_type;
12905
12906   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12907   return set_die_type (die, cv_type, cu);
12908 }
12909
12910 /* Handle DW_TAG_restrict_type.  */
12911
12912 static struct type *
12913 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12914 {
12915   struct type *base_type, *cv_type;
12916
12917   base_type = die_type (die, cu);
12918
12919   /* The die_type call above may have already set the type for this DIE.  */
12920   cv_type = get_die_type (die, cu);
12921   if (cv_type)
12922     return cv_type;
12923
12924   cv_type = make_restrict_type (base_type);
12925   return set_die_type (die, cv_type, cu);
12926 }
12927
12928 /* Extract all information from a DW_TAG_string_type DIE and add to
12929    the user defined type vector.  It isn't really a user defined type,
12930    but it behaves like one, with other DIE's using an AT_user_def_type
12931    attribute to reference it.  */
12932
12933 static struct type *
12934 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12935 {
12936   struct objfile *objfile = cu->objfile;
12937   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12938   struct type *type, *range_type, *index_type, *char_type;
12939   struct attribute *attr;
12940   unsigned int length;
12941
12942   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12943   if (attr)
12944     {
12945       length = DW_UNSND (attr);
12946     }
12947   else
12948     {
12949       /* Check for the DW_AT_byte_size attribute.  */
12950       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12951       if (attr)
12952         {
12953           length = DW_UNSND (attr);
12954         }
12955       else
12956         {
12957           length = 1;
12958         }
12959     }
12960
12961   index_type = objfile_type (objfile)->builtin_int;
12962   range_type = create_range_type (NULL, index_type, 1, length);
12963   char_type = language_string_char_type (cu->language_defn, gdbarch);
12964   type = create_string_type (NULL, char_type, range_type);
12965
12966   return set_die_type (die, type, cu);
12967 }
12968
12969 /* Assuming that DIE corresponds to a function, returns nonzero
12970    if the function is prototyped.  */
12971
12972 static int
12973 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
12974 {
12975   struct attribute *attr;
12976
12977   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12978   if (attr && (DW_UNSND (attr) != 0))
12979     return 1;
12980
12981   /* The DWARF standard implies that the DW_AT_prototyped attribute
12982      is only meaninful for C, but the concept also extends to other
12983      languages that allow unprototyped functions (Eg: Objective C).
12984      For all other languages, assume that functions are always
12985      prototyped.  */
12986   if (cu->language != language_c
12987       && cu->language != language_objc
12988       && cu->language != language_opencl)
12989     return 1;
12990
12991   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
12992      prototyped and unprototyped functions; default to prototyped,
12993      since that is more common in modern code (and RealView warns
12994      about unprototyped functions).  */
12995   if (producer_is_realview (cu->producer))
12996     return 1;
12997
12998   return 0;
12999 }
13000
13001 /* Handle DIES due to C code like:
13002
13003    struct foo
13004    {
13005    int (*funcp)(int a, long l);
13006    int b;
13007    };
13008
13009    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13010
13011 static struct type *
13012 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13013 {
13014   struct objfile *objfile = cu->objfile;
13015   struct type *type;            /* Type that this function returns.  */
13016   struct type *ftype;           /* Function that returns above type.  */
13017   struct attribute *attr;
13018
13019   type = die_type (die, cu);
13020
13021   /* The die_type call above may have already set the type for this DIE.  */
13022   ftype = get_die_type (die, cu);
13023   if (ftype)
13024     return ftype;
13025
13026   ftype = lookup_function_type (type);
13027
13028   if (prototyped_function_p (die, cu))
13029     TYPE_PROTOTYPED (ftype) = 1;
13030
13031   /* Store the calling convention in the type if it's available in
13032      the subroutine die.  Otherwise set the calling convention to
13033      the default value DW_CC_normal.  */
13034   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13035   if (attr)
13036     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13037   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13038     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13039   else
13040     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13041
13042   /* We need to add the subroutine type to the die immediately so
13043      we don't infinitely recurse when dealing with parameters
13044      declared as the same subroutine type.  */
13045   set_die_type (die, ftype, cu);
13046
13047   if (die->child != NULL)
13048     {
13049       struct type *void_type = objfile_type (objfile)->builtin_void;
13050       struct die_info *child_die;
13051       int nparams, iparams;
13052
13053       /* Count the number of parameters.
13054          FIXME: GDB currently ignores vararg functions, but knows about
13055          vararg member functions.  */
13056       nparams = 0;
13057       child_die = die->child;
13058       while (child_die && child_die->tag)
13059         {
13060           if (child_die->tag == DW_TAG_formal_parameter)
13061             nparams++;
13062           else if (child_die->tag == DW_TAG_unspecified_parameters)
13063             TYPE_VARARGS (ftype) = 1;
13064           child_die = sibling_die (child_die);
13065         }
13066
13067       /* Allocate storage for parameters and fill them in.  */
13068       TYPE_NFIELDS (ftype) = nparams;
13069       TYPE_FIELDS (ftype) = (struct field *)
13070         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13071
13072       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13073          even if we error out during the parameters reading below.  */
13074       for (iparams = 0; iparams < nparams; iparams++)
13075         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13076
13077       iparams = 0;
13078       child_die = die->child;
13079       while (child_die && child_die->tag)
13080         {
13081           if (child_die->tag == DW_TAG_formal_parameter)
13082             {
13083               struct type *arg_type;
13084
13085               /* DWARF version 2 has no clean way to discern C++
13086                  static and non-static member functions.  G++ helps
13087                  GDB by marking the first parameter for non-static
13088                  member functions (which is the this pointer) as
13089                  artificial.  We pass this information to
13090                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13091
13092                  DWARF version 3 added DW_AT_object_pointer, which GCC
13093                  4.5 does not yet generate.  */
13094               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13095               if (attr)
13096                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13097               else
13098                 {
13099                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13100
13101                   /* GCC/43521: In java, the formal parameter
13102                      "this" is sometimes not marked with DW_AT_artificial.  */
13103                   if (cu->language == language_java)
13104                     {
13105                       const char *name = dwarf2_name (child_die, cu);
13106
13107                       if (name && !strcmp (name, "this"))
13108                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13109                     }
13110                 }
13111               arg_type = die_type (child_die, cu);
13112
13113               /* RealView does not mark THIS as const, which the testsuite
13114                  expects.  GCC marks THIS as const in method definitions,
13115                  but not in the class specifications (GCC PR 43053).  */
13116               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13117                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13118                 {
13119                   int is_this = 0;
13120                   struct dwarf2_cu *arg_cu = cu;
13121                   const char *name = dwarf2_name (child_die, cu);
13122
13123                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13124                   if (attr)
13125                     {
13126                       /* If the compiler emits this, use it.  */
13127                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13128                         is_this = 1;
13129                     }
13130                   else if (name && strcmp (name, "this") == 0)
13131                     /* Function definitions will have the argument names.  */
13132                     is_this = 1;
13133                   else if (name == NULL && iparams == 0)
13134                     /* Declarations may not have the names, so like
13135                        elsewhere in GDB, assume an artificial first
13136                        argument is "this".  */
13137                     is_this = 1;
13138
13139                   if (is_this)
13140                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13141                                              arg_type, 0);
13142                 }
13143
13144               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
13145               iparams++;
13146             }
13147           child_die = sibling_die (child_die);
13148         }
13149     }
13150
13151   return ftype;
13152 }
13153
13154 static struct type *
13155 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
13156 {
13157   struct objfile *objfile = cu->objfile;
13158   const char *name = NULL;
13159   struct type *this_type, *target_type;
13160
13161   name = dwarf2_full_name (NULL, die, cu);
13162   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
13163                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
13164   TYPE_NAME (this_type) = name;
13165   set_die_type (die, this_type, cu);
13166   target_type = die_type (die, cu);
13167   if (target_type != this_type)
13168     TYPE_TARGET_TYPE (this_type) = target_type;
13169   else
13170     {
13171       /* Self-referential typedefs are, it seems, not allowed by the DWARF
13172          spec and cause infinite loops in GDB.  */
13173       complaint (&symfile_complaints,
13174                  _("Self-referential DW_TAG_typedef "
13175                    "- DIE at 0x%x [in module %s]"),
13176                  die->offset.sect_off, objfile->name);
13177       TYPE_TARGET_TYPE (this_type) = NULL;
13178     }
13179   return this_type;
13180 }
13181
13182 /* Find a representation of a given base type and install
13183    it in the TYPE field of the die.  */
13184
13185 static struct type *
13186 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
13187 {
13188   struct objfile *objfile = cu->objfile;
13189   struct type *type;
13190   struct attribute *attr;
13191   int encoding = 0, size = 0;
13192   const char *name;
13193   enum type_code code = TYPE_CODE_INT;
13194   int type_flags = 0;
13195   struct type *target_type = NULL;
13196
13197   attr = dwarf2_attr (die, DW_AT_encoding, cu);
13198   if (attr)
13199     {
13200       encoding = DW_UNSND (attr);
13201     }
13202   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13203   if (attr)
13204     {
13205       size = DW_UNSND (attr);
13206     }
13207   name = dwarf2_name (die, cu);
13208   if (!name)
13209     {
13210       complaint (&symfile_complaints,
13211                  _("DW_AT_name missing from DW_TAG_base_type"));
13212     }
13213
13214   switch (encoding)
13215     {
13216       case DW_ATE_address:
13217         /* Turn DW_ATE_address into a void * pointer.  */
13218         code = TYPE_CODE_PTR;
13219         type_flags |= TYPE_FLAG_UNSIGNED;
13220         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
13221         break;
13222       case DW_ATE_boolean:
13223         code = TYPE_CODE_BOOL;
13224         type_flags |= TYPE_FLAG_UNSIGNED;
13225         break;
13226       case DW_ATE_complex_float:
13227         code = TYPE_CODE_COMPLEX;
13228         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
13229         break;
13230       case DW_ATE_decimal_float:
13231         code = TYPE_CODE_DECFLOAT;
13232         break;
13233       case DW_ATE_float:
13234         code = TYPE_CODE_FLT;
13235         break;
13236       case DW_ATE_signed:
13237         break;
13238       case DW_ATE_unsigned:
13239         type_flags |= TYPE_FLAG_UNSIGNED;
13240         if (cu->language == language_fortran
13241             && name
13242             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
13243           code = TYPE_CODE_CHAR;
13244         break;
13245       case DW_ATE_signed_char:
13246         if (cu->language == language_ada || cu->language == language_m2
13247             || cu->language == language_pascal
13248             || cu->language == language_fortran)
13249           code = TYPE_CODE_CHAR;
13250         break;
13251       case DW_ATE_unsigned_char:
13252         if (cu->language == language_ada || cu->language == language_m2
13253             || cu->language == language_pascal
13254             || cu->language == language_fortran)
13255           code = TYPE_CODE_CHAR;
13256         type_flags |= TYPE_FLAG_UNSIGNED;
13257         break;
13258       case DW_ATE_UTF:
13259         /* We just treat this as an integer and then recognize the
13260            type by name elsewhere.  */
13261         break;
13262
13263       default:
13264         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
13265                    dwarf_type_encoding_name (encoding));
13266         break;
13267     }
13268
13269   type = init_type (code, size, type_flags, NULL, objfile);
13270   TYPE_NAME (type) = name;
13271   TYPE_TARGET_TYPE (type) = target_type;
13272
13273   if (name && strcmp (name, "char") == 0)
13274     TYPE_NOSIGN (type) = 1;
13275
13276   return set_die_type (die, type, cu);
13277 }
13278
13279 /* Read the given DW_AT_subrange DIE.  */
13280
13281 static struct type *
13282 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
13283 {
13284   struct type *base_type, *orig_base_type;
13285   struct type *range_type;
13286   struct attribute *attr;
13287   LONGEST low, high;
13288   int low_default_is_valid;
13289   const char *name;
13290   LONGEST negative_mask;
13291
13292   orig_base_type = die_type (die, cu);
13293   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
13294      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
13295      creating the range type, but we use the result of check_typedef
13296      when examining properties of the type.  */
13297   base_type = check_typedef (orig_base_type);
13298
13299   /* The die_type call above may have already set the type for this DIE.  */
13300   range_type = get_die_type (die, cu);
13301   if (range_type)
13302     return range_type;
13303
13304   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
13305      omitting DW_AT_lower_bound.  */
13306   switch (cu->language)
13307     {
13308     case language_c:
13309     case language_cplus:
13310       low = 0;
13311       low_default_is_valid = 1;
13312       break;
13313     case language_fortran:
13314       low = 1;
13315       low_default_is_valid = 1;
13316       break;
13317     case language_d:
13318     case language_java:
13319     case language_objc:
13320       low = 0;
13321       low_default_is_valid = (cu->header.version >= 4);
13322       break;
13323     case language_ada:
13324     case language_m2:
13325     case language_pascal:
13326       low = 1;
13327       low_default_is_valid = (cu->header.version >= 4);
13328       break;
13329     default:
13330       low = 0;
13331       low_default_is_valid = 0;
13332       break;
13333     }
13334
13335   /* FIXME: For variable sized arrays either of these could be
13336      a variable rather than a constant value.  We'll allow it,
13337      but we don't know how to handle it.  */
13338   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
13339   if (attr)
13340     low = dwarf2_get_attr_constant_value (attr, low);
13341   else if (!low_default_is_valid)
13342     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
13343                                       "- DIE at 0x%x [in module %s]"),
13344                die->offset.sect_off, cu->objfile->name);
13345
13346   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
13347   if (attr)
13348     {
13349       if (attr_form_is_block (attr) || is_ref_attr (attr))
13350         {
13351           /* GCC encodes arrays with unspecified or dynamic length
13352              with a DW_FORM_block1 attribute or a reference attribute.
13353              FIXME: GDB does not yet know how to handle dynamic
13354              arrays properly, treat them as arrays with unspecified
13355              length for now.
13356
13357              FIXME: jimb/2003-09-22: GDB does not really know
13358              how to handle arrays of unspecified length
13359              either; we just represent them as zero-length
13360              arrays.  Choose an appropriate upper bound given
13361              the lower bound we've computed above.  */
13362           high = low - 1;
13363         }
13364       else
13365         high = dwarf2_get_attr_constant_value (attr, 1);
13366     }
13367   else
13368     {
13369       attr = dwarf2_attr (die, DW_AT_count, cu);
13370       if (attr)
13371         {
13372           int count = dwarf2_get_attr_constant_value (attr, 1);
13373           high = low + count - 1;
13374         }
13375       else
13376         {
13377           /* Unspecified array length.  */
13378           high = low - 1;
13379         }
13380     }
13381
13382   /* Dwarf-2 specifications explicitly allows to create subrange types
13383      without specifying a base type.
13384      In that case, the base type must be set to the type of
13385      the lower bound, upper bound or count, in that order, if any of these
13386      three attributes references an object that has a type.
13387      If no base type is found, the Dwarf-2 specifications say that
13388      a signed integer type of size equal to the size of an address should
13389      be used.
13390      For the following C code: `extern char gdb_int [];'
13391      GCC produces an empty range DIE.
13392      FIXME: muller/2010-05-28: Possible references to object for low bound,
13393      high bound or count are not yet handled by this code.  */
13394   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
13395     {
13396       struct objfile *objfile = cu->objfile;
13397       struct gdbarch *gdbarch = get_objfile_arch (objfile);
13398       int addr_size = gdbarch_addr_bit (gdbarch) /8;
13399       struct type *int_type = objfile_type (objfile)->builtin_int;
13400
13401       /* Test "int", "long int", and "long long int" objfile types,
13402          and select the first one having a size above or equal to the
13403          architecture address size.  */
13404       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13405         base_type = int_type;
13406       else
13407         {
13408           int_type = objfile_type (objfile)->builtin_long;
13409           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13410             base_type = int_type;
13411           else
13412             {
13413               int_type = objfile_type (objfile)->builtin_long_long;
13414               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13415                 base_type = int_type;
13416             }
13417         }
13418     }
13419
13420   negative_mask =
13421     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13422   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13423     low |= negative_mask;
13424   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13425     high |= negative_mask;
13426
13427   range_type = create_range_type (NULL, orig_base_type, low, high);
13428
13429   /* Mark arrays with dynamic length at least as an array of unspecified
13430      length.  GDB could check the boundary but before it gets implemented at
13431      least allow accessing the array elements.  */
13432   if (attr && attr_form_is_block (attr))
13433     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13434
13435   /* Ada expects an empty array on no boundary attributes.  */
13436   if (attr == NULL && cu->language != language_ada)
13437     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13438
13439   name = dwarf2_name (die, cu);
13440   if (name)
13441     TYPE_NAME (range_type) = name;
13442
13443   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13444   if (attr)
13445     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13446
13447   set_die_type (die, range_type, cu);
13448
13449   /* set_die_type should be already done.  */
13450   set_descriptive_type (range_type, die, cu);
13451
13452   return range_type;
13453 }
13454
13455 static struct type *
13456 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13457 {
13458   struct type *type;
13459
13460   /* For now, we only support the C meaning of an unspecified type: void.  */
13461
13462   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13463   TYPE_NAME (type) = dwarf2_name (die, cu);
13464
13465   return set_die_type (die, type, cu);
13466 }
13467
13468 /* Read a single die and all its descendents.  Set the die's sibling
13469    field to NULL; set other fields in the die correctly, and set all
13470    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13471    location of the info_ptr after reading all of those dies.  PARENT
13472    is the parent of the die in question.  */
13473
13474 static struct die_info *
13475 read_die_and_children (const struct die_reader_specs *reader,
13476                        const gdb_byte *info_ptr,
13477                        const gdb_byte **new_info_ptr,
13478                        struct die_info *parent)
13479 {
13480   struct die_info *die;
13481   const gdb_byte *cur_ptr;
13482   int has_children;
13483
13484   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13485   if (die == NULL)
13486     {
13487       *new_info_ptr = cur_ptr;
13488       return NULL;
13489     }
13490   store_in_ref_table (die, reader->cu);
13491
13492   if (has_children)
13493     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13494   else
13495     {
13496       die->child = NULL;
13497       *new_info_ptr = cur_ptr;
13498     }
13499
13500   die->sibling = NULL;
13501   die->parent = parent;
13502   return die;
13503 }
13504
13505 /* Read a die, all of its descendents, and all of its siblings; set
13506    all of the fields of all of the dies correctly.  Arguments are as
13507    in read_die_and_children.  */
13508
13509 static struct die_info *
13510 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13511                          const gdb_byte *info_ptr,
13512                          const gdb_byte **new_info_ptr,
13513                          struct die_info *parent)
13514 {
13515   struct die_info *first_die, *last_sibling;
13516   const gdb_byte *cur_ptr;
13517
13518   cur_ptr = info_ptr;
13519   first_die = last_sibling = NULL;
13520
13521   while (1)
13522     {
13523       struct die_info *die
13524         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13525
13526       if (die == NULL)
13527         {
13528           *new_info_ptr = cur_ptr;
13529           return first_die;
13530         }
13531
13532       if (!first_die)
13533         first_die = die;
13534       else
13535         last_sibling->sibling = die;
13536
13537       last_sibling = die;
13538     }
13539 }
13540
13541 /* Read a die, all of its descendents, and all of its siblings; set
13542    all of the fields of all of the dies correctly.  Arguments are as
13543    in read_die_and_children.
13544    This the main entry point for reading a DIE and all its children.  */
13545
13546 static struct die_info *
13547 read_die_and_siblings (const struct die_reader_specs *reader,
13548                        const gdb_byte *info_ptr,
13549                        const gdb_byte **new_info_ptr,
13550                        struct die_info *parent)
13551 {
13552   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13553                                                   new_info_ptr, parent);
13554
13555   if (dwarf2_die_debug)
13556     {
13557       fprintf_unfiltered (gdb_stdlog,
13558                           "Read die from %s@0x%x of %s:\n",
13559                           bfd_section_name (reader->abfd,
13560                                             reader->die_section->asection),
13561                           (unsigned) (info_ptr - reader->die_section->buffer),
13562                           bfd_get_filename (reader->abfd));
13563       dump_die (die, dwarf2_die_debug);
13564     }
13565
13566   return die;
13567 }
13568
13569 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13570    attributes.
13571    The caller is responsible for filling in the extra attributes
13572    and updating (*DIEP)->num_attrs.
13573    Set DIEP to point to a newly allocated die with its information,
13574    except for its child, sibling, and parent fields.
13575    Set HAS_CHILDREN to tell whether the die has children or not.  */
13576
13577 static const gdb_byte *
13578 read_full_die_1 (const struct die_reader_specs *reader,
13579                  struct die_info **diep, const gdb_byte *info_ptr,
13580                  int *has_children, int num_extra_attrs)
13581 {
13582   unsigned int abbrev_number, bytes_read, i;
13583   sect_offset offset;
13584   struct abbrev_info *abbrev;
13585   struct die_info *die;
13586   struct dwarf2_cu *cu = reader->cu;
13587   bfd *abfd = reader->abfd;
13588
13589   offset.sect_off = info_ptr - reader->buffer;
13590   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13591   info_ptr += bytes_read;
13592   if (!abbrev_number)
13593     {
13594       *diep = NULL;
13595       *has_children = 0;
13596       return info_ptr;
13597     }
13598
13599   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13600   if (!abbrev)
13601     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13602            abbrev_number,
13603            bfd_get_filename (abfd));
13604
13605   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13606   die->offset = offset;
13607   die->tag = abbrev->tag;
13608   die->abbrev = abbrev_number;
13609
13610   /* Make the result usable.
13611      The caller needs to update num_attrs after adding the extra
13612      attributes.  */
13613   die->num_attrs = abbrev->num_attrs;
13614
13615   for (i = 0; i < abbrev->num_attrs; ++i)
13616     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13617                                info_ptr);
13618
13619   *diep = die;
13620   *has_children = abbrev->has_children;
13621   return info_ptr;
13622 }
13623
13624 /* Read a die and all its attributes.
13625    Set DIEP to point to a newly allocated die with its information,
13626    except for its child, sibling, and parent fields.
13627    Set HAS_CHILDREN to tell whether the die has children or not.  */
13628
13629 static const gdb_byte *
13630 read_full_die (const struct die_reader_specs *reader,
13631                struct die_info **diep, const gdb_byte *info_ptr,
13632                int *has_children)
13633 {
13634   const gdb_byte *result;
13635
13636   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13637
13638   if (dwarf2_die_debug)
13639     {
13640       fprintf_unfiltered (gdb_stdlog,
13641                           "Read die from %s@0x%x of %s:\n",
13642                           bfd_section_name (reader->abfd,
13643                                             reader->die_section->asection),
13644                           (unsigned) (info_ptr - reader->die_section->buffer),
13645                           bfd_get_filename (reader->abfd));
13646       dump_die (*diep, dwarf2_die_debug);
13647     }
13648
13649   return result;
13650 }
13651 \f
13652 /* Abbreviation tables.
13653
13654    In DWARF version 2, the description of the debugging information is
13655    stored in a separate .debug_abbrev section.  Before we read any
13656    dies from a section we read in all abbreviations and install them
13657    in a hash table.  */
13658
13659 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13660
13661 static struct abbrev_info *
13662 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13663 {
13664   struct abbrev_info *abbrev;
13665
13666   abbrev = (struct abbrev_info *)
13667     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13668   memset (abbrev, 0, sizeof (struct abbrev_info));
13669   return abbrev;
13670 }
13671
13672 /* Add an abbreviation to the table.  */
13673
13674 static void
13675 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13676                          unsigned int abbrev_number,
13677                          struct abbrev_info *abbrev)
13678 {
13679   unsigned int hash_number;
13680
13681   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13682   abbrev->next = abbrev_table->abbrevs[hash_number];
13683   abbrev_table->abbrevs[hash_number] = abbrev;
13684 }
13685
13686 /* Look up an abbrev in the table.
13687    Returns NULL if the abbrev is not found.  */
13688
13689 static struct abbrev_info *
13690 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13691                             unsigned int abbrev_number)
13692 {
13693   unsigned int hash_number;
13694   struct abbrev_info *abbrev;
13695
13696   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13697   abbrev = abbrev_table->abbrevs[hash_number];
13698
13699   while (abbrev)
13700     {
13701       if (abbrev->number == abbrev_number)
13702         return abbrev;
13703       abbrev = abbrev->next;
13704     }
13705   return NULL;
13706 }
13707
13708 /* Read in an abbrev table.  */
13709
13710 static struct abbrev_table *
13711 abbrev_table_read_table (struct dwarf2_section_info *section,
13712                          sect_offset offset)
13713 {
13714   struct objfile *objfile = dwarf2_per_objfile->objfile;
13715   bfd *abfd = section->asection->owner;
13716   struct abbrev_table *abbrev_table;
13717   const gdb_byte *abbrev_ptr;
13718   struct abbrev_info *cur_abbrev;
13719   unsigned int abbrev_number, bytes_read, abbrev_name;
13720   unsigned int abbrev_form;
13721   struct attr_abbrev *cur_attrs;
13722   unsigned int allocated_attrs;
13723
13724   abbrev_table = XMALLOC (struct abbrev_table);
13725   abbrev_table->offset = offset;
13726   obstack_init (&abbrev_table->abbrev_obstack);
13727   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13728                                          (ABBREV_HASH_SIZE
13729                                           * sizeof (struct abbrev_info *)));
13730   memset (abbrev_table->abbrevs, 0,
13731           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13732
13733   dwarf2_read_section (objfile, section);
13734   abbrev_ptr = section->buffer + offset.sect_off;
13735   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13736   abbrev_ptr += bytes_read;
13737
13738   allocated_attrs = ATTR_ALLOC_CHUNK;
13739   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13740
13741   /* Loop until we reach an abbrev number of 0.  */
13742   while (abbrev_number)
13743     {
13744       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13745
13746       /* read in abbrev header */
13747       cur_abbrev->number = abbrev_number;
13748       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13749       abbrev_ptr += bytes_read;
13750       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13751       abbrev_ptr += 1;
13752
13753       /* now read in declarations */
13754       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13755       abbrev_ptr += bytes_read;
13756       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13757       abbrev_ptr += bytes_read;
13758       while (abbrev_name)
13759         {
13760           if (cur_abbrev->num_attrs == allocated_attrs)
13761             {
13762               allocated_attrs += ATTR_ALLOC_CHUNK;
13763               cur_attrs
13764                 = xrealloc (cur_attrs, (allocated_attrs
13765                                         * sizeof (struct attr_abbrev)));
13766             }
13767
13768           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13769           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13770           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13771           abbrev_ptr += bytes_read;
13772           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13773           abbrev_ptr += bytes_read;
13774         }
13775
13776       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13777                                          (cur_abbrev->num_attrs
13778                                           * sizeof (struct attr_abbrev)));
13779       memcpy (cur_abbrev->attrs, cur_attrs,
13780               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13781
13782       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13783
13784       /* Get next abbreviation.
13785          Under Irix6 the abbreviations for a compilation unit are not
13786          always properly terminated with an abbrev number of 0.
13787          Exit loop if we encounter an abbreviation which we have
13788          already read (which means we are about to read the abbreviations
13789          for the next compile unit) or if the end of the abbreviation
13790          table is reached.  */
13791       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13792         break;
13793       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13794       abbrev_ptr += bytes_read;
13795       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13796         break;
13797     }
13798
13799   xfree (cur_attrs);
13800   return abbrev_table;
13801 }
13802
13803 /* Free the resources held by ABBREV_TABLE.  */
13804
13805 static void
13806 abbrev_table_free (struct abbrev_table *abbrev_table)
13807 {
13808   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13809   xfree (abbrev_table);
13810 }
13811
13812 /* Same as abbrev_table_free but as a cleanup.
13813    We pass in a pointer to the pointer to the table so that we can
13814    set the pointer to NULL when we're done.  It also simplifies
13815    build_type_unit_groups.  */
13816
13817 static void
13818 abbrev_table_free_cleanup (void *table_ptr)
13819 {
13820   struct abbrev_table **abbrev_table_ptr = table_ptr;
13821
13822   if (*abbrev_table_ptr != NULL)
13823     abbrev_table_free (*abbrev_table_ptr);
13824   *abbrev_table_ptr = NULL;
13825 }
13826
13827 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13828
13829 static void
13830 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13831                      struct dwarf2_section_info *abbrev_section)
13832 {
13833   cu->abbrev_table =
13834     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13835 }
13836
13837 /* Release the memory used by the abbrev table for a compilation unit.  */
13838
13839 static void
13840 dwarf2_free_abbrev_table (void *ptr_to_cu)
13841 {
13842   struct dwarf2_cu *cu = ptr_to_cu;
13843
13844   if (cu->abbrev_table != NULL)
13845     abbrev_table_free (cu->abbrev_table);
13846   /* Set this to NULL so that we SEGV if we try to read it later,
13847      and also because free_comp_unit verifies this is NULL.  */
13848   cu->abbrev_table = NULL;
13849 }
13850 \f
13851 /* Returns nonzero if TAG represents a type that we might generate a partial
13852    symbol for.  */
13853
13854 static int
13855 is_type_tag_for_partial (int tag)
13856 {
13857   switch (tag)
13858     {
13859 #if 0
13860     /* Some types that would be reasonable to generate partial symbols for,
13861        that we don't at present.  */
13862     case DW_TAG_array_type:
13863     case DW_TAG_file_type:
13864     case DW_TAG_ptr_to_member_type:
13865     case DW_TAG_set_type:
13866     case DW_TAG_string_type:
13867     case DW_TAG_subroutine_type:
13868 #endif
13869     case DW_TAG_base_type:
13870     case DW_TAG_class_type:
13871     case DW_TAG_interface_type:
13872     case DW_TAG_enumeration_type:
13873     case DW_TAG_structure_type:
13874     case DW_TAG_subrange_type:
13875     case DW_TAG_typedef:
13876     case DW_TAG_union_type:
13877       return 1;
13878     default:
13879       return 0;
13880     }
13881 }
13882
13883 /* Load all DIEs that are interesting for partial symbols into memory.  */
13884
13885 static struct partial_die_info *
13886 load_partial_dies (const struct die_reader_specs *reader,
13887                    const gdb_byte *info_ptr, int building_psymtab)
13888 {
13889   struct dwarf2_cu *cu = reader->cu;
13890   struct objfile *objfile = cu->objfile;
13891   struct partial_die_info *part_die;
13892   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13893   struct abbrev_info *abbrev;
13894   unsigned int bytes_read;
13895   unsigned int load_all = 0;
13896   int nesting_level = 1;
13897
13898   parent_die = NULL;
13899   last_die = NULL;
13900
13901   gdb_assert (cu->per_cu != NULL);
13902   if (cu->per_cu->load_all_dies)
13903     load_all = 1;
13904
13905   cu->partial_dies
13906     = htab_create_alloc_ex (cu->header.length / 12,
13907                             partial_die_hash,
13908                             partial_die_eq,
13909                             NULL,
13910                             &cu->comp_unit_obstack,
13911                             hashtab_obstack_allocate,
13912                             dummy_obstack_deallocate);
13913
13914   part_die = obstack_alloc (&cu->comp_unit_obstack,
13915                             sizeof (struct partial_die_info));
13916
13917   while (1)
13918     {
13919       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13920
13921       /* A NULL abbrev means the end of a series of children.  */
13922       if (abbrev == NULL)
13923         {
13924           if (--nesting_level == 0)
13925             {
13926               /* PART_DIE was probably the last thing allocated on the
13927                  comp_unit_obstack, so we could call obstack_free
13928                  here.  We don't do that because the waste is small,
13929                  and will be cleaned up when we're done with this
13930                  compilation unit.  This way, we're also more robust
13931                  against other users of the comp_unit_obstack.  */
13932               return first_die;
13933             }
13934           info_ptr += bytes_read;
13935           last_die = parent_die;
13936           parent_die = parent_die->die_parent;
13937           continue;
13938         }
13939
13940       /* Check for template arguments.  We never save these; if
13941          they're seen, we just mark the parent, and go on our way.  */
13942       if (parent_die != NULL
13943           && cu->language == language_cplus
13944           && (abbrev->tag == DW_TAG_template_type_param
13945               || abbrev->tag == DW_TAG_template_value_param))
13946         {
13947           parent_die->has_template_arguments = 1;
13948
13949           if (!load_all)
13950             {
13951               /* We don't need a partial DIE for the template argument.  */
13952               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13953               continue;
13954             }
13955         }
13956
13957       /* We only recurse into c++ subprograms looking for template arguments.
13958          Skip their other children.  */
13959       if (!load_all
13960           && cu->language == language_cplus
13961           && parent_die != NULL
13962           && parent_die->tag == DW_TAG_subprogram)
13963         {
13964           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13965           continue;
13966         }
13967
13968       /* Check whether this DIE is interesting enough to save.  Normally
13969          we would not be interested in members here, but there may be
13970          later variables referencing them via DW_AT_specification (for
13971          static members).  */
13972       if (!load_all
13973           && !is_type_tag_for_partial (abbrev->tag)
13974           && abbrev->tag != DW_TAG_constant
13975           && abbrev->tag != DW_TAG_enumerator
13976           && abbrev->tag != DW_TAG_subprogram
13977           && abbrev->tag != DW_TAG_lexical_block
13978           && abbrev->tag != DW_TAG_variable
13979           && abbrev->tag != DW_TAG_namespace
13980           && abbrev->tag != DW_TAG_module
13981           && abbrev->tag != DW_TAG_member
13982           && abbrev->tag != DW_TAG_imported_unit)
13983         {
13984           /* Otherwise we skip to the next sibling, if any.  */
13985           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13986           continue;
13987         }
13988
13989       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13990                                    info_ptr);
13991
13992       /* This two-pass algorithm for processing partial symbols has a
13993          high cost in cache pressure.  Thus, handle some simple cases
13994          here which cover the majority of C partial symbols.  DIEs
13995          which neither have specification tags in them, nor could have
13996          specification tags elsewhere pointing at them, can simply be
13997          processed and discarded.
13998
13999          This segment is also optional; scan_partial_symbols and
14000          add_partial_symbol will handle these DIEs if we chain
14001          them in normally.  When compilers which do not emit large
14002          quantities of duplicate debug information are more common,
14003          this code can probably be removed.  */
14004
14005       /* Any complete simple types at the top level (pretty much all
14006          of them, for a language without namespaces), can be processed
14007          directly.  */
14008       if (parent_die == NULL
14009           && part_die->has_specification == 0
14010           && part_die->is_declaration == 0
14011           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14012               || part_die->tag == DW_TAG_base_type
14013               || part_die->tag == DW_TAG_subrange_type))
14014         {
14015           if (building_psymtab && part_die->name != NULL)
14016             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14017                                  VAR_DOMAIN, LOC_TYPEDEF,
14018                                  &objfile->static_psymbols,
14019                                  0, (CORE_ADDR) 0, cu->language, objfile);
14020           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14021           continue;
14022         }
14023
14024       /* The exception for DW_TAG_typedef with has_children above is
14025          a workaround of GCC PR debug/47510.  In the case of this complaint
14026          type_name_no_tag_or_error will error on such types later.
14027
14028          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14029          it could not find the child DIEs referenced later, this is checked
14030          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14031
14032       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14033         complaint (&symfile_complaints,
14034                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14035                      "- DIE at 0x%x [in module %s]"),
14036                    part_die->offset.sect_off, objfile->name);
14037
14038       /* If we're at the second level, and we're an enumerator, and
14039          our parent has no specification (meaning possibly lives in a
14040          namespace elsewhere), then we can add the partial symbol now
14041          instead of queueing it.  */
14042       if (part_die->tag == DW_TAG_enumerator
14043           && parent_die != NULL
14044           && parent_die->die_parent == NULL
14045           && parent_die->tag == DW_TAG_enumeration_type
14046           && parent_die->has_specification == 0)
14047         {
14048           if (part_die->name == NULL)
14049             complaint (&symfile_complaints,
14050                        _("malformed enumerator DIE ignored"));
14051           else if (building_psymtab)
14052             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14053                                  VAR_DOMAIN, LOC_CONST,
14054                                  (cu->language == language_cplus
14055                                   || cu->language == language_java)
14056                                  ? &objfile->global_psymbols
14057                                  : &objfile->static_psymbols,
14058                                  0, (CORE_ADDR) 0, cu->language, objfile);
14059
14060           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14061           continue;
14062         }
14063
14064       /* We'll save this DIE so link it in.  */
14065       part_die->die_parent = parent_die;
14066       part_die->die_sibling = NULL;
14067       part_die->die_child = NULL;
14068
14069       if (last_die && last_die == parent_die)
14070         last_die->die_child = part_die;
14071       else if (last_die)
14072         last_die->die_sibling = part_die;
14073
14074       last_die = part_die;
14075
14076       if (first_die == NULL)
14077         first_die = part_die;
14078
14079       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14080          find interesting need to be in the hash table, because we
14081          also have the parent/sibling/child chains; only those that we
14082          might refer to by offset later during partial symbol reading.
14083
14084          For now this means things that might have be the target of a
14085          DW_AT_specification, DW_AT_abstract_origin, or
14086          DW_AT_extension.  DW_AT_extension will refer only to
14087          namespaces; DW_AT_abstract_origin refers to functions (and
14088          many things under the function DIE, but we do not recurse
14089          into function DIEs during partial symbol reading) and
14090          possibly variables as well; DW_AT_specification refers to
14091          declarations.  Declarations ought to have the DW_AT_declaration
14092          flag.  It happens that GCC forgets to put it in sometimes, but
14093          only for functions, not for types.
14094
14095          Adding more things than necessary to the hash table is harmless
14096          except for the performance cost.  Adding too few will result in
14097          wasted time in find_partial_die, when we reread the compilation
14098          unit with load_all_dies set.  */
14099
14100       if (load_all
14101           || abbrev->tag == DW_TAG_constant
14102           || abbrev->tag == DW_TAG_subprogram
14103           || abbrev->tag == DW_TAG_variable
14104           || abbrev->tag == DW_TAG_namespace
14105           || part_die->is_declaration)
14106         {
14107           void **slot;
14108
14109           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14110                                            part_die->offset.sect_off, INSERT);
14111           *slot = part_die;
14112         }
14113
14114       part_die = obstack_alloc (&cu->comp_unit_obstack,
14115                                 sizeof (struct partial_die_info));
14116
14117       /* For some DIEs we want to follow their children (if any).  For C
14118          we have no reason to follow the children of structures; for other
14119          languages we have to, so that we can get at method physnames
14120          to infer fully qualified class names, for DW_AT_specification,
14121          and for C++ template arguments.  For C++, we also look one level
14122          inside functions to find template arguments (if the name of the
14123          function does not already contain the template arguments).
14124
14125          For Ada, we need to scan the children of subprograms and lexical
14126          blocks as well because Ada allows the definition of nested
14127          entities that could be interesting for the debugger, such as
14128          nested subprograms for instance.  */
14129       if (last_die->has_children
14130           && (load_all
14131               || last_die->tag == DW_TAG_namespace
14132               || last_die->tag == DW_TAG_module
14133               || last_die->tag == DW_TAG_enumeration_type
14134               || (cu->language == language_cplus
14135                   && last_die->tag == DW_TAG_subprogram
14136                   && (last_die->name == NULL
14137                       || strchr (last_die->name, '<') == NULL))
14138               || (cu->language != language_c
14139                   && (last_die->tag == DW_TAG_class_type
14140                       || last_die->tag == DW_TAG_interface_type
14141                       || last_die->tag == DW_TAG_structure_type
14142                       || last_die->tag == DW_TAG_union_type))
14143               || (cu->language == language_ada
14144                   && (last_die->tag == DW_TAG_subprogram
14145                       || last_die->tag == DW_TAG_lexical_block))))
14146         {
14147           nesting_level++;
14148           parent_die = last_die;
14149           continue;
14150         }
14151
14152       /* Otherwise we skip to the next sibling, if any.  */
14153       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
14154
14155       /* Back to the top, do it again.  */
14156     }
14157 }
14158
14159 /* Read a minimal amount of information into the minimal die structure.  */
14160
14161 static const gdb_byte *
14162 read_partial_die (const struct die_reader_specs *reader,
14163                   struct partial_die_info *part_die,
14164                   struct abbrev_info *abbrev, unsigned int abbrev_len,
14165                   const gdb_byte *info_ptr)
14166 {
14167   struct dwarf2_cu *cu = reader->cu;
14168   struct objfile *objfile = cu->objfile;
14169   const gdb_byte *buffer = reader->buffer;
14170   unsigned int i;
14171   struct attribute attr;
14172   int has_low_pc_attr = 0;
14173   int has_high_pc_attr = 0;
14174   int high_pc_relative = 0;
14175
14176   memset (part_die, 0, sizeof (struct partial_die_info));
14177
14178   part_die->offset.sect_off = info_ptr - buffer;
14179
14180   info_ptr += abbrev_len;
14181
14182   if (abbrev == NULL)
14183     return info_ptr;
14184
14185   part_die->tag = abbrev->tag;
14186   part_die->has_children = abbrev->has_children;
14187
14188   for (i = 0; i < abbrev->num_attrs; ++i)
14189     {
14190       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
14191
14192       /* Store the data if it is of an attribute we want to keep in a
14193          partial symbol table.  */
14194       switch (attr.name)
14195         {
14196         case DW_AT_name:
14197           switch (part_die->tag)
14198             {
14199             case DW_TAG_compile_unit:
14200             case DW_TAG_partial_unit:
14201             case DW_TAG_type_unit:
14202               /* Compilation units have a DW_AT_name that is a filename, not
14203                  a source language identifier.  */
14204             case DW_TAG_enumeration_type:
14205             case DW_TAG_enumerator:
14206               /* These tags always have simple identifiers already; no need
14207                  to canonicalize them.  */
14208               part_die->name = DW_STRING (&attr);
14209               break;
14210             default:
14211               part_die->name
14212                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
14213                                             &objfile->objfile_obstack);
14214               break;
14215             }
14216           break;
14217         case DW_AT_linkage_name:
14218         case DW_AT_MIPS_linkage_name:
14219           /* Note that both forms of linkage name might appear.  We
14220              assume they will be the same, and we only store the last
14221              one we see.  */
14222           if (cu->language == language_ada)
14223             part_die->name = DW_STRING (&attr);
14224           part_die->linkage_name = DW_STRING (&attr);
14225           break;
14226         case DW_AT_low_pc:
14227           has_low_pc_attr = 1;
14228           part_die->lowpc = DW_ADDR (&attr);
14229           break;
14230         case DW_AT_high_pc:
14231           has_high_pc_attr = 1;
14232           if (attr.form == DW_FORM_addr
14233               || attr.form == DW_FORM_GNU_addr_index)
14234             part_die->highpc = DW_ADDR (&attr);
14235           else
14236             {
14237               high_pc_relative = 1;
14238               part_die->highpc = DW_UNSND (&attr);
14239             }
14240           break;
14241         case DW_AT_location:
14242           /* Support the .debug_loc offsets.  */
14243           if (attr_form_is_block (&attr))
14244             {
14245                part_die->d.locdesc = DW_BLOCK (&attr);
14246             }
14247           else if (attr_form_is_section_offset (&attr))
14248             {
14249               dwarf2_complex_location_expr_complaint ();
14250             }
14251           else
14252             {
14253               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14254                                                      "partial symbol information");
14255             }
14256           break;
14257         case DW_AT_external:
14258           part_die->is_external = DW_UNSND (&attr);
14259           break;
14260         case DW_AT_declaration:
14261           part_die->is_declaration = DW_UNSND (&attr);
14262           break;
14263         case DW_AT_type:
14264           part_die->has_type = 1;
14265           break;
14266         case DW_AT_abstract_origin:
14267         case DW_AT_specification:
14268         case DW_AT_extension:
14269           part_die->has_specification = 1;
14270           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
14271           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14272                                    || cu->per_cu->is_dwz);
14273           break;
14274         case DW_AT_sibling:
14275           /* Ignore absolute siblings, they might point outside of
14276              the current compile unit.  */
14277           if (attr.form == DW_FORM_ref_addr)
14278             complaint (&symfile_complaints,
14279                        _("ignoring absolute DW_AT_sibling"));
14280           else
14281             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
14282           break;
14283         case DW_AT_byte_size:
14284           part_die->has_byte_size = 1;
14285           break;
14286         case DW_AT_calling_convention:
14287           /* DWARF doesn't provide a way to identify a program's source-level
14288              entry point.  DW_AT_calling_convention attributes are only meant
14289              to describe functions' calling conventions.
14290
14291              However, because it's a necessary piece of information in
14292              Fortran, and because DW_CC_program is the only piece of debugging
14293              information whose definition refers to a 'main program' at all,
14294              several compilers have begun marking Fortran main programs with
14295              DW_CC_program --- even when those functions use the standard
14296              calling conventions.
14297
14298              So until DWARF specifies a way to provide this information and
14299              compilers pick up the new representation, we'll support this
14300              practice.  */
14301           if (DW_UNSND (&attr) == DW_CC_program
14302               && cu->language == language_fortran)
14303             {
14304               set_main_name (part_die->name);
14305
14306               /* As this DIE has a static linkage the name would be difficult
14307                  to look up later.  */
14308               language_of_main = language_fortran;
14309             }
14310           break;
14311         case DW_AT_inline:
14312           if (DW_UNSND (&attr) == DW_INL_inlined
14313               || DW_UNSND (&attr) == DW_INL_declared_inlined)
14314             part_die->may_be_inlined = 1;
14315           break;
14316
14317         case DW_AT_import:
14318           if (part_die->tag == DW_TAG_imported_unit)
14319             {
14320               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
14321               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
14322                                   || cu->per_cu->is_dwz);
14323             }
14324           break;
14325
14326         default:
14327           break;
14328         }
14329     }
14330
14331   if (high_pc_relative)
14332     part_die->highpc += part_die->lowpc;
14333
14334   if (has_low_pc_attr && has_high_pc_attr)
14335     {
14336       /* When using the GNU linker, .gnu.linkonce. sections are used to
14337          eliminate duplicate copies of functions and vtables and such.
14338          The linker will arbitrarily choose one and discard the others.
14339          The AT_*_pc values for such functions refer to local labels in
14340          these sections.  If the section from that file was discarded, the
14341          labels are not in the output, so the relocs get a value of 0.
14342          If this is a discarded function, mark the pc bounds as invalid,
14343          so that GDB will ignore it.  */
14344       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
14345         {
14346           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14347
14348           complaint (&symfile_complaints,
14349                      _("DW_AT_low_pc %s is zero "
14350                        "for DIE at 0x%x [in module %s]"),
14351                      paddress (gdbarch, part_die->lowpc),
14352                      part_die->offset.sect_off, objfile->name);
14353         }
14354       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
14355       else if (part_die->lowpc >= part_die->highpc)
14356         {
14357           struct gdbarch *gdbarch = get_objfile_arch (objfile);
14358
14359           complaint (&symfile_complaints,
14360                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
14361                        "for DIE at 0x%x [in module %s]"),
14362                      paddress (gdbarch, part_die->lowpc),
14363                      paddress (gdbarch, part_die->highpc),
14364                      part_die->offset.sect_off, objfile->name);
14365         }
14366       else
14367         part_die->has_pc_info = 1;
14368     }
14369
14370   return info_ptr;
14371 }
14372
14373 /* Find a cached partial DIE at OFFSET in CU.  */
14374
14375 static struct partial_die_info *
14376 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
14377 {
14378   struct partial_die_info *lookup_die = NULL;
14379   struct partial_die_info part_die;
14380
14381   part_die.offset = offset;
14382   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
14383                                     offset.sect_off);
14384
14385   return lookup_die;
14386 }
14387
14388 /* Find a partial DIE at OFFSET, which may or may not be in CU,
14389    except in the case of .debug_types DIEs which do not reference
14390    outside their CU (they do however referencing other types via
14391    DW_FORM_ref_sig8).  */
14392
14393 static struct partial_die_info *
14394 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
14395 {
14396   struct objfile *objfile = cu->objfile;
14397   struct dwarf2_per_cu_data *per_cu = NULL;
14398   struct partial_die_info *pd = NULL;
14399
14400   if (offset_in_dwz == cu->per_cu->is_dwz
14401       && offset_in_cu_p (&cu->header, offset))
14402     {
14403       pd = find_partial_die_in_comp_unit (offset, cu);
14404       if (pd != NULL)
14405         return pd;
14406       /* We missed recording what we needed.
14407          Load all dies and try again.  */
14408       per_cu = cu->per_cu;
14409     }
14410   else
14411     {
14412       /* TUs don't reference other CUs/TUs (except via type signatures).  */
14413       if (cu->per_cu->is_debug_types)
14414         {
14415           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14416                    " external reference to offset 0x%lx [in module %s].\n"),
14417                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14418                  bfd_get_filename (objfile->obfd));
14419         }
14420       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14421                                                  objfile);
14422
14423       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14424         load_partial_comp_unit (per_cu);
14425
14426       per_cu->cu->last_used = 0;
14427       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14428     }
14429
14430   /* If we didn't find it, and not all dies have been loaded,
14431      load them all and try again.  */
14432
14433   if (pd == NULL && per_cu->load_all_dies == 0)
14434     {
14435       per_cu->load_all_dies = 1;
14436
14437       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14438          THIS_CU->cu may already be in use.  So we can't just free it and
14439          replace its DIEs with the ones we read in.  Instead, we leave those
14440          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14441          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14442          set.  */
14443       load_partial_comp_unit (per_cu);
14444
14445       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14446     }
14447
14448   if (pd == NULL)
14449     internal_error (__FILE__, __LINE__,
14450                     _("could not find partial DIE 0x%x "
14451                       "in cache [from module %s]\n"),
14452                     offset.sect_off, bfd_get_filename (objfile->obfd));
14453   return pd;
14454 }
14455
14456 /* See if we can figure out if the class lives in a namespace.  We do
14457    this by looking for a member function; its demangled name will
14458    contain namespace info, if there is any.  */
14459
14460 static void
14461 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14462                                   struct dwarf2_cu *cu)
14463 {
14464   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14465      what template types look like, because the demangler
14466      frequently doesn't give the same name as the debug info.  We
14467      could fix this by only using the demangled name to get the
14468      prefix (but see comment in read_structure_type).  */
14469
14470   struct partial_die_info *real_pdi;
14471   struct partial_die_info *child_pdi;
14472
14473   /* If this DIE (this DIE's specification, if any) has a parent, then
14474      we should not do this.  We'll prepend the parent's fully qualified
14475      name when we create the partial symbol.  */
14476
14477   real_pdi = struct_pdi;
14478   while (real_pdi->has_specification)
14479     real_pdi = find_partial_die (real_pdi->spec_offset,
14480                                  real_pdi->spec_is_dwz, cu);
14481
14482   if (real_pdi->die_parent != NULL)
14483     return;
14484
14485   for (child_pdi = struct_pdi->die_child;
14486        child_pdi != NULL;
14487        child_pdi = child_pdi->die_sibling)
14488     {
14489       if (child_pdi->tag == DW_TAG_subprogram
14490           && child_pdi->linkage_name != NULL)
14491         {
14492           char *actual_class_name
14493             = language_class_name_from_physname (cu->language_defn,
14494                                                  child_pdi->linkage_name);
14495           if (actual_class_name != NULL)
14496             {
14497               struct_pdi->name
14498                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14499                                  actual_class_name,
14500                                  strlen (actual_class_name));
14501               xfree (actual_class_name);
14502             }
14503           break;
14504         }
14505     }
14506 }
14507
14508 /* Adjust PART_DIE before generating a symbol for it.  This function
14509    may set the is_external flag or change the DIE's name.  */
14510
14511 static void
14512 fixup_partial_die (struct partial_die_info *part_die,
14513                    struct dwarf2_cu *cu)
14514 {
14515   /* Once we've fixed up a die, there's no point in doing so again.
14516      This also avoids a memory leak if we were to call
14517      guess_partial_die_structure_name multiple times.  */
14518   if (part_die->fixup_called)
14519     return;
14520
14521   /* If we found a reference attribute and the DIE has no name, try
14522      to find a name in the referred to DIE.  */
14523
14524   if (part_die->name == NULL && part_die->has_specification)
14525     {
14526       struct partial_die_info *spec_die;
14527
14528       spec_die = find_partial_die (part_die->spec_offset,
14529                                    part_die->spec_is_dwz, cu);
14530
14531       fixup_partial_die (spec_die, cu);
14532
14533       if (spec_die->name)
14534         {
14535           part_die->name = spec_die->name;
14536
14537           /* Copy DW_AT_external attribute if it is set.  */
14538           if (spec_die->is_external)
14539             part_die->is_external = spec_die->is_external;
14540         }
14541     }
14542
14543   /* Set default names for some unnamed DIEs.  */
14544
14545   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14546     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14547
14548   /* If there is no parent die to provide a namespace, and there are
14549      children, see if we can determine the namespace from their linkage
14550      name.  */
14551   if (cu->language == language_cplus
14552       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14553       && part_die->die_parent == NULL
14554       && part_die->has_children
14555       && (part_die->tag == DW_TAG_class_type
14556           || part_die->tag == DW_TAG_structure_type
14557           || part_die->tag == DW_TAG_union_type))
14558     guess_partial_die_structure_name (part_die, cu);
14559
14560   /* GCC might emit a nameless struct or union that has a linkage
14561      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14562   if (part_die->name == NULL
14563       && (part_die->tag == DW_TAG_class_type
14564           || part_die->tag == DW_TAG_interface_type
14565           || part_die->tag == DW_TAG_structure_type
14566           || part_die->tag == DW_TAG_union_type)
14567       && part_die->linkage_name != NULL)
14568     {
14569       char *demangled;
14570
14571       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14572       if (demangled)
14573         {
14574           const char *base;
14575
14576           /* Strip any leading namespaces/classes, keep only the base name.
14577              DW_AT_name for named DIEs does not contain the prefixes.  */
14578           base = strrchr (demangled, ':');
14579           if (base && base > demangled && base[-1] == ':')
14580             base++;
14581           else
14582             base = demangled;
14583
14584           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14585                                           base, strlen (base));
14586           xfree (demangled);
14587         }
14588     }
14589
14590   part_die->fixup_called = 1;
14591 }
14592
14593 /* Read an attribute value described by an attribute form.  */
14594
14595 static const gdb_byte *
14596 read_attribute_value (const struct die_reader_specs *reader,
14597                       struct attribute *attr, unsigned form,
14598                       const gdb_byte *info_ptr)
14599 {
14600   struct dwarf2_cu *cu = reader->cu;
14601   bfd *abfd = reader->abfd;
14602   struct comp_unit_head *cu_header = &cu->header;
14603   unsigned int bytes_read;
14604   struct dwarf_block *blk;
14605
14606   attr->form = form;
14607   switch (form)
14608     {
14609     case DW_FORM_ref_addr:
14610       if (cu->header.version == 2)
14611         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14612       else
14613         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14614                                        &cu->header, &bytes_read);
14615       info_ptr += bytes_read;
14616       break;
14617     case DW_FORM_GNU_ref_alt:
14618       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14619       info_ptr += bytes_read;
14620       break;
14621     case DW_FORM_addr:
14622       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14623       info_ptr += bytes_read;
14624       break;
14625     case DW_FORM_block2:
14626       blk = dwarf_alloc_block (cu);
14627       blk->size = read_2_bytes (abfd, info_ptr);
14628       info_ptr += 2;
14629       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14630       info_ptr += blk->size;
14631       DW_BLOCK (attr) = blk;
14632       break;
14633     case DW_FORM_block4:
14634       blk = dwarf_alloc_block (cu);
14635       blk->size = read_4_bytes (abfd, info_ptr);
14636       info_ptr += 4;
14637       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14638       info_ptr += blk->size;
14639       DW_BLOCK (attr) = blk;
14640       break;
14641     case DW_FORM_data2:
14642       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14643       info_ptr += 2;
14644       break;
14645     case DW_FORM_data4:
14646       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14647       info_ptr += 4;
14648       break;
14649     case DW_FORM_data8:
14650       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14651       info_ptr += 8;
14652       break;
14653     case DW_FORM_sec_offset:
14654       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14655       info_ptr += bytes_read;
14656       break;
14657     case DW_FORM_string:
14658       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14659       DW_STRING_IS_CANONICAL (attr) = 0;
14660       info_ptr += bytes_read;
14661       break;
14662     case DW_FORM_strp:
14663       if (!cu->per_cu->is_dwz)
14664         {
14665           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14666                                                    &bytes_read);
14667           DW_STRING_IS_CANONICAL (attr) = 0;
14668           info_ptr += bytes_read;
14669           break;
14670         }
14671       /* FALLTHROUGH */
14672     case DW_FORM_GNU_strp_alt:
14673       {
14674         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14675         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14676                                           &bytes_read);
14677
14678         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14679         DW_STRING_IS_CANONICAL (attr) = 0;
14680         info_ptr += bytes_read;
14681       }
14682       break;
14683     case DW_FORM_exprloc:
14684     case DW_FORM_block:
14685       blk = dwarf_alloc_block (cu);
14686       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14687       info_ptr += bytes_read;
14688       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14689       info_ptr += blk->size;
14690       DW_BLOCK (attr) = blk;
14691       break;
14692     case DW_FORM_block1:
14693       blk = dwarf_alloc_block (cu);
14694       blk->size = read_1_byte (abfd, info_ptr);
14695       info_ptr += 1;
14696       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14697       info_ptr += blk->size;
14698       DW_BLOCK (attr) = blk;
14699       break;
14700     case DW_FORM_data1:
14701       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14702       info_ptr += 1;
14703       break;
14704     case DW_FORM_flag:
14705       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14706       info_ptr += 1;
14707       break;
14708     case DW_FORM_flag_present:
14709       DW_UNSND (attr) = 1;
14710       break;
14711     case DW_FORM_sdata:
14712       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14713       info_ptr += bytes_read;
14714       break;
14715     case DW_FORM_udata:
14716       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14717       info_ptr += bytes_read;
14718       break;
14719     case DW_FORM_ref1:
14720       DW_UNSND (attr) = (cu->header.offset.sect_off
14721                          + read_1_byte (abfd, info_ptr));
14722       info_ptr += 1;
14723       break;
14724     case DW_FORM_ref2:
14725       DW_UNSND (attr) = (cu->header.offset.sect_off
14726                          + read_2_bytes (abfd, info_ptr));
14727       info_ptr += 2;
14728       break;
14729     case DW_FORM_ref4:
14730       DW_UNSND (attr) = (cu->header.offset.sect_off
14731                          + read_4_bytes (abfd, info_ptr));
14732       info_ptr += 4;
14733       break;
14734     case DW_FORM_ref8:
14735       DW_UNSND (attr) = (cu->header.offset.sect_off
14736                          + read_8_bytes (abfd, info_ptr));
14737       info_ptr += 8;
14738       break;
14739     case DW_FORM_ref_sig8:
14740       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
14741       info_ptr += 8;
14742       break;
14743     case DW_FORM_ref_udata:
14744       DW_UNSND (attr) = (cu->header.offset.sect_off
14745                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14746       info_ptr += bytes_read;
14747       break;
14748     case DW_FORM_indirect:
14749       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14750       info_ptr += bytes_read;
14751       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14752       break;
14753     case DW_FORM_GNU_addr_index:
14754       if (reader->dwo_file == NULL)
14755         {
14756           /* For now flag a hard error.
14757              Later we can turn this into a complaint.  */
14758           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14759                  dwarf_form_name (form),
14760                  bfd_get_filename (abfd));
14761         }
14762       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14763       info_ptr += bytes_read;
14764       break;
14765     case DW_FORM_GNU_str_index:
14766       if (reader->dwo_file == NULL)
14767         {
14768           /* For now flag a hard error.
14769              Later we can turn this into a complaint if warranted.  */
14770           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14771                  dwarf_form_name (form),
14772                  bfd_get_filename (abfd));
14773         }
14774       {
14775         ULONGEST str_index =
14776           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14777
14778         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14779         DW_STRING_IS_CANONICAL (attr) = 0;
14780         info_ptr += bytes_read;
14781       }
14782       break;
14783     default:
14784       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14785              dwarf_form_name (form),
14786              bfd_get_filename (abfd));
14787     }
14788
14789   /* Super hack.  */
14790   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14791     attr->form = DW_FORM_GNU_ref_alt;
14792
14793   /* We have seen instances where the compiler tried to emit a byte
14794      size attribute of -1 which ended up being encoded as an unsigned
14795      0xffffffff.  Although 0xffffffff is technically a valid size value,
14796      an object of this size seems pretty unlikely so we can relatively
14797      safely treat these cases as if the size attribute was invalid and
14798      treat them as zero by default.  */
14799   if (attr->name == DW_AT_byte_size
14800       && form == DW_FORM_data4
14801       && DW_UNSND (attr) >= 0xffffffff)
14802     {
14803       complaint
14804         (&symfile_complaints,
14805          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14806          hex_string (DW_UNSND (attr)));
14807       DW_UNSND (attr) = 0;
14808     }
14809
14810   return info_ptr;
14811 }
14812
14813 /* Read an attribute described by an abbreviated attribute.  */
14814
14815 static const gdb_byte *
14816 read_attribute (const struct die_reader_specs *reader,
14817                 struct attribute *attr, struct attr_abbrev *abbrev,
14818                 const gdb_byte *info_ptr)
14819 {
14820   attr->name = abbrev->name;
14821   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14822 }
14823
14824 /* Read dwarf information from a buffer.  */
14825
14826 static unsigned int
14827 read_1_byte (bfd *abfd, const gdb_byte *buf)
14828 {
14829   return bfd_get_8 (abfd, buf);
14830 }
14831
14832 static int
14833 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14834 {
14835   return bfd_get_signed_8 (abfd, buf);
14836 }
14837
14838 static unsigned int
14839 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14840 {
14841   return bfd_get_16 (abfd, buf);
14842 }
14843
14844 static int
14845 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14846 {
14847   return bfd_get_signed_16 (abfd, buf);
14848 }
14849
14850 static unsigned int
14851 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14852 {
14853   return bfd_get_32 (abfd, buf);
14854 }
14855
14856 static int
14857 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14858 {
14859   return bfd_get_signed_32 (abfd, buf);
14860 }
14861
14862 static ULONGEST
14863 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14864 {
14865   return bfd_get_64 (abfd, buf);
14866 }
14867
14868 static CORE_ADDR
14869 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14870               unsigned int *bytes_read)
14871 {
14872   struct comp_unit_head *cu_header = &cu->header;
14873   CORE_ADDR retval = 0;
14874
14875   if (cu_header->signed_addr_p)
14876     {
14877       switch (cu_header->addr_size)
14878         {
14879         case 2:
14880           retval = bfd_get_signed_16 (abfd, buf);
14881           break;
14882         case 4:
14883           retval = bfd_get_signed_32 (abfd, buf);
14884           break;
14885         case 8:
14886           retval = bfd_get_signed_64 (abfd, buf);
14887           break;
14888         default:
14889           internal_error (__FILE__, __LINE__,
14890                           _("read_address: bad switch, signed [in module %s]"),
14891                           bfd_get_filename (abfd));
14892         }
14893     }
14894   else
14895     {
14896       switch (cu_header->addr_size)
14897         {
14898         case 2:
14899           retval = bfd_get_16 (abfd, buf);
14900           break;
14901         case 4:
14902           retval = bfd_get_32 (abfd, buf);
14903           break;
14904         case 8:
14905           retval = bfd_get_64 (abfd, buf);
14906           break;
14907         default:
14908           internal_error (__FILE__, __LINE__,
14909                           _("read_address: bad switch, "
14910                             "unsigned [in module %s]"),
14911                           bfd_get_filename (abfd));
14912         }
14913     }
14914
14915   *bytes_read = cu_header->addr_size;
14916   return retval;
14917 }
14918
14919 /* Read the initial length from a section.  The (draft) DWARF 3
14920    specification allows the initial length to take up either 4 bytes
14921    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14922    bytes describe the length and all offsets will be 8 bytes in length
14923    instead of 4.
14924
14925    An older, non-standard 64-bit format is also handled by this
14926    function.  The older format in question stores the initial length
14927    as an 8-byte quantity without an escape value.  Lengths greater
14928    than 2^32 aren't very common which means that the initial 4 bytes
14929    is almost always zero.  Since a length value of zero doesn't make
14930    sense for the 32-bit format, this initial zero can be considered to
14931    be an escape value which indicates the presence of the older 64-bit
14932    format.  As written, the code can't detect (old format) lengths
14933    greater than 4GB.  If it becomes necessary to handle lengths
14934    somewhat larger than 4GB, we could allow other small values (such
14935    as the non-sensical values of 1, 2, and 3) to also be used as
14936    escape values indicating the presence of the old format.
14937
14938    The value returned via bytes_read should be used to increment the
14939    relevant pointer after calling read_initial_length().
14940
14941    [ Note:  read_initial_length() and read_offset() are based on the
14942      document entitled "DWARF Debugging Information Format", revision
14943      3, draft 8, dated November 19, 2001.  This document was obtained
14944      from:
14945
14946         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14947
14948      This document is only a draft and is subject to change.  (So beware.)
14949
14950      Details regarding the older, non-standard 64-bit format were
14951      determined empirically by examining 64-bit ELF files produced by
14952      the SGI toolchain on an IRIX 6.5 machine.
14953
14954      - Kevin, July 16, 2002
14955    ] */
14956
14957 static LONGEST
14958 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
14959 {
14960   LONGEST length = bfd_get_32 (abfd, buf);
14961
14962   if (length == 0xffffffff)
14963     {
14964       length = bfd_get_64 (abfd, buf + 4);
14965       *bytes_read = 12;
14966     }
14967   else if (length == 0)
14968     {
14969       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14970       length = bfd_get_64 (abfd, buf);
14971       *bytes_read = 8;
14972     }
14973   else
14974     {
14975       *bytes_read = 4;
14976     }
14977
14978   return length;
14979 }
14980
14981 /* Cover function for read_initial_length.
14982    Returns the length of the object at BUF, and stores the size of the
14983    initial length in *BYTES_READ and stores the size that offsets will be in
14984    *OFFSET_SIZE.
14985    If the initial length size is not equivalent to that specified in
14986    CU_HEADER then issue a complaint.
14987    This is useful when reading non-comp-unit headers.  */
14988
14989 static LONGEST
14990 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
14991                                         const struct comp_unit_head *cu_header,
14992                                         unsigned int *bytes_read,
14993                                         unsigned int *offset_size)
14994 {
14995   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14996
14997   gdb_assert (cu_header->initial_length_size == 4
14998               || cu_header->initial_length_size == 8
14999               || cu_header->initial_length_size == 12);
15000
15001   if (cu_header->initial_length_size != *bytes_read)
15002     complaint (&symfile_complaints,
15003                _("intermixed 32-bit and 64-bit DWARF sections"));
15004
15005   *offset_size = (*bytes_read == 4) ? 4 : 8;
15006   return length;
15007 }
15008
15009 /* Read an offset from the data stream.  The size of the offset is
15010    given by cu_header->offset_size.  */
15011
15012 static LONGEST
15013 read_offset (bfd *abfd, const gdb_byte *buf,
15014              const struct comp_unit_head *cu_header,
15015              unsigned int *bytes_read)
15016 {
15017   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15018
15019   *bytes_read = cu_header->offset_size;
15020   return offset;
15021 }
15022
15023 /* Read an offset from the data stream.  */
15024
15025 static LONGEST
15026 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15027 {
15028   LONGEST retval = 0;
15029
15030   switch (offset_size)
15031     {
15032     case 4:
15033       retval = bfd_get_32 (abfd, buf);
15034       break;
15035     case 8:
15036       retval = bfd_get_64 (abfd, buf);
15037       break;
15038     default:
15039       internal_error (__FILE__, __LINE__,
15040                       _("read_offset_1: bad switch [in module %s]"),
15041                       bfd_get_filename (abfd));
15042     }
15043
15044   return retval;
15045 }
15046
15047 static const gdb_byte *
15048 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15049 {
15050   /* If the size of a host char is 8 bits, we can return a pointer
15051      to the buffer, otherwise we have to copy the data to a buffer
15052      allocated on the temporary obstack.  */
15053   gdb_assert (HOST_CHAR_BIT == 8);
15054   return buf;
15055 }
15056
15057 static const char *
15058 read_direct_string (bfd *abfd, const gdb_byte *buf,
15059                     unsigned int *bytes_read_ptr)
15060 {
15061   /* If the size of a host char is 8 bits, we can return a pointer
15062      to the string, otherwise we have to copy the string to a buffer
15063      allocated on the temporary obstack.  */
15064   gdb_assert (HOST_CHAR_BIT == 8);
15065   if (*buf == '\0')
15066     {
15067       *bytes_read_ptr = 1;
15068       return NULL;
15069     }
15070   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15071   return (const char *) buf;
15072 }
15073
15074 static const char *
15075 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15076 {
15077   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15078   if (dwarf2_per_objfile->str.buffer == NULL)
15079     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15080            bfd_get_filename (abfd));
15081   if (str_offset >= dwarf2_per_objfile->str.size)
15082     error (_("DW_FORM_strp pointing outside of "
15083              ".debug_str section [in module %s]"),
15084            bfd_get_filename (abfd));
15085   gdb_assert (HOST_CHAR_BIT == 8);
15086   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15087     return NULL;
15088   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15089 }
15090
15091 /* Read a string at offset STR_OFFSET in the .debug_str section from
15092    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15093    the string consists of a single NUL byte, return NULL; otherwise
15094    return a pointer to the string.  */
15095
15096 static const char *
15097 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15098 {
15099   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15100
15101   if (dwz->str.buffer == NULL)
15102     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15103              "section [in module %s]"),
15104            bfd_get_filename (dwz->dwz_bfd));
15105   if (str_offset >= dwz->str.size)
15106     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15107              ".debug_str section [in module %s]"),
15108            bfd_get_filename (dwz->dwz_bfd));
15109   gdb_assert (HOST_CHAR_BIT == 8);
15110   if (dwz->str.buffer[str_offset] == '\0')
15111     return NULL;
15112   return (const char *) (dwz->str.buffer + str_offset);
15113 }
15114
15115 static const char *
15116 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15117                       const struct comp_unit_head *cu_header,
15118                       unsigned int *bytes_read_ptr)
15119 {
15120   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15121
15122   return read_indirect_string_at_offset (abfd, str_offset);
15123 }
15124
15125 static ULONGEST
15126 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15127                       unsigned int *bytes_read_ptr)
15128 {
15129   ULONGEST result;
15130   unsigned int num_read;
15131   int i, shift;
15132   unsigned char byte;
15133
15134   result = 0;
15135   shift = 0;
15136   num_read = 0;
15137   i = 0;
15138   while (1)
15139     {
15140       byte = bfd_get_8 (abfd, buf);
15141       buf++;
15142       num_read++;
15143       result |= ((ULONGEST) (byte & 127) << shift);
15144       if ((byte & 128) == 0)
15145         {
15146           break;
15147         }
15148       shift += 7;
15149     }
15150   *bytes_read_ptr = num_read;
15151   return result;
15152 }
15153
15154 static LONGEST
15155 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
15156                     unsigned int *bytes_read_ptr)
15157 {
15158   LONGEST result;
15159   int i, shift, num_read;
15160   unsigned char byte;
15161
15162   result = 0;
15163   shift = 0;
15164   num_read = 0;
15165   i = 0;
15166   while (1)
15167     {
15168       byte = bfd_get_8 (abfd, buf);
15169       buf++;
15170       num_read++;
15171       result |= ((LONGEST) (byte & 127) << shift);
15172       shift += 7;
15173       if ((byte & 128) == 0)
15174         {
15175           break;
15176         }
15177     }
15178   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
15179     result |= -(((LONGEST) 1) << shift);
15180   *bytes_read_ptr = num_read;
15181   return result;
15182 }
15183
15184 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
15185    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
15186    ADDR_SIZE is the size of addresses from the CU header.  */
15187
15188 static CORE_ADDR
15189 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
15190 {
15191   struct objfile *objfile = dwarf2_per_objfile->objfile;
15192   bfd *abfd = objfile->obfd;
15193   const gdb_byte *info_ptr;
15194
15195   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
15196   if (dwarf2_per_objfile->addr.buffer == NULL)
15197     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
15198            objfile->name);
15199   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
15200     error (_("DW_FORM_addr_index pointing outside of "
15201              ".debug_addr section [in module %s]"),
15202            objfile->name);
15203   info_ptr = (dwarf2_per_objfile->addr.buffer
15204               + addr_base + addr_index * addr_size);
15205   if (addr_size == 4)
15206     return bfd_get_32 (abfd, info_ptr);
15207   else
15208     return bfd_get_64 (abfd, info_ptr);
15209 }
15210
15211 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
15212
15213 static CORE_ADDR
15214 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
15215 {
15216   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
15217 }
15218
15219 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
15220
15221 static CORE_ADDR
15222 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
15223                              unsigned int *bytes_read)
15224 {
15225   bfd *abfd = cu->objfile->obfd;
15226   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
15227
15228   return read_addr_index (cu, addr_index);
15229 }
15230
15231 /* Data structure to pass results from dwarf2_read_addr_index_reader
15232    back to dwarf2_read_addr_index.  */
15233
15234 struct dwarf2_read_addr_index_data
15235 {
15236   ULONGEST addr_base;
15237   int addr_size;
15238 };
15239
15240 /* die_reader_func for dwarf2_read_addr_index.  */
15241
15242 static void
15243 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
15244                                const gdb_byte *info_ptr,
15245                                struct die_info *comp_unit_die,
15246                                int has_children,
15247                                void *data)
15248 {
15249   struct dwarf2_cu *cu = reader->cu;
15250   struct dwarf2_read_addr_index_data *aidata =
15251     (struct dwarf2_read_addr_index_data *) data;
15252
15253   aidata->addr_base = cu->addr_base;
15254   aidata->addr_size = cu->header.addr_size;
15255 }
15256
15257 /* Given an index in .debug_addr, fetch the value.
15258    NOTE: This can be called during dwarf expression evaluation,
15259    long after the debug information has been read, and thus per_cu->cu
15260    may no longer exist.  */
15261
15262 CORE_ADDR
15263 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
15264                         unsigned int addr_index)
15265 {
15266   struct objfile *objfile = per_cu->objfile;
15267   struct dwarf2_cu *cu = per_cu->cu;
15268   ULONGEST addr_base;
15269   int addr_size;
15270
15271   /* This is intended to be called from outside this file.  */
15272   dw2_setup (objfile);
15273
15274   /* We need addr_base and addr_size.
15275      If we don't have PER_CU->cu, we have to get it.
15276      Nasty, but the alternative is storing the needed info in PER_CU,
15277      which at this point doesn't seem justified: it's not clear how frequently
15278      it would get used and it would increase the size of every PER_CU.
15279      Entry points like dwarf2_per_cu_addr_size do a similar thing
15280      so we're not in uncharted territory here.
15281      Alas we need to be a bit more complicated as addr_base is contained
15282      in the DIE.
15283
15284      We don't need to read the entire CU(/TU).
15285      We just need the header and top level die.
15286
15287      IWBN to use the aging mechanism to let us lazily later discard the CU.
15288      For now we skip this optimization.  */
15289
15290   if (cu != NULL)
15291     {
15292       addr_base = cu->addr_base;
15293       addr_size = cu->header.addr_size;
15294     }
15295   else
15296     {
15297       struct dwarf2_read_addr_index_data aidata;
15298
15299       /* Note: We can't use init_cutu_and_read_dies_simple here,
15300          we need addr_base.  */
15301       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
15302                                dwarf2_read_addr_index_reader, &aidata);
15303       addr_base = aidata.addr_base;
15304       addr_size = aidata.addr_size;
15305     }
15306
15307   return read_addr_index_1 (addr_index, addr_base, addr_size);
15308 }
15309
15310 /* Given a DW_AT_str_index, fetch the string.  */
15311
15312 static const char *
15313 read_str_index (const struct die_reader_specs *reader,
15314                 struct dwarf2_cu *cu, ULONGEST str_index)
15315 {
15316   struct objfile *objfile = dwarf2_per_objfile->objfile;
15317   const char *dwo_name = objfile->name;
15318   bfd *abfd = objfile->obfd;
15319   struct dwo_sections *sections = &reader->dwo_file->sections;
15320   const gdb_byte *info_ptr;
15321   ULONGEST str_offset;
15322
15323   dwarf2_read_section (objfile, &sections->str);
15324   dwarf2_read_section (objfile, &sections->str_offsets);
15325   if (sections->str.buffer == NULL)
15326     error (_("DW_FORM_str_index used without .debug_str.dwo section"
15327              " in CU at offset 0x%lx [in module %s]"),
15328            (long) cu->header.offset.sect_off, dwo_name);
15329   if (sections->str_offsets.buffer == NULL)
15330     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
15331              " in CU at offset 0x%lx [in module %s]"),
15332            (long) cu->header.offset.sect_off, dwo_name);
15333   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
15334     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
15335              " section in CU at offset 0x%lx [in module %s]"),
15336            (long) cu->header.offset.sect_off, dwo_name);
15337   info_ptr = (sections->str_offsets.buffer
15338               + str_index * cu->header.offset_size);
15339   if (cu->header.offset_size == 4)
15340     str_offset = bfd_get_32 (abfd, info_ptr);
15341   else
15342     str_offset = bfd_get_64 (abfd, info_ptr);
15343   if (str_offset >= sections->str.size)
15344     error (_("Offset from DW_FORM_str_index pointing outside of"
15345              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
15346            (long) cu->header.offset.sect_off, dwo_name);
15347   return (const char *) (sections->str.buffer + str_offset);
15348 }
15349
15350 /* Return the length of an LEB128 number in BUF.  */
15351
15352 static int
15353 leb128_size (const gdb_byte *buf)
15354 {
15355   const gdb_byte *begin = buf;
15356   gdb_byte byte;
15357
15358   while (1)
15359     {
15360       byte = *buf++;
15361       if ((byte & 128) == 0)
15362         return buf - begin;
15363     }
15364 }
15365
15366 static void
15367 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
15368 {
15369   switch (lang)
15370     {
15371     case DW_LANG_C89:
15372     case DW_LANG_C99:
15373     case DW_LANG_C:
15374     case DW_LANG_UPC:
15375       cu->language = language_c;
15376       break;
15377     case DW_LANG_C_plus_plus:
15378       cu->language = language_cplus;
15379       break;
15380     case DW_LANG_D:
15381       cu->language = language_d;
15382       break;
15383     case DW_LANG_Fortran77:
15384     case DW_LANG_Fortran90:
15385     case DW_LANG_Fortran95:
15386       cu->language = language_fortran;
15387       break;
15388     case DW_LANG_Go:
15389       cu->language = language_go;
15390       break;
15391     case DW_LANG_Mips_Assembler:
15392       cu->language = language_asm;
15393       break;
15394     case DW_LANG_Java:
15395       cu->language = language_java;
15396       break;
15397     case DW_LANG_Ada83:
15398     case DW_LANG_Ada95:
15399       cu->language = language_ada;
15400       break;
15401     case DW_LANG_Modula2:
15402       cu->language = language_m2;
15403       break;
15404     case DW_LANG_Pascal83:
15405       cu->language = language_pascal;
15406       break;
15407     case DW_LANG_ObjC:
15408       cu->language = language_objc;
15409       break;
15410     case DW_LANG_Cobol74:
15411     case DW_LANG_Cobol85:
15412     default:
15413       cu->language = language_minimal;
15414       break;
15415     }
15416   cu->language_defn = language_def (cu->language);
15417 }
15418
15419 /* Return the named attribute or NULL if not there.  */
15420
15421 static struct attribute *
15422 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15423 {
15424   for (;;)
15425     {
15426       unsigned int i;
15427       struct attribute *spec = NULL;
15428
15429       for (i = 0; i < die->num_attrs; ++i)
15430         {
15431           if (die->attrs[i].name == name)
15432             return &die->attrs[i];
15433           if (die->attrs[i].name == DW_AT_specification
15434               || die->attrs[i].name == DW_AT_abstract_origin)
15435             spec = &die->attrs[i];
15436         }
15437
15438       if (!spec)
15439         break;
15440
15441       die = follow_die_ref (die, spec, &cu);
15442     }
15443
15444   return NULL;
15445 }
15446
15447 /* Return the named attribute or NULL if not there,
15448    but do not follow DW_AT_specification, etc.
15449    This is for use in contexts where we're reading .debug_types dies.
15450    Following DW_AT_specification, DW_AT_abstract_origin will take us
15451    back up the chain, and we want to go down.  */
15452
15453 static struct attribute *
15454 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15455 {
15456   unsigned int i;
15457
15458   for (i = 0; i < die->num_attrs; ++i)
15459     if (die->attrs[i].name == name)
15460       return &die->attrs[i];
15461
15462   return NULL;
15463 }
15464
15465 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15466    and holds a non-zero value.  This function should only be used for
15467    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15468
15469 static int
15470 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15471 {
15472   struct attribute *attr = dwarf2_attr (die, name, cu);
15473
15474   return (attr && DW_UNSND (attr));
15475 }
15476
15477 static int
15478 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15479 {
15480   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15481      which value is non-zero.  However, we have to be careful with
15482      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15483      (via dwarf2_flag_true_p) follows this attribute.  So we may
15484      end up accidently finding a declaration attribute that belongs
15485      to a different DIE referenced by the specification attribute,
15486      even though the given DIE does not have a declaration attribute.  */
15487   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15488           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15489 }
15490
15491 /* Return the die giving the specification for DIE, if there is
15492    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15493    containing the return value on output.  If there is no
15494    specification, but there is an abstract origin, that is
15495    returned.  */
15496
15497 static struct die_info *
15498 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15499 {
15500   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15501                                              *spec_cu);
15502
15503   if (spec_attr == NULL)
15504     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15505
15506   if (spec_attr == NULL)
15507     return NULL;
15508   else
15509     return follow_die_ref (die, spec_attr, spec_cu);
15510 }
15511
15512 /* Free the line_header structure *LH, and any arrays and strings it
15513    refers to.
15514    NOTE: This is also used as a "cleanup" function.  */
15515
15516 static void
15517 free_line_header (struct line_header *lh)
15518 {
15519   if (lh->standard_opcode_lengths)
15520     xfree (lh->standard_opcode_lengths);
15521
15522   /* Remember that all the lh->file_names[i].name pointers are
15523      pointers into debug_line_buffer, and don't need to be freed.  */
15524   if (lh->file_names)
15525     xfree (lh->file_names);
15526
15527   /* Similarly for the include directory names.  */
15528   if (lh->include_dirs)
15529     xfree (lh->include_dirs);
15530
15531   xfree (lh);
15532 }
15533
15534 /* Add an entry to LH's include directory table.  */
15535
15536 static void
15537 add_include_dir (struct line_header *lh, const char *include_dir)
15538 {
15539   /* Grow the array if necessary.  */
15540   if (lh->include_dirs_size == 0)
15541     {
15542       lh->include_dirs_size = 1; /* for testing */
15543       lh->include_dirs = xmalloc (lh->include_dirs_size
15544                                   * sizeof (*lh->include_dirs));
15545     }
15546   else if (lh->num_include_dirs >= lh->include_dirs_size)
15547     {
15548       lh->include_dirs_size *= 2;
15549       lh->include_dirs = xrealloc (lh->include_dirs,
15550                                    (lh->include_dirs_size
15551                                     * sizeof (*lh->include_dirs)));
15552     }
15553
15554   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15555 }
15556
15557 /* Add an entry to LH's file name table.  */
15558
15559 static void
15560 add_file_name (struct line_header *lh,
15561                const char *name,
15562                unsigned int dir_index,
15563                unsigned int mod_time,
15564                unsigned int length)
15565 {
15566   struct file_entry *fe;
15567
15568   /* Grow the array if necessary.  */
15569   if (lh->file_names_size == 0)
15570     {
15571       lh->file_names_size = 1; /* for testing */
15572       lh->file_names = xmalloc (lh->file_names_size
15573                                 * sizeof (*lh->file_names));
15574     }
15575   else if (lh->num_file_names >= lh->file_names_size)
15576     {
15577       lh->file_names_size *= 2;
15578       lh->file_names = xrealloc (lh->file_names,
15579                                  (lh->file_names_size
15580                                   * sizeof (*lh->file_names)));
15581     }
15582
15583   fe = &lh->file_names[lh->num_file_names++];
15584   fe->name = name;
15585   fe->dir_index = dir_index;
15586   fe->mod_time = mod_time;
15587   fe->length = length;
15588   fe->included_p = 0;
15589   fe->symtab = NULL;
15590 }
15591
15592 /* A convenience function to find the proper .debug_line section for a
15593    CU.  */
15594
15595 static struct dwarf2_section_info *
15596 get_debug_line_section (struct dwarf2_cu *cu)
15597 {
15598   struct dwarf2_section_info *section;
15599
15600   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15601      DWO file.  */
15602   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15603     section = &cu->dwo_unit->dwo_file->sections.line;
15604   else if (cu->per_cu->is_dwz)
15605     {
15606       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15607
15608       section = &dwz->line;
15609     }
15610   else
15611     section = &dwarf2_per_objfile->line;
15612
15613   return section;
15614 }
15615
15616 /* Read the statement program header starting at OFFSET in
15617    .debug_line, or .debug_line.dwo.  Return a pointer
15618    to a struct line_header, allocated using xmalloc.
15619
15620    NOTE: the strings in the include directory and file name tables of
15621    the returned object point into the dwarf line section buffer,
15622    and must not be freed.  */
15623
15624 static struct line_header *
15625 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15626 {
15627   struct cleanup *back_to;
15628   struct line_header *lh;
15629   const gdb_byte *line_ptr;
15630   unsigned int bytes_read, offset_size;
15631   int i;
15632   const char *cur_dir, *cur_file;
15633   struct dwarf2_section_info *section;
15634   bfd *abfd;
15635
15636   section = get_debug_line_section (cu);
15637   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15638   if (section->buffer == NULL)
15639     {
15640       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15641         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15642       else
15643         complaint (&symfile_complaints, _("missing .debug_line section"));
15644       return 0;
15645     }
15646
15647   /* We can't do this until we know the section is non-empty.
15648      Only then do we know we have such a section.  */
15649   abfd = section->asection->owner;
15650
15651   /* Make sure that at least there's room for the total_length field.
15652      That could be 12 bytes long, but we're just going to fudge that.  */
15653   if (offset + 4 >= section->size)
15654     {
15655       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15656       return 0;
15657     }
15658
15659   lh = xmalloc (sizeof (*lh));
15660   memset (lh, 0, sizeof (*lh));
15661   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15662                           (void *) lh);
15663
15664   line_ptr = section->buffer + offset;
15665
15666   /* Read in the header.  */
15667   lh->total_length =
15668     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15669                                             &bytes_read, &offset_size);
15670   line_ptr += bytes_read;
15671   if (line_ptr + lh->total_length > (section->buffer + section->size))
15672     {
15673       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15674       return 0;
15675     }
15676   lh->statement_program_end = line_ptr + lh->total_length;
15677   lh->version = read_2_bytes (abfd, line_ptr);
15678   line_ptr += 2;
15679   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15680   line_ptr += offset_size;
15681   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15682   line_ptr += 1;
15683   if (lh->version >= 4)
15684     {
15685       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15686       line_ptr += 1;
15687     }
15688   else
15689     lh->maximum_ops_per_instruction = 1;
15690
15691   if (lh->maximum_ops_per_instruction == 0)
15692     {
15693       lh->maximum_ops_per_instruction = 1;
15694       complaint (&symfile_complaints,
15695                  _("invalid maximum_ops_per_instruction "
15696                    "in `.debug_line' section"));
15697     }
15698
15699   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15700   line_ptr += 1;
15701   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15702   line_ptr += 1;
15703   lh->line_range = read_1_byte (abfd, line_ptr);
15704   line_ptr += 1;
15705   lh->opcode_base = read_1_byte (abfd, line_ptr);
15706   line_ptr += 1;
15707   lh->standard_opcode_lengths
15708     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15709
15710   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15711   for (i = 1; i < lh->opcode_base; ++i)
15712     {
15713       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15714       line_ptr += 1;
15715     }
15716
15717   /* Read directory table.  */
15718   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15719     {
15720       line_ptr += bytes_read;
15721       add_include_dir (lh, cur_dir);
15722     }
15723   line_ptr += bytes_read;
15724
15725   /* Read file name table.  */
15726   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15727     {
15728       unsigned int dir_index, mod_time, length;
15729
15730       line_ptr += bytes_read;
15731       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15732       line_ptr += bytes_read;
15733       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15734       line_ptr += bytes_read;
15735       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15736       line_ptr += bytes_read;
15737
15738       add_file_name (lh, cur_file, dir_index, mod_time, length);
15739     }
15740   line_ptr += bytes_read;
15741   lh->statement_program_start = line_ptr;
15742
15743   if (line_ptr > (section->buffer + section->size))
15744     complaint (&symfile_complaints,
15745                _("line number info header doesn't "
15746                  "fit in `.debug_line' section"));
15747
15748   discard_cleanups (back_to);
15749   return lh;
15750 }
15751
15752 /* Subroutine of dwarf_decode_lines to simplify it.
15753    Return the file name of the psymtab for included file FILE_INDEX
15754    in line header LH of PST.
15755    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15756    If space for the result is malloc'd, it will be freed by a cleanup.
15757    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15758
15759    The function creates dangling cleanup registration.  */
15760
15761 static const char *
15762 psymtab_include_file_name (const struct line_header *lh, int file_index,
15763                            const struct partial_symtab *pst,
15764                            const char *comp_dir)
15765 {
15766   const struct file_entry fe = lh->file_names [file_index];
15767   const char *include_name = fe.name;
15768   const char *include_name_to_compare = include_name;
15769   const char *dir_name = NULL;
15770   const char *pst_filename;
15771   char *copied_name = NULL;
15772   int file_is_pst;
15773
15774   if (fe.dir_index)
15775     dir_name = lh->include_dirs[fe.dir_index - 1];
15776
15777   if (!IS_ABSOLUTE_PATH (include_name)
15778       && (dir_name != NULL || comp_dir != NULL))
15779     {
15780       /* Avoid creating a duplicate psymtab for PST.
15781          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15782          Before we do the comparison, however, we need to account
15783          for DIR_NAME and COMP_DIR.
15784          First prepend dir_name (if non-NULL).  If we still don't
15785          have an absolute path prepend comp_dir (if non-NULL).
15786          However, the directory we record in the include-file's
15787          psymtab does not contain COMP_DIR (to match the
15788          corresponding symtab(s)).
15789
15790          Example:
15791
15792          bash$ cd /tmp
15793          bash$ gcc -g ./hello.c
15794          include_name = "hello.c"
15795          dir_name = "."
15796          DW_AT_comp_dir = comp_dir = "/tmp"
15797          DW_AT_name = "./hello.c"  */
15798
15799       if (dir_name != NULL)
15800         {
15801           char *tem = concat (dir_name, SLASH_STRING,
15802                               include_name, (char *)NULL);
15803
15804           make_cleanup (xfree, tem);
15805           include_name = tem;
15806           include_name_to_compare = include_name;
15807         }
15808       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15809         {
15810           char *tem = concat (comp_dir, SLASH_STRING,
15811                               include_name, (char *)NULL);
15812
15813           make_cleanup (xfree, tem);
15814           include_name_to_compare = tem;
15815         }
15816     }
15817
15818   pst_filename = pst->filename;
15819   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15820     {
15821       copied_name = concat (pst->dirname, SLASH_STRING,
15822                             pst_filename, (char *)NULL);
15823       pst_filename = copied_name;
15824     }
15825
15826   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15827
15828   if (copied_name != NULL)
15829     xfree (copied_name);
15830
15831   if (file_is_pst)
15832     return NULL;
15833   return include_name;
15834 }
15835
15836 /* Ignore this record_line request.  */
15837
15838 static void
15839 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15840 {
15841   return;
15842 }
15843
15844 /* Subroutine of dwarf_decode_lines to simplify it.
15845    Process the line number information in LH.  */
15846
15847 static void
15848 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15849                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15850 {
15851   const gdb_byte *line_ptr, *extended_end;
15852   const gdb_byte *line_end;
15853   unsigned int bytes_read, extended_len;
15854   unsigned char op_code, extended_op, adj_opcode;
15855   CORE_ADDR baseaddr;
15856   struct objfile *objfile = cu->objfile;
15857   bfd *abfd = objfile->obfd;
15858   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15859   const int decode_for_pst_p = (pst != NULL);
15860   struct subfile *last_subfile = NULL;
15861   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15862     = record_line;
15863
15864   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15865
15866   line_ptr = lh->statement_program_start;
15867   line_end = lh->statement_program_end;
15868
15869   /* Read the statement sequences until there's nothing left.  */
15870   while (line_ptr < line_end)
15871     {
15872       /* state machine registers  */
15873       CORE_ADDR address = 0;
15874       unsigned int file = 1;
15875       unsigned int line = 1;
15876       unsigned int column = 0;
15877       int is_stmt = lh->default_is_stmt;
15878       int basic_block = 0;
15879       int end_sequence = 0;
15880       CORE_ADDR addr;
15881       unsigned char op_index = 0;
15882
15883       if (!decode_for_pst_p && lh->num_file_names >= file)
15884         {
15885           /* Start a subfile for the current file of the state machine.  */
15886           /* lh->include_dirs and lh->file_names are 0-based, but the
15887              directory and file name numbers in the statement program
15888              are 1-based.  */
15889           struct file_entry *fe = &lh->file_names[file - 1];
15890           const char *dir = NULL;
15891
15892           if (fe->dir_index)
15893             dir = lh->include_dirs[fe->dir_index - 1];
15894
15895           dwarf2_start_subfile (fe->name, dir, comp_dir);
15896         }
15897
15898       /* Decode the table.  */
15899       while (!end_sequence)
15900         {
15901           op_code = read_1_byte (abfd, line_ptr);
15902           line_ptr += 1;
15903           if (line_ptr > line_end)
15904             {
15905               dwarf2_debug_line_missing_end_sequence_complaint ();
15906               break;
15907             }
15908
15909           if (op_code >= lh->opcode_base)
15910             {
15911               /* Special operand.  */
15912               adj_opcode = op_code - lh->opcode_base;
15913               address += (((op_index + (adj_opcode / lh->line_range))
15914                            / lh->maximum_ops_per_instruction)
15915                           * lh->minimum_instruction_length);
15916               op_index = ((op_index + (adj_opcode / lh->line_range))
15917                           % lh->maximum_ops_per_instruction);
15918               line += lh->line_base + (adj_opcode % lh->line_range);
15919               if (lh->num_file_names < file || file == 0)
15920                 dwarf2_debug_line_missing_file_complaint ();
15921               /* For now we ignore lines not starting on an
15922                  instruction boundary.  */
15923               else if (op_index == 0)
15924                 {
15925                   lh->file_names[file - 1].included_p = 1;
15926                   if (!decode_for_pst_p && is_stmt)
15927                     {
15928                       if (last_subfile != current_subfile)
15929                         {
15930                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15931                           if (last_subfile)
15932                             (*p_record_line) (last_subfile, 0, addr);
15933                           last_subfile = current_subfile;
15934                         }
15935                       /* Append row to matrix using current values.  */
15936                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15937                       (*p_record_line) (current_subfile, line, addr);
15938                     }
15939                 }
15940               basic_block = 0;
15941             }
15942           else switch (op_code)
15943             {
15944             case DW_LNS_extended_op:
15945               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15946                                                    &bytes_read);
15947               line_ptr += bytes_read;
15948               extended_end = line_ptr + extended_len;
15949               extended_op = read_1_byte (abfd, line_ptr);
15950               line_ptr += 1;
15951               switch (extended_op)
15952                 {
15953                 case DW_LNE_end_sequence:
15954                   p_record_line = record_line;
15955                   end_sequence = 1;
15956                   break;
15957                 case DW_LNE_set_address:
15958                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15959
15960                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15961                     {
15962                       /* This line table is for a function which has been
15963                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15964
15965                       long line_offset
15966                         = line_ptr - get_debug_line_section (cu)->buffer;
15967
15968                       complaint (&symfile_complaints,
15969                                  _(".debug_line address at offset 0x%lx is 0 "
15970                                    "[in module %s]"),
15971                                  line_offset, objfile->name);
15972                       p_record_line = noop_record_line;
15973                     }
15974
15975                   op_index = 0;
15976                   line_ptr += bytes_read;
15977                   address += baseaddr;
15978                   break;
15979                 case DW_LNE_define_file:
15980                   {
15981                     const char *cur_file;
15982                     unsigned int dir_index, mod_time, length;
15983
15984                     cur_file = read_direct_string (abfd, line_ptr,
15985                                                    &bytes_read);
15986                     line_ptr += bytes_read;
15987                     dir_index =
15988                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15989                     line_ptr += bytes_read;
15990                     mod_time =
15991                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15992                     line_ptr += bytes_read;
15993                     length =
15994                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15995                     line_ptr += bytes_read;
15996                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15997                   }
15998                   break;
15999                 case DW_LNE_set_discriminator:
16000                   /* The discriminator is not interesting to the debugger;
16001                      just ignore it.  */
16002                   line_ptr = extended_end;
16003                   break;
16004                 default:
16005                   complaint (&symfile_complaints,
16006                              _("mangled .debug_line section"));
16007                   return;
16008                 }
16009               /* Make sure that we parsed the extended op correctly.  If e.g.
16010                  we expected a different address size than the producer used,
16011                  we may have read the wrong number of bytes.  */
16012               if (line_ptr != extended_end)
16013                 {
16014                   complaint (&symfile_complaints,
16015                              _("mangled .debug_line section"));
16016                   return;
16017                 }
16018               break;
16019             case DW_LNS_copy:
16020               if (lh->num_file_names < file || file == 0)
16021                 dwarf2_debug_line_missing_file_complaint ();
16022               else
16023                 {
16024                   lh->file_names[file - 1].included_p = 1;
16025                   if (!decode_for_pst_p && is_stmt)
16026                     {
16027                       if (last_subfile != current_subfile)
16028                         {
16029                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16030                           if (last_subfile)
16031                             (*p_record_line) (last_subfile, 0, addr);
16032                           last_subfile = current_subfile;
16033                         }
16034                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16035                       (*p_record_line) (current_subfile, line, addr);
16036                     }
16037                 }
16038               basic_block = 0;
16039               break;
16040             case DW_LNS_advance_pc:
16041               {
16042                 CORE_ADDR adjust
16043                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16044
16045                 address += (((op_index + adjust)
16046                              / lh->maximum_ops_per_instruction)
16047                             * lh->minimum_instruction_length);
16048                 op_index = ((op_index + adjust)
16049                             % lh->maximum_ops_per_instruction);
16050                 line_ptr += bytes_read;
16051               }
16052               break;
16053             case DW_LNS_advance_line:
16054               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16055               line_ptr += bytes_read;
16056               break;
16057             case DW_LNS_set_file:
16058               {
16059                 /* The arrays lh->include_dirs and lh->file_names are
16060                    0-based, but the directory and file name numbers in
16061                    the statement program are 1-based.  */
16062                 struct file_entry *fe;
16063                 const char *dir = NULL;
16064
16065                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16066                 line_ptr += bytes_read;
16067                 if (lh->num_file_names < file || file == 0)
16068                   dwarf2_debug_line_missing_file_complaint ();
16069                 else
16070                   {
16071                     fe = &lh->file_names[file - 1];
16072                     if (fe->dir_index)
16073                       dir = lh->include_dirs[fe->dir_index - 1];
16074                     if (!decode_for_pst_p)
16075                       {
16076                         last_subfile = current_subfile;
16077                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16078                       }
16079                   }
16080               }
16081               break;
16082             case DW_LNS_set_column:
16083               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16084               line_ptr += bytes_read;
16085               break;
16086             case DW_LNS_negate_stmt:
16087               is_stmt = (!is_stmt);
16088               break;
16089             case DW_LNS_set_basic_block:
16090               basic_block = 1;
16091               break;
16092             /* Add to the address register of the state machine the
16093                address increment value corresponding to special opcode
16094                255.  I.e., this value is scaled by the minimum
16095                instruction length since special opcode 255 would have
16096                scaled the increment.  */
16097             case DW_LNS_const_add_pc:
16098               {
16099                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16100
16101                 address += (((op_index + adjust)
16102                              / lh->maximum_ops_per_instruction)
16103                             * lh->minimum_instruction_length);
16104                 op_index = ((op_index + adjust)
16105                             % lh->maximum_ops_per_instruction);
16106               }
16107               break;
16108             case DW_LNS_fixed_advance_pc:
16109               address += read_2_bytes (abfd, line_ptr);
16110               op_index = 0;
16111               line_ptr += 2;
16112               break;
16113             default:
16114               {
16115                 /* Unknown standard opcode, ignore it.  */
16116                 int i;
16117
16118                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16119                   {
16120                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16121                     line_ptr += bytes_read;
16122                   }
16123               }
16124             }
16125         }
16126       if (lh->num_file_names < file || file == 0)
16127         dwarf2_debug_line_missing_file_complaint ();
16128       else
16129         {
16130           lh->file_names[file - 1].included_p = 1;
16131           if (!decode_for_pst_p)
16132             {
16133               addr = gdbarch_addr_bits_remove (gdbarch, address);
16134               (*p_record_line) (current_subfile, 0, addr);
16135             }
16136         }
16137     }
16138 }
16139
16140 /* Decode the Line Number Program (LNP) for the given line_header
16141    structure and CU.  The actual information extracted and the type
16142    of structures created from the LNP depends on the value of PST.
16143
16144    1. If PST is NULL, then this procedure uses the data from the program
16145       to create all necessary symbol tables, and their linetables.
16146
16147    2. If PST is not NULL, this procedure reads the program to determine
16148       the list of files included by the unit represented by PST, and
16149       builds all the associated partial symbol tables.
16150
16151    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16152    It is used for relative paths in the line table.
16153    NOTE: When processing partial symtabs (pst != NULL),
16154    comp_dir == pst->dirname.
16155
16156    NOTE: It is important that psymtabs have the same file name (via strcmp)
16157    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
16158    symtab we don't use it in the name of the psymtabs we create.
16159    E.g. expand_line_sal requires this when finding psymtabs to expand.
16160    A good testcase for this is mb-inline.exp.  */
16161
16162 static void
16163 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
16164                     struct dwarf2_cu *cu, struct partial_symtab *pst,
16165                     int want_line_info)
16166 {
16167   struct objfile *objfile = cu->objfile;
16168   const int decode_for_pst_p = (pst != NULL);
16169   struct subfile *first_subfile = current_subfile;
16170
16171   if (want_line_info)
16172     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
16173
16174   if (decode_for_pst_p)
16175     {
16176       int file_index;
16177
16178       /* Now that we're done scanning the Line Header Program, we can
16179          create the psymtab of each included file.  */
16180       for (file_index = 0; file_index < lh->num_file_names; file_index++)
16181         if (lh->file_names[file_index].included_p == 1)
16182           {
16183             const char *include_name =
16184               psymtab_include_file_name (lh, file_index, pst, comp_dir);
16185             if (include_name != NULL)
16186               dwarf2_create_include_psymtab (include_name, pst, objfile);
16187           }
16188     }
16189   else
16190     {
16191       /* Make sure a symtab is created for every file, even files
16192          which contain only variables (i.e. no code with associated
16193          line numbers).  */
16194       int i;
16195
16196       for (i = 0; i < lh->num_file_names; i++)
16197         {
16198           const char *dir = NULL;
16199           struct file_entry *fe;
16200
16201           fe = &lh->file_names[i];
16202           if (fe->dir_index)
16203             dir = lh->include_dirs[fe->dir_index - 1];
16204           dwarf2_start_subfile (fe->name, dir, comp_dir);
16205
16206           /* Skip the main file; we don't need it, and it must be
16207              allocated last, so that it will show up before the
16208              non-primary symtabs in the objfile's symtab list.  */
16209           if (current_subfile == first_subfile)
16210             continue;
16211
16212           if (current_subfile->symtab == NULL)
16213             current_subfile->symtab = allocate_symtab (current_subfile->name,
16214                                                        objfile);
16215           fe->symtab = current_subfile->symtab;
16216         }
16217     }
16218 }
16219
16220 /* Start a subfile for DWARF.  FILENAME is the name of the file and
16221    DIRNAME the name of the source directory which contains FILENAME
16222    or NULL if not known.  COMP_DIR is the compilation directory for the
16223    linetable's compilation unit or NULL if not known.
16224    This routine tries to keep line numbers from identical absolute and
16225    relative file names in a common subfile.
16226
16227    Using the `list' example from the GDB testsuite, which resides in
16228    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
16229    of /srcdir/list0.c yields the following debugging information for list0.c:
16230
16231    DW_AT_name:          /srcdir/list0.c
16232    DW_AT_comp_dir:              /compdir
16233    files.files[0].name: list0.h
16234    files.files[0].dir:  /srcdir
16235    files.files[1].name: list0.c
16236    files.files[1].dir:  /srcdir
16237
16238    The line number information for list0.c has to end up in a single
16239    subfile, so that `break /srcdir/list0.c:1' works as expected.
16240    start_subfile will ensure that this happens provided that we pass the
16241    concatenation of files.files[1].dir and files.files[1].name as the
16242    subfile's name.  */
16243
16244 static void
16245 dwarf2_start_subfile (const char *filename, const char *dirname,
16246                       const char *comp_dir)
16247 {
16248   char *copy = NULL;
16249
16250   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
16251      `start_symtab' will always pass the contents of DW_AT_comp_dir as
16252      second argument to start_subfile.  To be consistent, we do the
16253      same here.  In order not to lose the line information directory,
16254      we concatenate it to the filename when it makes sense.
16255      Note that the Dwarf3 standard says (speaking of filenames in line
16256      information): ``The directory index is ignored for file names
16257      that represent full path names''.  Thus ignoring dirname in the
16258      `else' branch below isn't an issue.  */
16259
16260   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
16261     {
16262       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
16263       filename = copy;
16264     }
16265
16266   start_subfile (filename, comp_dir);
16267
16268   if (copy != NULL)
16269     xfree (copy);
16270 }
16271
16272 /* Start a symtab for DWARF.
16273    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
16274
16275 static void
16276 dwarf2_start_symtab (struct dwarf2_cu *cu,
16277                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
16278 {
16279   start_symtab (name, comp_dir, low_pc);
16280   record_debugformat ("DWARF 2");
16281   record_producer (cu->producer);
16282
16283   /* We assume that we're processing GCC output.  */
16284   processing_gcc_compilation = 2;
16285
16286   cu->processing_has_namespace_info = 0;
16287 }
16288
16289 static void
16290 var_decode_location (struct attribute *attr, struct symbol *sym,
16291                      struct dwarf2_cu *cu)
16292 {
16293   struct objfile *objfile = cu->objfile;
16294   struct comp_unit_head *cu_header = &cu->header;
16295
16296   /* NOTE drow/2003-01-30: There used to be a comment and some special
16297      code here to turn a symbol with DW_AT_external and a
16298      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
16299      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
16300      with some versions of binutils) where shared libraries could have
16301      relocations against symbols in their debug information - the
16302      minimal symbol would have the right address, but the debug info
16303      would not.  It's no longer necessary, because we will explicitly
16304      apply relocations when we read in the debug information now.  */
16305
16306   /* A DW_AT_location attribute with no contents indicates that a
16307      variable has been optimized away.  */
16308   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
16309     {
16310       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16311       return;
16312     }
16313
16314   /* Handle one degenerate form of location expression specially, to
16315      preserve GDB's previous behavior when section offsets are
16316      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
16317      then mark this symbol as LOC_STATIC.  */
16318
16319   if (attr_form_is_block (attr)
16320       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
16321            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
16322           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
16323               && (DW_BLOCK (attr)->size
16324                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
16325     {
16326       unsigned int dummy;
16327
16328       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
16329         SYMBOL_VALUE_ADDRESS (sym) =
16330           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
16331       else
16332         SYMBOL_VALUE_ADDRESS (sym) =
16333           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
16334       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
16335       fixup_symbol_section (sym, objfile);
16336       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
16337                                               SYMBOL_SECTION (sym));
16338       return;
16339     }
16340
16341   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
16342      expression evaluator, and use LOC_COMPUTED only when necessary
16343      (i.e. when the value of a register or memory location is
16344      referenced, or a thread-local block, etc.).  Then again, it might
16345      not be worthwhile.  I'm assuming that it isn't unless performance
16346      or memory numbers show me otherwise.  */
16347
16348   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
16349
16350   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
16351     cu->has_loclist = 1;
16352 }
16353
16354 /* Given a pointer to a DWARF information entry, figure out if we need
16355    to make a symbol table entry for it, and if so, create a new entry
16356    and return a pointer to it.
16357    If TYPE is NULL, determine symbol type from the die, otherwise
16358    used the passed type.
16359    If SPACE is not NULL, use it to hold the new symbol.  If it is
16360    NULL, allocate a new symbol on the objfile's obstack.  */
16361
16362 static struct symbol *
16363 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
16364                  struct symbol *space)
16365 {
16366   struct objfile *objfile = cu->objfile;
16367   struct symbol *sym = NULL;
16368   const char *name;
16369   struct attribute *attr = NULL;
16370   struct attribute *attr2 = NULL;
16371   CORE_ADDR baseaddr;
16372   struct pending **list_to_add = NULL;
16373
16374   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
16375
16376   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16377
16378   name = dwarf2_name (die, cu);
16379   if (name)
16380     {
16381       const char *linkagename;
16382       int suppress_add = 0;
16383
16384       if (space)
16385         sym = space;
16386       else
16387         sym = allocate_symbol (objfile);
16388       OBJSTAT (objfile, n_syms++);
16389
16390       /* Cache this symbol's name and the name's demangled form (if any).  */
16391       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
16392       linkagename = dwarf2_physname (name, die, cu);
16393       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
16394
16395       /* Fortran does not have mangling standard and the mangling does differ
16396          between gfortran, iFort etc.  */
16397       if (cu->language == language_fortran
16398           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
16399         symbol_set_demangled_name (&(sym->ginfo),
16400                                    dwarf2_full_name (name, die, cu),
16401                                    NULL);
16402
16403       /* Default assumptions.
16404          Use the passed type or decode it from the die.  */
16405       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16406       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
16407       if (type != NULL)
16408         SYMBOL_TYPE (sym) = type;
16409       else
16410         SYMBOL_TYPE (sym) = die_type (die, cu);
16411       attr = dwarf2_attr (die,
16412                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16413                           cu);
16414       if (attr)
16415         {
16416           SYMBOL_LINE (sym) = DW_UNSND (attr);
16417         }
16418
16419       attr = dwarf2_attr (die,
16420                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16421                           cu);
16422       if (attr)
16423         {
16424           int file_index = DW_UNSND (attr);
16425
16426           if (cu->line_header == NULL
16427               || file_index > cu->line_header->num_file_names)
16428             complaint (&symfile_complaints,
16429                        _("file index out of range"));
16430           else if (file_index > 0)
16431             {
16432               struct file_entry *fe;
16433
16434               fe = &cu->line_header->file_names[file_index - 1];
16435               SYMBOL_SYMTAB (sym) = fe->symtab;
16436             }
16437         }
16438
16439       switch (die->tag)
16440         {
16441         case DW_TAG_label:
16442           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16443           if (attr)
16444             {
16445               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16446             }
16447           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16448           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16449           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16450           add_symbol_to_list (sym, cu->list_in_scope);
16451           break;
16452         case DW_TAG_subprogram:
16453           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16454              finish_block.  */
16455           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16456           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16457           if ((attr2 && (DW_UNSND (attr2) != 0))
16458               || cu->language == language_ada)
16459             {
16460               /* Subprograms marked external are stored as a global symbol.
16461                  Ada subprograms, whether marked external or not, are always
16462                  stored as a global symbol, because we want to be able to
16463                  access them globally.  For instance, we want to be able
16464                  to break on a nested subprogram without having to
16465                  specify the context.  */
16466               list_to_add = &global_symbols;
16467             }
16468           else
16469             {
16470               list_to_add = cu->list_in_scope;
16471             }
16472           break;
16473         case DW_TAG_inlined_subroutine:
16474           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16475              finish_block.  */
16476           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16477           SYMBOL_INLINED (sym) = 1;
16478           list_to_add = cu->list_in_scope;
16479           break;
16480         case DW_TAG_template_value_param:
16481           suppress_add = 1;
16482           /* Fall through.  */
16483         case DW_TAG_constant:
16484         case DW_TAG_variable:
16485         case DW_TAG_member:
16486           /* Compilation with minimal debug info may result in
16487              variables with missing type entries.  Change the
16488              misleading `void' type to something sensible.  */
16489           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16490             SYMBOL_TYPE (sym)
16491               = objfile_type (objfile)->nodebug_data_symbol;
16492
16493           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16494           /* In the case of DW_TAG_member, we should only be called for
16495              static const members.  */
16496           if (die->tag == DW_TAG_member)
16497             {
16498               /* dwarf2_add_field uses die_is_declaration,
16499                  so we do the same.  */
16500               gdb_assert (die_is_declaration (die, cu));
16501               gdb_assert (attr);
16502             }
16503           if (attr)
16504             {
16505               dwarf2_const_value (attr, sym, cu);
16506               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16507               if (!suppress_add)
16508                 {
16509                   if (attr2 && (DW_UNSND (attr2) != 0))
16510                     list_to_add = &global_symbols;
16511                   else
16512                     list_to_add = cu->list_in_scope;
16513                 }
16514               break;
16515             }
16516           attr = dwarf2_attr (die, DW_AT_location, cu);
16517           if (attr)
16518             {
16519               var_decode_location (attr, sym, cu);
16520               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16521
16522               /* Fortran explicitly imports any global symbols to the local
16523                  scope by DW_TAG_common_block.  */
16524               if (cu->language == language_fortran && die->parent
16525                   && die->parent->tag == DW_TAG_common_block)
16526                 attr2 = NULL;
16527
16528               if (SYMBOL_CLASS (sym) == LOC_STATIC
16529                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16530                   && !dwarf2_per_objfile->has_section_at_zero)
16531                 {
16532                   /* When a static variable is eliminated by the linker,
16533                      the corresponding debug information is not stripped
16534                      out, but the variable address is set to null;
16535                      do not add such variables into symbol table.  */
16536                 }
16537               else if (attr2 && (DW_UNSND (attr2) != 0))
16538                 {
16539                   /* Workaround gfortran PR debug/40040 - it uses
16540                      DW_AT_location for variables in -fPIC libraries which may
16541                      get overriden by other libraries/executable and get
16542                      a different address.  Resolve it by the minimal symbol
16543                      which may come from inferior's executable using copy
16544                      relocation.  Make this workaround only for gfortran as for
16545                      other compilers GDB cannot guess the minimal symbol
16546                      Fortran mangling kind.  */
16547                   if (cu->language == language_fortran && die->parent
16548                       && die->parent->tag == DW_TAG_module
16549                       && cu->producer
16550                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16551                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16552
16553                   /* A variable with DW_AT_external is never static,
16554                      but it may be block-scoped.  */
16555                   list_to_add = (cu->list_in_scope == &file_symbols
16556                                  ? &global_symbols : cu->list_in_scope);
16557                 }
16558               else
16559                 list_to_add = cu->list_in_scope;
16560             }
16561           else
16562             {
16563               /* We do not know the address of this symbol.
16564                  If it is an external symbol and we have type information
16565                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16566                  The address of the variable will then be determined from
16567                  the minimal symbol table whenever the variable is
16568                  referenced.  */
16569               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16570
16571               /* Fortran explicitly imports any global symbols to the local
16572                  scope by DW_TAG_common_block.  */
16573               if (cu->language == language_fortran && die->parent
16574                   && die->parent->tag == DW_TAG_common_block)
16575                 {
16576                   /* SYMBOL_CLASS doesn't matter here because
16577                      read_common_block is going to reset it.  */
16578                   if (!suppress_add)
16579                     list_to_add = cu->list_in_scope;
16580                 }
16581               else if (attr2 && (DW_UNSND (attr2) != 0)
16582                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16583                 {
16584                   /* A variable with DW_AT_external is never static, but it
16585                      may be block-scoped.  */
16586                   list_to_add = (cu->list_in_scope == &file_symbols
16587                                  ? &global_symbols : cu->list_in_scope);
16588
16589                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16590                 }
16591               else if (!die_is_declaration (die, cu))
16592                 {
16593                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16594                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16595                   if (!suppress_add)
16596                     list_to_add = cu->list_in_scope;
16597                 }
16598             }
16599           break;
16600         case DW_TAG_formal_parameter:
16601           /* If we are inside a function, mark this as an argument.  If
16602              not, we might be looking at an argument to an inlined function
16603              when we do not have enough information to show inlined frames;
16604              pretend it's a local variable in that case so that the user can
16605              still see it.  */
16606           if (context_stack_depth > 0
16607               && context_stack[context_stack_depth - 1].name != NULL)
16608             SYMBOL_IS_ARGUMENT (sym) = 1;
16609           attr = dwarf2_attr (die, DW_AT_location, cu);
16610           if (attr)
16611             {
16612               var_decode_location (attr, sym, cu);
16613             }
16614           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16615           if (attr)
16616             {
16617               dwarf2_const_value (attr, sym, cu);
16618             }
16619
16620           list_to_add = cu->list_in_scope;
16621           break;
16622         case DW_TAG_unspecified_parameters:
16623           /* From varargs functions; gdb doesn't seem to have any
16624              interest in this information, so just ignore it for now.
16625              (FIXME?) */
16626           break;
16627         case DW_TAG_template_type_param:
16628           suppress_add = 1;
16629           /* Fall through.  */
16630         case DW_TAG_class_type:
16631         case DW_TAG_interface_type:
16632         case DW_TAG_structure_type:
16633         case DW_TAG_union_type:
16634         case DW_TAG_set_type:
16635         case DW_TAG_enumeration_type:
16636           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16637           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16638
16639           {
16640             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16641                really ever be static objects: otherwise, if you try
16642                to, say, break of a class's method and you're in a file
16643                which doesn't mention that class, it won't work unless
16644                the check for all static symbols in lookup_symbol_aux
16645                saves you.  See the OtherFileClass tests in
16646                gdb.c++/namespace.exp.  */
16647
16648             if (!suppress_add)
16649               {
16650                 list_to_add = (cu->list_in_scope == &file_symbols
16651                                && (cu->language == language_cplus
16652                                    || cu->language == language_java)
16653                                ? &global_symbols : cu->list_in_scope);
16654
16655                 /* The semantics of C++ state that "struct foo {
16656                    ... }" also defines a typedef for "foo".  A Java
16657                    class declaration also defines a typedef for the
16658                    class.  */
16659                 if (cu->language == language_cplus
16660                     || cu->language == language_java
16661                     || cu->language == language_ada)
16662                   {
16663                     /* The symbol's name is already allocated along
16664                        with this objfile, so we don't need to
16665                        duplicate it for the type.  */
16666                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16667                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16668                   }
16669               }
16670           }
16671           break;
16672         case DW_TAG_typedef:
16673           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16674           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16675           list_to_add = cu->list_in_scope;
16676           break;
16677         case DW_TAG_base_type:
16678         case DW_TAG_subrange_type:
16679           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16680           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16681           list_to_add = cu->list_in_scope;
16682           break;
16683         case DW_TAG_enumerator:
16684           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16685           if (attr)
16686             {
16687               dwarf2_const_value (attr, sym, cu);
16688             }
16689           {
16690             /* NOTE: carlton/2003-11-10: See comment above in the
16691                DW_TAG_class_type, etc. block.  */
16692
16693             list_to_add = (cu->list_in_scope == &file_symbols
16694                            && (cu->language == language_cplus
16695                                || cu->language == language_java)
16696                            ? &global_symbols : cu->list_in_scope);
16697           }
16698           break;
16699         case DW_TAG_namespace:
16700           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16701           list_to_add = &global_symbols;
16702           break;
16703         case DW_TAG_common_block:
16704           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16705           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16706           add_symbol_to_list (sym, cu->list_in_scope);
16707           break;
16708         default:
16709           /* Not a tag we recognize.  Hopefully we aren't processing
16710              trash data, but since we must specifically ignore things
16711              we don't recognize, there is nothing else we should do at
16712              this point.  */
16713           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16714                      dwarf_tag_name (die->tag));
16715           break;
16716         }
16717
16718       if (suppress_add)
16719         {
16720           sym->hash_next = objfile->template_symbols;
16721           objfile->template_symbols = sym;
16722           list_to_add = NULL;
16723         }
16724
16725       if (list_to_add != NULL)
16726         add_symbol_to_list (sym, list_to_add);
16727
16728       /* For the benefit of old versions of GCC, check for anonymous
16729          namespaces based on the demangled name.  */
16730       if (!cu->processing_has_namespace_info
16731           && cu->language == language_cplus)
16732         cp_scan_for_anonymous_namespaces (sym, objfile);
16733     }
16734   return (sym);
16735 }
16736
16737 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16738
16739 static struct symbol *
16740 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16741 {
16742   return new_symbol_full (die, type, cu, NULL);
16743 }
16744
16745 /* Given an attr with a DW_FORM_dataN value in host byte order,
16746    zero-extend it as appropriate for the symbol's type.  The DWARF
16747    standard (v4) is not entirely clear about the meaning of using
16748    DW_FORM_dataN for a constant with a signed type, where the type is
16749    wider than the data.  The conclusion of a discussion on the DWARF
16750    list was that this is unspecified.  We choose to always zero-extend
16751    because that is the interpretation long in use by GCC.  */
16752
16753 static gdb_byte *
16754 dwarf2_const_value_data (struct attribute *attr, struct obstack *obstack,
16755                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16756 {
16757   struct objfile *objfile = cu->objfile;
16758   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16759                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16760   LONGEST l = DW_UNSND (attr);
16761
16762   if (bits < sizeof (*value) * 8)
16763     {
16764       l &= ((LONGEST) 1 << bits) - 1;
16765       *value = l;
16766     }
16767   else if (bits == sizeof (*value) * 8)
16768     *value = l;
16769   else
16770     {
16771       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16772       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16773       return bytes;
16774     }
16775
16776   return NULL;
16777 }
16778
16779 /* Read a constant value from an attribute.  Either set *VALUE, or if
16780    the value does not fit in *VALUE, set *BYTES - either already
16781    allocated on the objfile obstack, or newly allocated on OBSTACK,
16782    or, set *BATON, if we translated the constant to a location
16783    expression.  */
16784
16785 static void
16786 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16787                          const char *name, struct obstack *obstack,
16788                          struct dwarf2_cu *cu,
16789                          LONGEST *value, const gdb_byte **bytes,
16790                          struct dwarf2_locexpr_baton **baton)
16791 {
16792   struct objfile *objfile = cu->objfile;
16793   struct comp_unit_head *cu_header = &cu->header;
16794   struct dwarf_block *blk;
16795   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16796                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16797
16798   *value = 0;
16799   *bytes = NULL;
16800   *baton = NULL;
16801
16802   switch (attr->form)
16803     {
16804     case DW_FORM_addr:
16805     case DW_FORM_GNU_addr_index:
16806       {
16807         gdb_byte *data;
16808
16809         if (TYPE_LENGTH (type) != cu_header->addr_size)
16810           dwarf2_const_value_length_mismatch_complaint (name,
16811                                                         cu_header->addr_size,
16812                                                         TYPE_LENGTH (type));
16813         /* Symbols of this form are reasonably rare, so we just
16814            piggyback on the existing location code rather than writing
16815            a new implementation of symbol_computed_ops.  */
16816         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
16817         (*baton)->per_cu = cu->per_cu;
16818         gdb_assert ((*baton)->per_cu);
16819
16820         (*baton)->size = 2 + cu_header->addr_size;
16821         data = obstack_alloc (obstack, (*baton)->size);
16822         (*baton)->data = data;
16823
16824         data[0] = DW_OP_addr;
16825         store_unsigned_integer (&data[1], cu_header->addr_size,
16826                                 byte_order, DW_ADDR (attr));
16827         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16828       }
16829       break;
16830     case DW_FORM_string:
16831     case DW_FORM_strp:
16832     case DW_FORM_GNU_str_index:
16833     case DW_FORM_GNU_strp_alt:
16834       /* DW_STRING is already allocated on the objfile obstack, point
16835          directly to it.  */
16836       *bytes = (const gdb_byte *) DW_STRING (attr);
16837       break;
16838     case DW_FORM_block1:
16839     case DW_FORM_block2:
16840     case DW_FORM_block4:
16841     case DW_FORM_block:
16842     case DW_FORM_exprloc:
16843       blk = DW_BLOCK (attr);
16844       if (TYPE_LENGTH (type) != blk->size)
16845         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16846                                                       TYPE_LENGTH (type));
16847       *bytes = blk->data;
16848       break;
16849
16850       /* The DW_AT_const_value attributes are supposed to carry the
16851          symbol's value "represented as it would be on the target
16852          architecture."  By the time we get here, it's already been
16853          converted to host endianness, so we just need to sign- or
16854          zero-extend it as appropriate.  */
16855     case DW_FORM_data1:
16856       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
16857       break;
16858     case DW_FORM_data2:
16859       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
16860       break;
16861     case DW_FORM_data4:
16862       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
16863       break;
16864     case DW_FORM_data8:
16865       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
16866       break;
16867
16868     case DW_FORM_sdata:
16869       *value = DW_SND (attr);
16870       break;
16871
16872     case DW_FORM_udata:
16873       *value = DW_UNSND (attr);
16874       break;
16875
16876     default:
16877       complaint (&symfile_complaints,
16878                  _("unsupported const value attribute form: '%s'"),
16879                  dwarf_form_name (attr->form));
16880       *value = 0;
16881       break;
16882     }
16883 }
16884
16885
16886 /* Copy constant value from an attribute to a symbol.  */
16887
16888 static void
16889 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16890                     struct dwarf2_cu *cu)
16891 {
16892   struct objfile *objfile = cu->objfile;
16893   struct comp_unit_head *cu_header = &cu->header;
16894   LONGEST value;
16895   const gdb_byte *bytes;
16896   struct dwarf2_locexpr_baton *baton;
16897
16898   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16899                            SYMBOL_PRINT_NAME (sym),
16900                            &objfile->objfile_obstack, cu,
16901                            &value, &bytes, &baton);
16902
16903   if (baton != NULL)
16904     {
16905       SYMBOL_LOCATION_BATON (sym) = baton;
16906       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16907     }
16908   else if (bytes != NULL)
16909      {
16910       SYMBOL_VALUE_BYTES (sym) = bytes;
16911       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16912     }
16913   else
16914     {
16915       SYMBOL_VALUE (sym) = value;
16916       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16917     }
16918 }
16919
16920 /* Return the type of the die in question using its DW_AT_type attribute.  */
16921
16922 static struct type *
16923 die_type (struct die_info *die, struct dwarf2_cu *cu)
16924 {
16925   struct attribute *type_attr;
16926
16927   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16928   if (!type_attr)
16929     {
16930       /* A missing DW_AT_type represents a void type.  */
16931       return objfile_type (cu->objfile)->builtin_void;
16932     }
16933
16934   return lookup_die_type (die, type_attr, cu);
16935 }
16936
16937 /* True iff CU's producer generates GNAT Ada auxiliary information
16938    that allows to find parallel types through that information instead
16939    of having to do expensive parallel lookups by type name.  */
16940
16941 static int
16942 need_gnat_info (struct dwarf2_cu *cu)
16943 {
16944   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16945      of GNAT produces this auxiliary information, without any indication
16946      that it is produced.  Part of enhancing the FSF version of GNAT
16947      to produce that information will be to put in place an indicator
16948      that we can use in order to determine whether the descriptive type
16949      info is available or not.  One suggestion that has been made is
16950      to use a new attribute, attached to the CU die.  For now, assume
16951      that the descriptive type info is not available.  */
16952   return 0;
16953 }
16954
16955 /* Return the auxiliary type of the die in question using its
16956    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16957    attribute is not present.  */
16958
16959 static struct type *
16960 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16961 {
16962   struct attribute *type_attr;
16963
16964   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16965   if (!type_attr)
16966     return NULL;
16967
16968   return lookup_die_type (die, type_attr, cu);
16969 }
16970
16971 /* If DIE has a descriptive_type attribute, then set the TYPE's
16972    descriptive type accordingly.  */
16973
16974 static void
16975 set_descriptive_type (struct type *type, struct die_info *die,
16976                       struct dwarf2_cu *cu)
16977 {
16978   struct type *descriptive_type = die_descriptive_type (die, cu);
16979
16980   if (descriptive_type)
16981     {
16982       ALLOCATE_GNAT_AUX_TYPE (type);
16983       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16984     }
16985 }
16986
16987 /* Return the containing type of the die in question using its
16988    DW_AT_containing_type attribute.  */
16989
16990 static struct type *
16991 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16992 {
16993   struct attribute *type_attr;
16994
16995   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16996   if (!type_attr)
16997     error (_("Dwarf Error: Problem turning containing type into gdb type "
16998              "[in module %s]"), cu->objfile->name);
16999
17000   return lookup_die_type (die, type_attr, cu);
17001 }
17002
17003 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17004
17005 static struct type *
17006 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17007 {
17008   struct objfile *objfile = dwarf2_per_objfile->objfile;
17009   char *message, *saved;
17010
17011   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17012                         objfile->name,
17013                         cu->header.offset.sect_off,
17014                         die->offset.sect_off);
17015   saved = obstack_copy0 (&objfile->objfile_obstack,
17016                          message, strlen (message));
17017   xfree (message);
17018
17019   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17020 }
17021
17022 /* Look up the type of DIE in CU using its type attribute ATTR.
17023    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17024    DW_AT_containing_type.
17025    If there is no type substitute an error marker.  */
17026
17027 static struct type *
17028 lookup_die_type (struct die_info *die, struct attribute *attr,
17029                  struct dwarf2_cu *cu)
17030 {
17031   struct objfile *objfile = cu->objfile;
17032   struct type *this_type;
17033
17034   gdb_assert (attr->name == DW_AT_type
17035               || attr->name == DW_AT_GNAT_descriptive_type
17036               || attr->name == DW_AT_containing_type);
17037
17038   /* First see if we have it cached.  */
17039
17040   if (attr->form == DW_FORM_GNU_ref_alt)
17041     {
17042       struct dwarf2_per_cu_data *per_cu;
17043       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17044
17045       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17046       this_type = get_die_type_at_offset (offset, per_cu);
17047     }
17048   else if (is_ref_attr (attr))
17049     {
17050       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17051
17052       this_type = get_die_type_at_offset (offset, cu->per_cu);
17053     }
17054   else if (attr->form == DW_FORM_ref_sig8)
17055     {
17056       ULONGEST signature = DW_SIGNATURE (attr);
17057
17058       return get_signatured_type (die, signature, cu);
17059     }
17060   else
17061     {
17062       complaint (&symfile_complaints,
17063                  _("Dwarf Error: Bad type attribute %s in DIE"
17064                    " at 0x%x [in module %s]"),
17065                  dwarf_attr_name (attr->name), die->offset.sect_off,
17066                  objfile->name);
17067       return build_error_marker_type (cu, die);
17068     }
17069
17070   /* If not cached we need to read it in.  */
17071
17072   if (this_type == NULL)
17073     {
17074       struct die_info *type_die = NULL;
17075       struct dwarf2_cu *type_cu = cu;
17076
17077       if (is_ref_attr (attr))
17078         type_die = follow_die_ref (die, attr, &type_cu);
17079       if (type_die == NULL)
17080         return build_error_marker_type (cu, die);
17081       /* If we find the type now, it's probably because the type came
17082          from an inter-CU reference and the type's CU got expanded before
17083          ours.  */
17084       this_type = read_type_die (type_die, type_cu);
17085     }
17086
17087   /* If we still don't have a type use an error marker.  */
17088
17089   if (this_type == NULL)
17090     return build_error_marker_type (cu, die);
17091
17092   return this_type;
17093 }
17094
17095 /* Return the type in DIE, CU.
17096    Returns NULL for invalid types.
17097
17098    This first does a lookup in die_type_hash,
17099    and only reads the die in if necessary.
17100
17101    NOTE: This can be called when reading in partial or full symbols.  */
17102
17103 static struct type *
17104 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17105 {
17106   struct type *this_type;
17107
17108   this_type = get_die_type (die, cu);
17109   if (this_type)
17110     return this_type;
17111
17112   return read_type_die_1 (die, cu);
17113 }
17114
17115 /* Read the type in DIE, CU.
17116    Returns NULL for invalid types.  */
17117
17118 static struct type *
17119 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17120 {
17121   struct type *this_type = NULL;
17122
17123   switch (die->tag)
17124     {
17125     case DW_TAG_class_type:
17126     case DW_TAG_interface_type:
17127     case DW_TAG_structure_type:
17128     case DW_TAG_union_type:
17129       this_type = read_structure_type (die, cu);
17130       break;
17131     case DW_TAG_enumeration_type:
17132       this_type = read_enumeration_type (die, cu);
17133       break;
17134     case DW_TAG_subprogram:
17135     case DW_TAG_subroutine_type:
17136     case DW_TAG_inlined_subroutine:
17137       this_type = read_subroutine_type (die, cu);
17138       break;
17139     case DW_TAG_array_type:
17140       this_type = read_array_type (die, cu);
17141       break;
17142     case DW_TAG_set_type:
17143       this_type = read_set_type (die, cu);
17144       break;
17145     case DW_TAG_pointer_type:
17146       this_type = read_tag_pointer_type (die, cu);
17147       break;
17148     case DW_TAG_ptr_to_member_type:
17149       this_type = read_tag_ptr_to_member_type (die, cu);
17150       break;
17151     case DW_TAG_reference_type:
17152       this_type = read_tag_reference_type (die, cu);
17153       break;
17154     case DW_TAG_const_type:
17155       this_type = read_tag_const_type (die, cu);
17156       break;
17157     case DW_TAG_volatile_type:
17158       this_type = read_tag_volatile_type (die, cu);
17159       break;
17160     case DW_TAG_restrict_type:
17161       this_type = read_tag_restrict_type (die, cu);
17162       break;
17163     case DW_TAG_string_type:
17164       this_type = read_tag_string_type (die, cu);
17165       break;
17166     case DW_TAG_typedef:
17167       this_type = read_typedef (die, cu);
17168       break;
17169     case DW_TAG_subrange_type:
17170       this_type = read_subrange_type (die, cu);
17171       break;
17172     case DW_TAG_base_type:
17173       this_type = read_base_type (die, cu);
17174       break;
17175     case DW_TAG_unspecified_type:
17176       this_type = read_unspecified_type (die, cu);
17177       break;
17178     case DW_TAG_namespace:
17179       this_type = read_namespace_type (die, cu);
17180       break;
17181     case DW_TAG_module:
17182       this_type = read_module_type (die, cu);
17183       break;
17184     default:
17185       complaint (&symfile_complaints,
17186                  _("unexpected tag in read_type_die: '%s'"),
17187                  dwarf_tag_name (die->tag));
17188       break;
17189     }
17190
17191   return this_type;
17192 }
17193
17194 /* See if we can figure out if the class lives in a namespace.  We do
17195    this by looking for a member function; its demangled name will
17196    contain namespace info, if there is any.
17197    Return the computed name or NULL.
17198    Space for the result is allocated on the objfile's obstack.
17199    This is the full-die version of guess_partial_die_structure_name.
17200    In this case we know DIE has no useful parent.  */
17201
17202 static char *
17203 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
17204 {
17205   struct die_info *spec_die;
17206   struct dwarf2_cu *spec_cu;
17207   struct die_info *child;
17208
17209   spec_cu = cu;
17210   spec_die = die_specification (die, &spec_cu);
17211   if (spec_die != NULL)
17212     {
17213       die = spec_die;
17214       cu = spec_cu;
17215     }
17216
17217   for (child = die->child;
17218        child != NULL;
17219        child = child->sibling)
17220     {
17221       if (child->tag == DW_TAG_subprogram)
17222         {
17223           struct attribute *attr;
17224
17225           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
17226           if (attr == NULL)
17227             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
17228           if (attr != NULL)
17229             {
17230               char *actual_name
17231                 = language_class_name_from_physname (cu->language_defn,
17232                                                      DW_STRING (attr));
17233               char *name = NULL;
17234
17235               if (actual_name != NULL)
17236                 {
17237                   const char *die_name = dwarf2_name (die, cu);
17238
17239                   if (die_name != NULL
17240                       && strcmp (die_name, actual_name) != 0)
17241                     {
17242                       /* Strip off the class name from the full name.
17243                          We want the prefix.  */
17244                       int die_name_len = strlen (die_name);
17245                       int actual_name_len = strlen (actual_name);
17246
17247                       /* Test for '::' as a sanity check.  */
17248                       if (actual_name_len > die_name_len + 2
17249                           && actual_name[actual_name_len
17250                                          - die_name_len - 1] == ':')
17251                         name =
17252                           obstack_copy0 (&cu->objfile->objfile_obstack,
17253                                          actual_name,
17254                                          actual_name_len - die_name_len - 2);
17255                     }
17256                 }
17257               xfree (actual_name);
17258               return name;
17259             }
17260         }
17261     }
17262
17263   return NULL;
17264 }
17265
17266 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
17267    prefix part in such case.  See
17268    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17269
17270 static char *
17271 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
17272 {
17273   struct attribute *attr;
17274   char *base;
17275
17276   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
17277       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
17278     return NULL;
17279
17280   attr = dwarf2_attr (die, DW_AT_name, cu);
17281   if (attr != NULL && DW_STRING (attr) != NULL)
17282     return NULL;
17283
17284   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17285   if (attr == NULL)
17286     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17287   if (attr == NULL || DW_STRING (attr) == NULL)
17288     return NULL;
17289
17290   /* dwarf2_name had to be already called.  */
17291   gdb_assert (DW_STRING_IS_CANONICAL (attr));
17292
17293   /* Strip the base name, keep any leading namespaces/classes.  */
17294   base = strrchr (DW_STRING (attr), ':');
17295   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
17296     return "";
17297
17298   return obstack_copy0 (&cu->objfile->objfile_obstack,
17299                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
17300 }
17301
17302 /* Return the name of the namespace/class that DIE is defined within,
17303    or "" if we can't tell.  The caller should not xfree the result.
17304
17305    For example, if we're within the method foo() in the following
17306    code:
17307
17308    namespace N {
17309      class C {
17310        void foo () {
17311        }
17312      };
17313    }
17314
17315    then determine_prefix on foo's die will return "N::C".  */
17316
17317 static const char *
17318 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
17319 {
17320   struct die_info *parent, *spec_die;
17321   struct dwarf2_cu *spec_cu;
17322   struct type *parent_type;
17323   char *retval;
17324
17325   if (cu->language != language_cplus && cu->language != language_java
17326       && cu->language != language_fortran)
17327     return "";
17328
17329   retval = anonymous_struct_prefix (die, cu);
17330   if (retval)
17331     return retval;
17332
17333   /* We have to be careful in the presence of DW_AT_specification.
17334      For example, with GCC 3.4, given the code
17335
17336      namespace N {
17337        void foo() {
17338          // Definition of N::foo.
17339        }
17340      }
17341
17342      then we'll have a tree of DIEs like this:
17343
17344      1: DW_TAG_compile_unit
17345        2: DW_TAG_namespace        // N
17346          3: DW_TAG_subprogram     // declaration of N::foo
17347        4: DW_TAG_subprogram       // definition of N::foo
17348             DW_AT_specification   // refers to die #3
17349
17350      Thus, when processing die #4, we have to pretend that we're in
17351      the context of its DW_AT_specification, namely the contex of die
17352      #3.  */
17353   spec_cu = cu;
17354   spec_die = die_specification (die, &spec_cu);
17355   if (spec_die == NULL)
17356     parent = die->parent;
17357   else
17358     {
17359       parent = spec_die->parent;
17360       cu = spec_cu;
17361     }
17362
17363   if (parent == NULL)
17364     return "";
17365   else if (parent->building_fullname)
17366     {
17367       const char *name;
17368       const char *parent_name;
17369
17370       /* It has been seen on RealView 2.2 built binaries,
17371          DW_TAG_template_type_param types actually _defined_ as
17372          children of the parent class:
17373
17374          enum E {};
17375          template class <class Enum> Class{};
17376          Class<enum E> class_e;
17377
17378          1: DW_TAG_class_type (Class)
17379            2: DW_TAG_enumeration_type (E)
17380              3: DW_TAG_enumerator (enum1:0)
17381              3: DW_TAG_enumerator (enum2:1)
17382              ...
17383            2: DW_TAG_template_type_param
17384               DW_AT_type  DW_FORM_ref_udata (E)
17385
17386          Besides being broken debug info, it can put GDB into an
17387          infinite loop.  Consider:
17388
17389          When we're building the full name for Class<E>, we'll start
17390          at Class, and go look over its template type parameters,
17391          finding E.  We'll then try to build the full name of E, and
17392          reach here.  We're now trying to build the full name of E,
17393          and look over the parent DIE for containing scope.  In the
17394          broken case, if we followed the parent DIE of E, we'd again
17395          find Class, and once again go look at its template type
17396          arguments, etc., etc.  Simply don't consider such parent die
17397          as source-level parent of this die (it can't be, the language
17398          doesn't allow it), and break the loop here.  */
17399       name = dwarf2_name (die, cu);
17400       parent_name = dwarf2_name (parent, cu);
17401       complaint (&symfile_complaints,
17402                  _("template param type '%s' defined within parent '%s'"),
17403                  name ? name : "<unknown>",
17404                  parent_name ? parent_name : "<unknown>");
17405       return "";
17406     }
17407   else
17408     switch (parent->tag)
17409       {
17410       case DW_TAG_namespace:
17411         parent_type = read_type_die (parent, cu);
17412         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17413            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17414            Work around this problem here.  */
17415         if (cu->language == language_cplus
17416             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17417           return "";
17418         /* We give a name to even anonymous namespaces.  */
17419         return TYPE_TAG_NAME (parent_type);
17420       case DW_TAG_class_type:
17421       case DW_TAG_interface_type:
17422       case DW_TAG_structure_type:
17423       case DW_TAG_union_type:
17424       case DW_TAG_module:
17425         parent_type = read_type_die (parent, cu);
17426         if (TYPE_TAG_NAME (parent_type) != NULL)
17427           return TYPE_TAG_NAME (parent_type);
17428         else
17429           /* An anonymous structure is only allowed non-static data
17430              members; no typedefs, no member functions, et cetera.
17431              So it does not need a prefix.  */
17432           return "";
17433       case DW_TAG_compile_unit:
17434       case DW_TAG_partial_unit:
17435         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17436         if (cu->language == language_cplus
17437             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17438             && die->child != NULL
17439             && (die->tag == DW_TAG_class_type
17440                 || die->tag == DW_TAG_structure_type
17441                 || die->tag == DW_TAG_union_type))
17442           {
17443             char *name = guess_full_die_structure_name (die, cu);
17444             if (name != NULL)
17445               return name;
17446           }
17447         return "";
17448       default:
17449         return determine_prefix (parent, cu);
17450       }
17451 }
17452
17453 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17454    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17455    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17456    an obconcat, otherwise allocate storage for the result.  The CU argument is
17457    used to determine the language and hence, the appropriate separator.  */
17458
17459 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17460
17461 static char *
17462 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17463                  int physname, struct dwarf2_cu *cu)
17464 {
17465   const char *lead = "";
17466   const char *sep;
17467
17468   if (suffix == NULL || suffix[0] == '\0'
17469       || prefix == NULL || prefix[0] == '\0')
17470     sep = "";
17471   else if (cu->language == language_java)
17472     sep = ".";
17473   else if (cu->language == language_fortran && physname)
17474     {
17475       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17476          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17477
17478       lead = "__";
17479       sep = "_MOD_";
17480     }
17481   else
17482     sep = "::";
17483
17484   if (prefix == NULL)
17485     prefix = "";
17486   if (suffix == NULL)
17487     suffix = "";
17488
17489   if (obs == NULL)
17490     {
17491       char *retval
17492         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17493
17494       strcpy (retval, lead);
17495       strcat (retval, prefix);
17496       strcat (retval, sep);
17497       strcat (retval, suffix);
17498       return retval;
17499     }
17500   else
17501     {
17502       /* We have an obstack.  */
17503       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17504     }
17505 }
17506
17507 /* Return sibling of die, NULL if no sibling.  */
17508
17509 static struct die_info *
17510 sibling_die (struct die_info *die)
17511 {
17512   return die->sibling;
17513 }
17514
17515 /* Get name of a die, return NULL if not found.  */
17516
17517 static const char *
17518 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17519                           struct obstack *obstack)
17520 {
17521   if (name && cu->language == language_cplus)
17522     {
17523       char *canon_name = cp_canonicalize_string (name);
17524
17525       if (canon_name != NULL)
17526         {
17527           if (strcmp (canon_name, name) != 0)
17528             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17529           xfree (canon_name);
17530         }
17531     }
17532
17533   return name;
17534 }
17535
17536 /* Get name of a die, return NULL if not found.  */
17537
17538 static const char *
17539 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17540 {
17541   struct attribute *attr;
17542
17543   attr = dwarf2_attr (die, DW_AT_name, cu);
17544   if ((!attr || !DW_STRING (attr))
17545       && die->tag != DW_TAG_class_type
17546       && die->tag != DW_TAG_interface_type
17547       && die->tag != DW_TAG_structure_type
17548       && die->tag != DW_TAG_union_type)
17549     return NULL;
17550
17551   switch (die->tag)
17552     {
17553     case DW_TAG_compile_unit:
17554     case DW_TAG_partial_unit:
17555       /* Compilation units have a DW_AT_name that is a filename, not
17556          a source language identifier.  */
17557     case DW_TAG_enumeration_type:
17558     case DW_TAG_enumerator:
17559       /* These tags always have simple identifiers already; no need
17560          to canonicalize them.  */
17561       return DW_STRING (attr);
17562
17563     case DW_TAG_subprogram:
17564       /* Java constructors will all be named "<init>", so return
17565          the class name when we see this special case.  */
17566       if (cu->language == language_java
17567           && DW_STRING (attr) != NULL
17568           && strcmp (DW_STRING (attr), "<init>") == 0)
17569         {
17570           struct dwarf2_cu *spec_cu = cu;
17571           struct die_info *spec_die;
17572
17573           /* GCJ will output '<init>' for Java constructor names.
17574              For this special case, return the name of the parent class.  */
17575
17576           /* GCJ may output suprogram DIEs with AT_specification set.
17577              If so, use the name of the specified DIE.  */
17578           spec_die = die_specification (die, &spec_cu);
17579           if (spec_die != NULL)
17580             return dwarf2_name (spec_die, spec_cu);
17581
17582           do
17583             {
17584               die = die->parent;
17585               if (die->tag == DW_TAG_class_type)
17586                 return dwarf2_name (die, cu);
17587             }
17588           while (die->tag != DW_TAG_compile_unit
17589                  && die->tag != DW_TAG_partial_unit);
17590         }
17591       break;
17592
17593     case DW_TAG_class_type:
17594     case DW_TAG_interface_type:
17595     case DW_TAG_structure_type:
17596     case DW_TAG_union_type:
17597       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17598          structures or unions.  These were of the form "._%d" in GCC 4.1,
17599          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17600          and GCC 4.4.  We work around this problem by ignoring these.  */
17601       if (attr && DW_STRING (attr)
17602           && (strncmp (DW_STRING (attr), "._", 2) == 0
17603               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17604         return NULL;
17605
17606       /* GCC might emit a nameless typedef that has a linkage name.  See
17607          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17608       if (!attr || DW_STRING (attr) == NULL)
17609         {
17610           char *demangled = NULL;
17611
17612           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17613           if (attr == NULL)
17614             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17615
17616           if (attr == NULL || DW_STRING (attr) == NULL)
17617             return NULL;
17618
17619           /* Avoid demangling DW_STRING (attr) the second time on a second
17620              call for the same DIE.  */
17621           if (!DW_STRING_IS_CANONICAL (attr))
17622             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17623
17624           if (demangled)
17625             {
17626               char *base;
17627
17628               /* FIXME: we already did this for the partial symbol... */
17629               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17630                                                 demangled, strlen (demangled));
17631               DW_STRING_IS_CANONICAL (attr) = 1;
17632               xfree (demangled);
17633
17634               /* Strip any leading namespaces/classes, keep only the base name.
17635                  DW_AT_name for named DIEs does not contain the prefixes.  */
17636               base = strrchr (DW_STRING (attr), ':');
17637               if (base && base > DW_STRING (attr) && base[-1] == ':')
17638                 return &base[1];
17639               else
17640                 return DW_STRING (attr);
17641             }
17642         }
17643       break;
17644
17645     default:
17646       break;
17647     }
17648
17649   if (!DW_STRING_IS_CANONICAL (attr))
17650     {
17651       DW_STRING (attr)
17652         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17653                                     &cu->objfile->objfile_obstack);
17654       DW_STRING_IS_CANONICAL (attr) = 1;
17655     }
17656   return DW_STRING (attr);
17657 }
17658
17659 /* Return the die that this die in an extension of, or NULL if there
17660    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17661    containing the return value on output.  */
17662
17663 static struct die_info *
17664 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17665 {
17666   struct attribute *attr;
17667
17668   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17669   if (attr == NULL)
17670     return NULL;
17671
17672   return follow_die_ref (die, attr, ext_cu);
17673 }
17674
17675 /* Convert a DIE tag into its string name.  */
17676
17677 static const char *
17678 dwarf_tag_name (unsigned tag)
17679 {
17680   const char *name = get_DW_TAG_name (tag);
17681
17682   if (name == NULL)
17683     return "DW_TAG_<unknown>";
17684
17685   return name;
17686 }
17687
17688 /* Convert a DWARF attribute code into its string name.  */
17689
17690 static const char *
17691 dwarf_attr_name (unsigned attr)
17692 {
17693   const char *name;
17694
17695 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17696   if (attr == DW_AT_MIPS_fde)
17697     return "DW_AT_MIPS_fde";
17698 #else
17699   if (attr == DW_AT_HP_block_index)
17700     return "DW_AT_HP_block_index";
17701 #endif
17702
17703   name = get_DW_AT_name (attr);
17704
17705   if (name == NULL)
17706     return "DW_AT_<unknown>";
17707
17708   return name;
17709 }
17710
17711 /* Convert a DWARF value form code into its string name.  */
17712
17713 static const char *
17714 dwarf_form_name (unsigned form)
17715 {
17716   const char *name = get_DW_FORM_name (form);
17717
17718   if (name == NULL)
17719     return "DW_FORM_<unknown>";
17720
17721   return name;
17722 }
17723
17724 static char *
17725 dwarf_bool_name (unsigned mybool)
17726 {
17727   if (mybool)
17728     return "TRUE";
17729   else
17730     return "FALSE";
17731 }
17732
17733 /* Convert a DWARF type code into its string name.  */
17734
17735 static const char *
17736 dwarf_type_encoding_name (unsigned enc)
17737 {
17738   const char *name = get_DW_ATE_name (enc);
17739
17740   if (name == NULL)
17741     return "DW_ATE_<unknown>";
17742
17743   return name;
17744 }
17745
17746 static void
17747 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17748 {
17749   unsigned int i;
17750
17751   print_spaces (indent, f);
17752   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17753            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17754
17755   if (die->parent != NULL)
17756     {
17757       print_spaces (indent, f);
17758       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17759                           die->parent->offset.sect_off);
17760     }
17761
17762   print_spaces (indent, f);
17763   fprintf_unfiltered (f, "  has children: %s\n",
17764            dwarf_bool_name (die->child != NULL));
17765
17766   print_spaces (indent, f);
17767   fprintf_unfiltered (f, "  attributes:\n");
17768
17769   for (i = 0; i < die->num_attrs; ++i)
17770     {
17771       print_spaces (indent, f);
17772       fprintf_unfiltered (f, "    %s (%s) ",
17773                dwarf_attr_name (die->attrs[i].name),
17774                dwarf_form_name (die->attrs[i].form));
17775
17776       switch (die->attrs[i].form)
17777         {
17778         case DW_FORM_addr:
17779         case DW_FORM_GNU_addr_index:
17780           fprintf_unfiltered (f, "address: ");
17781           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17782           break;
17783         case DW_FORM_block2:
17784         case DW_FORM_block4:
17785         case DW_FORM_block:
17786         case DW_FORM_block1:
17787           fprintf_unfiltered (f, "block: size %s",
17788                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17789           break;
17790         case DW_FORM_exprloc:
17791           fprintf_unfiltered (f, "expression: size %s",
17792                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17793           break;
17794         case DW_FORM_ref_addr:
17795           fprintf_unfiltered (f, "ref address: ");
17796           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17797           break;
17798         case DW_FORM_GNU_ref_alt:
17799           fprintf_unfiltered (f, "alt ref address: ");
17800           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17801           break;
17802         case DW_FORM_ref1:
17803         case DW_FORM_ref2:
17804         case DW_FORM_ref4:
17805         case DW_FORM_ref8:
17806         case DW_FORM_ref_udata:
17807           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17808                               (long) (DW_UNSND (&die->attrs[i])));
17809           break;
17810         case DW_FORM_data1:
17811         case DW_FORM_data2:
17812         case DW_FORM_data4:
17813         case DW_FORM_data8:
17814         case DW_FORM_udata:
17815         case DW_FORM_sdata:
17816           fprintf_unfiltered (f, "constant: %s",
17817                               pulongest (DW_UNSND (&die->attrs[i])));
17818           break;
17819         case DW_FORM_sec_offset:
17820           fprintf_unfiltered (f, "section offset: %s",
17821                               pulongest (DW_UNSND (&die->attrs[i])));
17822           break;
17823         case DW_FORM_ref_sig8:
17824           fprintf_unfiltered (f, "signature: %s",
17825                               hex_string (DW_SIGNATURE (&die->attrs[i])));
17826           break;
17827         case DW_FORM_string:
17828         case DW_FORM_strp:
17829         case DW_FORM_GNU_str_index:
17830         case DW_FORM_GNU_strp_alt:
17831           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17832                    DW_STRING (&die->attrs[i])
17833                    ? DW_STRING (&die->attrs[i]) : "",
17834                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17835           break;
17836         case DW_FORM_flag:
17837           if (DW_UNSND (&die->attrs[i]))
17838             fprintf_unfiltered (f, "flag: TRUE");
17839           else
17840             fprintf_unfiltered (f, "flag: FALSE");
17841           break;
17842         case DW_FORM_flag_present:
17843           fprintf_unfiltered (f, "flag: TRUE");
17844           break;
17845         case DW_FORM_indirect:
17846           /* The reader will have reduced the indirect form to
17847              the "base form" so this form should not occur.  */
17848           fprintf_unfiltered (f, 
17849                               "unexpected attribute form: DW_FORM_indirect");
17850           break;
17851         default:
17852           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17853                    die->attrs[i].form);
17854           break;
17855         }
17856       fprintf_unfiltered (f, "\n");
17857     }
17858 }
17859
17860 static void
17861 dump_die_for_error (struct die_info *die)
17862 {
17863   dump_die_shallow (gdb_stderr, 0, die);
17864 }
17865
17866 static void
17867 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17868 {
17869   int indent = level * 4;
17870
17871   gdb_assert (die != NULL);
17872
17873   if (level >= max_level)
17874     return;
17875
17876   dump_die_shallow (f, indent, die);
17877
17878   if (die->child != NULL)
17879     {
17880       print_spaces (indent, f);
17881       fprintf_unfiltered (f, "  Children:");
17882       if (level + 1 < max_level)
17883         {
17884           fprintf_unfiltered (f, "\n");
17885           dump_die_1 (f, level + 1, max_level, die->child);
17886         }
17887       else
17888         {
17889           fprintf_unfiltered (f,
17890                               " [not printed, max nesting level reached]\n");
17891         }
17892     }
17893
17894   if (die->sibling != NULL && level > 0)
17895     {
17896       dump_die_1 (f, level, max_level, die->sibling);
17897     }
17898 }
17899
17900 /* This is called from the pdie macro in gdbinit.in.
17901    It's not static so gcc will keep a copy callable from gdb.  */
17902
17903 void
17904 dump_die (struct die_info *die, int max_level)
17905 {
17906   dump_die_1 (gdb_stdlog, 0, max_level, die);
17907 }
17908
17909 static void
17910 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17911 {
17912   void **slot;
17913
17914   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17915                                    INSERT);
17916
17917   *slot = die;
17918 }
17919
17920 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17921    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17922
17923 static int
17924 is_ref_attr (struct attribute *attr)
17925 {
17926   switch (attr->form)
17927     {
17928     case DW_FORM_ref_addr:
17929     case DW_FORM_ref1:
17930     case DW_FORM_ref2:
17931     case DW_FORM_ref4:
17932     case DW_FORM_ref8:
17933     case DW_FORM_ref_udata:
17934     case DW_FORM_GNU_ref_alt:
17935       return 1;
17936     default:
17937       return 0;
17938     }
17939 }
17940
17941 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17942    required kind.  */
17943
17944 static sect_offset
17945 dwarf2_get_ref_die_offset (struct attribute *attr)
17946 {
17947   sect_offset retval = { DW_UNSND (attr) };
17948
17949   if (is_ref_attr (attr))
17950     return retval;
17951
17952   retval.sect_off = 0;
17953   complaint (&symfile_complaints,
17954              _("unsupported die ref attribute form: '%s'"),
17955              dwarf_form_name (attr->form));
17956   return retval;
17957 }
17958
17959 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17960  * the value held by the attribute is not constant.  */
17961
17962 static LONGEST
17963 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17964 {
17965   if (attr->form == DW_FORM_sdata)
17966     return DW_SND (attr);
17967   else if (attr->form == DW_FORM_udata
17968            || attr->form == DW_FORM_data1
17969            || attr->form == DW_FORM_data2
17970            || attr->form == DW_FORM_data4
17971            || attr->form == DW_FORM_data8)
17972     return DW_UNSND (attr);
17973   else
17974     {
17975       complaint (&symfile_complaints,
17976                  _("Attribute value is not a constant (%s)"),
17977                  dwarf_form_name (attr->form));
17978       return default_value;
17979     }
17980 }
17981
17982 /* Follow reference or signature attribute ATTR of SRC_DIE.
17983    On entry *REF_CU is the CU of SRC_DIE.
17984    On exit *REF_CU is the CU of the result.  */
17985
17986 static struct die_info *
17987 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17988                        struct dwarf2_cu **ref_cu)
17989 {
17990   struct die_info *die;
17991
17992   if (is_ref_attr (attr))
17993     die = follow_die_ref (src_die, attr, ref_cu);
17994   else if (attr->form == DW_FORM_ref_sig8)
17995     die = follow_die_sig (src_die, attr, ref_cu);
17996   else
17997     {
17998       dump_die_for_error (src_die);
17999       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18000              (*ref_cu)->objfile->name);
18001     }
18002
18003   return die;
18004 }
18005
18006 /* Follow reference OFFSET.
18007    On entry *REF_CU is the CU of the source die referencing OFFSET.
18008    On exit *REF_CU is the CU of the result.
18009    Returns NULL if OFFSET is invalid.  */
18010
18011 static struct die_info *
18012 follow_die_offset (sect_offset offset, int offset_in_dwz,
18013                    struct dwarf2_cu **ref_cu)
18014 {
18015   struct die_info temp_die;
18016   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18017
18018   gdb_assert (cu->per_cu != NULL);
18019
18020   target_cu = cu;
18021
18022   if (cu->per_cu->is_debug_types)
18023     {
18024       /* .debug_types CUs cannot reference anything outside their CU.
18025          If they need to, they have to reference a signatured type via
18026          DW_FORM_ref_sig8.  */
18027       if (! offset_in_cu_p (&cu->header, offset))
18028         return NULL;
18029     }
18030   else if (offset_in_dwz != cu->per_cu->is_dwz
18031            || ! offset_in_cu_p (&cu->header, offset))
18032     {
18033       struct dwarf2_per_cu_data *per_cu;
18034
18035       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18036                                                  cu->objfile);
18037
18038       /* If necessary, add it to the queue and load its DIEs.  */
18039       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18040         load_full_comp_unit (per_cu, cu->language);
18041
18042       target_cu = per_cu->cu;
18043     }
18044   else if (cu->dies == NULL)
18045     {
18046       /* We're loading full DIEs during partial symbol reading.  */
18047       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18048       load_full_comp_unit (cu->per_cu, language_minimal);
18049     }
18050
18051   *ref_cu = target_cu;
18052   temp_die.offset = offset;
18053   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18054 }
18055
18056 /* Follow reference attribute ATTR of SRC_DIE.
18057    On entry *REF_CU is the CU of SRC_DIE.
18058    On exit *REF_CU is the CU of the result.  */
18059
18060 static struct die_info *
18061 follow_die_ref (struct die_info *src_die, struct attribute *attr,
18062                 struct dwarf2_cu **ref_cu)
18063 {
18064   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18065   struct dwarf2_cu *cu = *ref_cu;
18066   struct die_info *die;
18067
18068   die = follow_die_offset (offset,
18069                            (attr->form == DW_FORM_GNU_ref_alt
18070                             || cu->per_cu->is_dwz),
18071                            ref_cu);
18072   if (!die)
18073     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18074            "at 0x%x [in module %s]"),
18075            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
18076
18077   return die;
18078 }
18079
18080 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18081    Returned value is intended for DW_OP_call*.  Returned
18082    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18083
18084 struct dwarf2_locexpr_baton
18085 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18086                                struct dwarf2_per_cu_data *per_cu,
18087                                CORE_ADDR (*get_frame_pc) (void *baton),
18088                                void *baton)
18089 {
18090   struct dwarf2_cu *cu;
18091   struct die_info *die;
18092   struct attribute *attr;
18093   struct dwarf2_locexpr_baton retval;
18094
18095   dw2_setup (per_cu->objfile);
18096
18097   if (per_cu->cu == NULL)
18098     load_cu (per_cu);
18099   cu = per_cu->cu;
18100
18101   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18102   if (!die)
18103     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18104            offset.sect_off, per_cu->objfile->name);
18105
18106   attr = dwarf2_attr (die, DW_AT_location, cu);
18107   if (!attr)
18108     {
18109       /* DWARF: "If there is no such attribute, then there is no effect.".
18110          DATA is ignored if SIZE is 0.  */
18111
18112       retval.data = NULL;
18113       retval.size = 0;
18114     }
18115   else if (attr_form_is_section_offset (attr))
18116     {
18117       struct dwarf2_loclist_baton loclist_baton;
18118       CORE_ADDR pc = (*get_frame_pc) (baton);
18119       size_t size;
18120
18121       fill_in_loclist_baton (cu, &loclist_baton, attr);
18122
18123       retval.data = dwarf2_find_location_expression (&loclist_baton,
18124                                                      &size, pc);
18125       retval.size = size;
18126     }
18127   else
18128     {
18129       if (!attr_form_is_block (attr))
18130         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18131                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18132                offset.sect_off, per_cu->objfile->name);
18133
18134       retval.data = DW_BLOCK (attr)->data;
18135       retval.size = DW_BLOCK (attr)->size;
18136     }
18137   retval.per_cu = cu->per_cu;
18138
18139   age_cached_comp_units ();
18140
18141   return retval;
18142 }
18143
18144 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18145    offset.  */
18146
18147 struct dwarf2_locexpr_baton
18148 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18149                              struct dwarf2_per_cu_data *per_cu,
18150                              CORE_ADDR (*get_frame_pc) (void *baton),
18151                              void *baton)
18152 {
18153   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18154
18155   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18156 }
18157
18158 /* Write a constant of a given type as target-ordered bytes into
18159    OBSTACK.  */
18160
18161 static const gdb_byte *
18162 write_constant_as_bytes (struct obstack *obstack,
18163                          enum bfd_endian byte_order,
18164                          struct type *type,
18165                          ULONGEST value,
18166                          LONGEST *len)
18167 {
18168   gdb_byte *result;
18169
18170   *len = TYPE_LENGTH (type);
18171   result = obstack_alloc (obstack, *len);
18172   store_unsigned_integer (result, *len, byte_order, value);
18173
18174   return result;
18175 }
18176
18177 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
18178    pointer to the constant bytes and set LEN to the length of the
18179    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
18180    does not have a DW_AT_const_value, return NULL.  */
18181
18182 const gdb_byte *
18183 dwarf2_fetch_constant_bytes (sect_offset offset,
18184                              struct dwarf2_per_cu_data *per_cu,
18185                              struct obstack *obstack,
18186                              LONGEST *len)
18187 {
18188   struct dwarf2_cu *cu;
18189   struct die_info *die;
18190   struct attribute *attr;
18191   const gdb_byte *result = NULL;
18192   struct type *type;
18193   LONGEST value;
18194   enum bfd_endian byte_order;
18195
18196   dw2_setup (per_cu->objfile);
18197
18198   if (per_cu->cu == NULL)
18199     load_cu (per_cu);
18200   cu = per_cu->cu;
18201
18202   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18203   if (!die)
18204     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18205            offset.sect_off, per_cu->objfile->name);
18206
18207
18208   attr = dwarf2_attr (die, DW_AT_const_value, cu);
18209   if (attr == NULL)
18210     return NULL;
18211
18212   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
18213                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
18214
18215   switch (attr->form)
18216     {
18217     case DW_FORM_addr:
18218     case DW_FORM_GNU_addr_index:
18219       {
18220         gdb_byte *tem;
18221
18222         *len = cu->header.addr_size;
18223         tem = obstack_alloc (obstack, *len);
18224         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
18225         result = tem;
18226       }
18227       break;
18228     case DW_FORM_string:
18229     case DW_FORM_strp:
18230     case DW_FORM_GNU_str_index:
18231     case DW_FORM_GNU_strp_alt:
18232       /* DW_STRING is already allocated on the objfile obstack, point
18233          directly to it.  */
18234       result = (const gdb_byte *) DW_STRING (attr);
18235       *len = strlen (DW_STRING (attr));
18236       break;
18237     case DW_FORM_block1:
18238     case DW_FORM_block2:
18239     case DW_FORM_block4:
18240     case DW_FORM_block:
18241     case DW_FORM_exprloc:
18242       result = DW_BLOCK (attr)->data;
18243       *len = DW_BLOCK (attr)->size;
18244       break;
18245
18246       /* The DW_AT_const_value attributes are supposed to carry the
18247          symbol's value "represented as it would be on the target
18248          architecture."  By the time we get here, it's already been
18249          converted to host endianness, so we just need to sign- or
18250          zero-extend it as appropriate.  */
18251     case DW_FORM_data1:
18252       type = die_type (die, cu);
18253       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
18254       if (result == NULL)
18255         result = write_constant_as_bytes (obstack, byte_order,
18256                                           type, value, len);
18257       break;
18258     case DW_FORM_data2:
18259       type = die_type (die, cu);
18260       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
18261       if (result == NULL)
18262         result = write_constant_as_bytes (obstack, byte_order,
18263                                           type, value, len);
18264       break;
18265     case DW_FORM_data4:
18266       type = die_type (die, cu);
18267       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
18268       if (result == NULL)
18269         result = write_constant_as_bytes (obstack, byte_order,
18270                                           type, value, len);
18271       break;
18272     case DW_FORM_data8:
18273       type = die_type (die, cu);
18274       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
18275       if (result == NULL)
18276         result = write_constant_as_bytes (obstack, byte_order,
18277                                           type, value, len);
18278       break;
18279
18280     case DW_FORM_sdata:
18281       type = die_type (die, cu);
18282       result = write_constant_as_bytes (obstack, byte_order,
18283                                         type, DW_SND (attr), len);
18284       break;
18285
18286     case DW_FORM_udata:
18287       type = die_type (die, cu);
18288       result = write_constant_as_bytes (obstack, byte_order,
18289                                         type, DW_UNSND (attr), len);
18290       break;
18291
18292     default:
18293       complaint (&symfile_complaints,
18294                  _("unsupported const value attribute form: '%s'"),
18295                  dwarf_form_name (attr->form));
18296       break;
18297     }
18298
18299   return result;
18300 }
18301
18302 /* Return the type of the DIE at DIE_OFFSET in the CU named by
18303    PER_CU.  */
18304
18305 struct type *
18306 dwarf2_get_die_type (cu_offset die_offset,
18307                      struct dwarf2_per_cu_data *per_cu)
18308 {
18309   sect_offset die_offset_sect;
18310
18311   dw2_setup (per_cu->objfile);
18312
18313   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
18314   return get_die_type_at_offset (die_offset_sect, per_cu);
18315 }
18316
18317 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
18318    On entry *REF_CU is the CU of SRC_DIE.
18319    On exit *REF_CU is the CU of the result.
18320    Returns NULL if the referenced DIE isn't found.  */
18321
18322 static struct die_info *
18323 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
18324                   struct dwarf2_cu **ref_cu)
18325 {
18326   struct objfile *objfile = (*ref_cu)->objfile;
18327   struct die_info temp_die;
18328   struct dwarf2_cu *sig_cu;
18329   struct die_info *die;
18330
18331   /* While it might be nice to assert sig_type->type == NULL here,
18332      we can get here for DW_AT_imported_declaration where we need
18333      the DIE not the type.  */
18334
18335   /* If necessary, add it to the queue and load its DIEs.  */
18336
18337   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
18338     read_signatured_type (sig_type);
18339
18340   gdb_assert (sig_type->per_cu.cu != NULL);
18341
18342   sig_cu = sig_type->per_cu.cu;
18343   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
18344   temp_die.offset = sig_type->type_offset_in_section;
18345   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
18346                              temp_die.offset.sect_off);
18347   if (die)
18348     {
18349       /* For .gdb_index version 7 keep track of included TUs.
18350          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
18351       if (dwarf2_per_objfile->index_table != NULL
18352           && dwarf2_per_objfile->index_table->version <= 7)
18353         {
18354           VEC_safe_push (dwarf2_per_cu_ptr,
18355                          (*ref_cu)->per_cu->imported_symtabs,
18356                          sig_cu->per_cu);
18357         }
18358
18359       *ref_cu = sig_cu;
18360       return die;
18361     }
18362
18363   return NULL;
18364 }
18365
18366 /* Follow signatured type referenced by ATTR in SRC_DIE.
18367    On entry *REF_CU is the CU of SRC_DIE.
18368    On exit *REF_CU is the CU of the result.
18369    The result is the DIE of the type.
18370    If the referenced type cannot be found an error is thrown.  */
18371
18372 static struct die_info *
18373 follow_die_sig (struct die_info *src_die, struct attribute *attr,
18374                 struct dwarf2_cu **ref_cu)
18375 {
18376   ULONGEST signature = DW_SIGNATURE (attr);
18377   struct signatured_type *sig_type;
18378   struct die_info *die;
18379
18380   gdb_assert (attr->form == DW_FORM_ref_sig8);
18381
18382   sig_type = lookup_signatured_type (*ref_cu, signature);
18383   /* sig_type will be NULL if the signatured type is missing from
18384      the debug info.  */
18385   if (sig_type == NULL)
18386     {
18387       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
18388                " from DIE at 0x%x [in module %s]"),
18389              hex_string (signature), src_die->offset.sect_off,
18390              (*ref_cu)->objfile->name);
18391     }
18392
18393   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
18394   if (die == NULL)
18395     {
18396       dump_die_for_error (src_die);
18397       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
18398                " from DIE at 0x%x [in module %s]"),
18399              hex_string (signature), src_die->offset.sect_off,
18400              (*ref_cu)->objfile->name);
18401     }
18402
18403   return die;
18404 }
18405
18406 /* Get the type specified by SIGNATURE referenced in DIE/CU,
18407    reading in and processing the type unit if necessary.  */
18408
18409 static struct type *
18410 get_signatured_type (struct die_info *die, ULONGEST signature,
18411                      struct dwarf2_cu *cu)
18412 {
18413   struct signatured_type *sig_type;
18414   struct dwarf2_cu *type_cu;
18415   struct die_info *type_die;
18416   struct type *type;
18417
18418   sig_type = lookup_signatured_type (cu, signature);
18419   /* sig_type will be NULL if the signatured type is missing from
18420      the debug info.  */
18421   if (sig_type == NULL)
18422     {
18423       complaint (&symfile_complaints,
18424                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
18425                    " from DIE at 0x%x [in module %s]"),
18426                  hex_string (signature), die->offset.sect_off,
18427                  dwarf2_per_objfile->objfile->name);
18428       return build_error_marker_type (cu, die);
18429     }
18430
18431   /* If we already know the type we're done.  */
18432   if (sig_type->type != NULL)
18433     return sig_type->type;
18434
18435   type_cu = cu;
18436   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
18437   if (type_die != NULL)
18438     {
18439       /* N.B. We need to call get_die_type to ensure only one type for this DIE
18440          is created.  This is important, for example, because for c++ classes
18441          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
18442       type = read_type_die (type_die, type_cu);
18443       if (type == NULL)
18444         {
18445           complaint (&symfile_complaints,
18446                      _("Dwarf Error: Cannot build signatured type %s"
18447                        " referenced from DIE at 0x%x [in module %s]"),
18448                      hex_string (signature), die->offset.sect_off,
18449                      dwarf2_per_objfile->objfile->name);
18450           type = build_error_marker_type (cu, die);
18451         }
18452     }
18453   else
18454     {
18455       complaint (&symfile_complaints,
18456                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
18457                    " from DIE at 0x%x [in module %s]"),
18458                  hex_string (signature), die->offset.sect_off,
18459                  dwarf2_per_objfile->objfile->name);
18460       type = build_error_marker_type (cu, die);
18461     }
18462   sig_type->type = type;
18463
18464   return type;
18465 }
18466
18467 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
18468    reading in and processing the type unit if necessary.  */
18469
18470 static struct type *
18471 get_DW_AT_signature_type (struct die_info *die, struct attribute *attr,
18472                           struct dwarf2_cu *cu) /* ARI: editCase function */
18473 {
18474   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
18475   if (is_ref_attr (attr))
18476     {
18477       struct dwarf2_cu *type_cu = cu;
18478       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
18479
18480       return read_type_die (type_die, type_cu);
18481     }
18482   else if (attr->form == DW_FORM_ref_sig8)
18483     {
18484       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
18485     }
18486   else
18487     {
18488       complaint (&symfile_complaints,
18489                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
18490                    " at 0x%x [in module %s]"),
18491                  dwarf_form_name (attr->form), die->offset.sect_off,
18492                  dwarf2_per_objfile->objfile->name);
18493       return build_error_marker_type (cu, die);
18494     }
18495 }
18496
18497 /* Load the DIEs associated with type unit PER_CU into memory.  */
18498
18499 static void
18500 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
18501 {
18502   struct signatured_type *sig_type;
18503
18504   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
18505   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
18506
18507   /* We have the per_cu, but we need the signatured_type.
18508      Fortunately this is an easy translation.  */
18509   gdb_assert (per_cu->is_debug_types);
18510   sig_type = (struct signatured_type *) per_cu;
18511
18512   gdb_assert (per_cu->cu == NULL);
18513
18514   read_signatured_type (sig_type);
18515
18516   gdb_assert (per_cu->cu != NULL);
18517 }
18518
18519 /* die_reader_func for read_signatured_type.
18520    This is identical to load_full_comp_unit_reader,
18521    but is kept separate for now.  */
18522
18523 static void
18524 read_signatured_type_reader (const struct die_reader_specs *reader,
18525                              const gdb_byte *info_ptr,
18526                              struct die_info *comp_unit_die,
18527                              int has_children,
18528                              void *data)
18529 {
18530   struct dwarf2_cu *cu = reader->cu;
18531
18532   gdb_assert (cu->die_hash == NULL);
18533   cu->die_hash =
18534     htab_create_alloc_ex (cu->header.length / 12,
18535                           die_hash,
18536                           die_eq,
18537                           NULL,
18538                           &cu->comp_unit_obstack,
18539                           hashtab_obstack_allocate,
18540                           dummy_obstack_deallocate);
18541
18542   if (has_children)
18543     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
18544                                                   &info_ptr, comp_unit_die);
18545   cu->dies = comp_unit_die;
18546   /* comp_unit_die is not stored in die_hash, no need.  */
18547
18548   /* We try not to read any attributes in this function, because not
18549      all CUs needed for references have been loaded yet, and symbol
18550      table processing isn't initialized.  But we have to set the CU language,
18551      or we won't be able to build types correctly.
18552      Similarly, if we do not read the producer, we can not apply
18553      producer-specific interpretation.  */
18554   prepare_one_comp_unit (cu, cu->dies, language_minimal);
18555 }
18556
18557 /* Read in a signatured type and build its CU and DIEs.
18558    If the type is a stub for the real type in a DWO file,
18559    read in the real type from the DWO file as well.  */
18560
18561 static void
18562 read_signatured_type (struct signatured_type *sig_type)
18563 {
18564   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
18565
18566   gdb_assert (per_cu->is_debug_types);
18567   gdb_assert (per_cu->cu == NULL);
18568
18569   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
18570                            read_signatured_type_reader, NULL);
18571 }
18572
18573 /* Decode simple location descriptions.
18574    Given a pointer to a dwarf block that defines a location, compute
18575    the location and return the value.
18576
18577    NOTE drow/2003-11-18: This function is called in two situations
18578    now: for the address of static or global variables (partial symbols
18579    only) and for offsets into structures which are expected to be
18580    (more or less) constant.  The partial symbol case should go away,
18581    and only the constant case should remain.  That will let this
18582    function complain more accurately.  A few special modes are allowed
18583    without complaint for global variables (for instance, global
18584    register values and thread-local values).
18585
18586    A location description containing no operations indicates that the
18587    object is optimized out.  The return value is 0 for that case.
18588    FIXME drow/2003-11-16: No callers check for this case any more; soon all
18589    callers will only want a very basic result and this can become a
18590    complaint.
18591
18592    Note that stack[0] is unused except as a default error return.  */
18593
18594 static CORE_ADDR
18595 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
18596 {
18597   struct objfile *objfile = cu->objfile;
18598   size_t i;
18599   size_t size = blk->size;
18600   const gdb_byte *data = blk->data;
18601   CORE_ADDR stack[64];
18602   int stacki;
18603   unsigned int bytes_read, unsnd;
18604   gdb_byte op;
18605
18606   i = 0;
18607   stacki = 0;
18608   stack[stacki] = 0;
18609   stack[++stacki] = 0;
18610
18611   while (i < size)
18612     {
18613       op = data[i++];
18614       switch (op)
18615         {
18616         case DW_OP_lit0:
18617         case DW_OP_lit1:
18618         case DW_OP_lit2:
18619         case DW_OP_lit3:
18620         case DW_OP_lit4:
18621         case DW_OP_lit5:
18622         case DW_OP_lit6:
18623         case DW_OP_lit7:
18624         case DW_OP_lit8:
18625         case DW_OP_lit9:
18626         case DW_OP_lit10:
18627         case DW_OP_lit11:
18628         case DW_OP_lit12:
18629         case DW_OP_lit13:
18630         case DW_OP_lit14:
18631         case DW_OP_lit15:
18632         case DW_OP_lit16:
18633         case DW_OP_lit17:
18634         case DW_OP_lit18:
18635         case DW_OP_lit19:
18636         case DW_OP_lit20:
18637         case DW_OP_lit21:
18638         case DW_OP_lit22:
18639         case DW_OP_lit23:
18640         case DW_OP_lit24:
18641         case DW_OP_lit25:
18642         case DW_OP_lit26:
18643         case DW_OP_lit27:
18644         case DW_OP_lit28:
18645         case DW_OP_lit29:
18646         case DW_OP_lit30:
18647         case DW_OP_lit31:
18648           stack[++stacki] = op - DW_OP_lit0;
18649           break;
18650
18651         case DW_OP_reg0:
18652         case DW_OP_reg1:
18653         case DW_OP_reg2:
18654         case DW_OP_reg3:
18655         case DW_OP_reg4:
18656         case DW_OP_reg5:
18657         case DW_OP_reg6:
18658         case DW_OP_reg7:
18659         case DW_OP_reg8:
18660         case DW_OP_reg9:
18661         case DW_OP_reg10:
18662         case DW_OP_reg11:
18663         case DW_OP_reg12:
18664         case DW_OP_reg13:
18665         case DW_OP_reg14:
18666         case DW_OP_reg15:
18667         case DW_OP_reg16:
18668         case DW_OP_reg17:
18669         case DW_OP_reg18:
18670         case DW_OP_reg19:
18671         case DW_OP_reg20:
18672         case DW_OP_reg21:
18673         case DW_OP_reg22:
18674         case DW_OP_reg23:
18675         case DW_OP_reg24:
18676         case DW_OP_reg25:
18677         case DW_OP_reg26:
18678         case DW_OP_reg27:
18679         case DW_OP_reg28:
18680         case DW_OP_reg29:
18681         case DW_OP_reg30:
18682         case DW_OP_reg31:
18683           stack[++stacki] = op - DW_OP_reg0;
18684           if (i < size)
18685             dwarf2_complex_location_expr_complaint ();
18686           break;
18687
18688         case DW_OP_regx:
18689           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18690           i += bytes_read;
18691           stack[++stacki] = unsnd;
18692           if (i < size)
18693             dwarf2_complex_location_expr_complaint ();
18694           break;
18695
18696         case DW_OP_addr:
18697           stack[++stacki] = read_address (objfile->obfd, &data[i],
18698                                           cu, &bytes_read);
18699           i += bytes_read;
18700           break;
18701
18702         case DW_OP_const1u:
18703           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18704           i += 1;
18705           break;
18706
18707         case DW_OP_const1s:
18708           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18709           i += 1;
18710           break;
18711
18712         case DW_OP_const2u:
18713           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18714           i += 2;
18715           break;
18716
18717         case DW_OP_const2s:
18718           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18719           i += 2;
18720           break;
18721
18722         case DW_OP_const4u:
18723           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18724           i += 4;
18725           break;
18726
18727         case DW_OP_const4s:
18728           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18729           i += 4;
18730           break;
18731
18732         case DW_OP_const8u:
18733           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18734           i += 8;
18735           break;
18736
18737         case DW_OP_constu:
18738           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18739                                                   &bytes_read);
18740           i += bytes_read;
18741           break;
18742
18743         case DW_OP_consts:
18744           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18745           i += bytes_read;
18746           break;
18747
18748         case DW_OP_dup:
18749           stack[stacki + 1] = stack[stacki];
18750           stacki++;
18751           break;
18752
18753         case DW_OP_plus:
18754           stack[stacki - 1] += stack[stacki];
18755           stacki--;
18756           break;
18757
18758         case DW_OP_plus_uconst:
18759           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18760                                                  &bytes_read);
18761           i += bytes_read;
18762           break;
18763
18764         case DW_OP_minus:
18765           stack[stacki - 1] -= stack[stacki];
18766           stacki--;
18767           break;
18768
18769         case DW_OP_deref:
18770           /* If we're not the last op, then we definitely can't encode
18771              this using GDB's address_class enum.  This is valid for partial
18772              global symbols, although the variable's address will be bogus
18773              in the psymtab.  */
18774           if (i < size)
18775             dwarf2_complex_location_expr_complaint ();
18776           break;
18777
18778         case DW_OP_GNU_push_tls_address:
18779           /* The top of the stack has the offset from the beginning
18780              of the thread control block at which the variable is located.  */
18781           /* Nothing should follow this operator, so the top of stack would
18782              be returned.  */
18783           /* This is valid for partial global symbols, but the variable's
18784              address will be bogus in the psymtab.  Make it always at least
18785              non-zero to not look as a variable garbage collected by linker
18786              which have DW_OP_addr 0.  */
18787           if (i < size)
18788             dwarf2_complex_location_expr_complaint ();
18789           stack[stacki]++;
18790           break;
18791
18792         case DW_OP_GNU_uninit:
18793           break;
18794
18795         case DW_OP_GNU_addr_index:
18796         case DW_OP_GNU_const_index:
18797           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18798                                                          &bytes_read);
18799           i += bytes_read;
18800           break;
18801
18802         default:
18803           {
18804             const char *name = get_DW_OP_name (op);
18805
18806             if (name)
18807               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18808                          name);
18809             else
18810               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18811                          op);
18812           }
18813
18814           return (stack[stacki]);
18815         }
18816
18817       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18818          outside of the allocated space.  Also enforce minimum>0.  */
18819       if (stacki >= ARRAY_SIZE (stack) - 1)
18820         {
18821           complaint (&symfile_complaints,
18822                      _("location description stack overflow"));
18823           return 0;
18824         }
18825
18826       if (stacki <= 0)
18827         {
18828           complaint (&symfile_complaints,
18829                      _("location description stack underflow"));
18830           return 0;
18831         }
18832     }
18833   return (stack[stacki]);
18834 }
18835
18836 /* memory allocation interface */
18837
18838 static struct dwarf_block *
18839 dwarf_alloc_block (struct dwarf2_cu *cu)
18840 {
18841   struct dwarf_block *blk;
18842
18843   blk = (struct dwarf_block *)
18844     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18845   return (blk);
18846 }
18847
18848 static struct die_info *
18849 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18850 {
18851   struct die_info *die;
18852   size_t size = sizeof (struct die_info);
18853
18854   if (num_attrs > 1)
18855     size += (num_attrs - 1) * sizeof (struct attribute);
18856
18857   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18858   memset (die, 0, sizeof (struct die_info));
18859   return (die);
18860 }
18861
18862 \f
18863 /* Macro support.  */
18864
18865 /* Return file name relative to the compilation directory of file number I in
18866    *LH's file name table.  The result is allocated using xmalloc; the caller is
18867    responsible for freeing it.  */
18868
18869 static char *
18870 file_file_name (int file, struct line_header *lh)
18871 {
18872   /* Is the file number a valid index into the line header's file name
18873      table?  Remember that file numbers start with one, not zero.  */
18874   if (1 <= file && file <= lh->num_file_names)
18875     {
18876       struct file_entry *fe = &lh->file_names[file - 1];
18877
18878       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18879         return xstrdup (fe->name);
18880       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18881                      fe->name, NULL);
18882     }
18883   else
18884     {
18885       /* The compiler produced a bogus file number.  We can at least
18886          record the macro definitions made in the file, even if we
18887          won't be able to find the file by name.  */
18888       char fake_name[80];
18889
18890       xsnprintf (fake_name, sizeof (fake_name),
18891                  "<bad macro file number %d>", file);
18892
18893       complaint (&symfile_complaints,
18894                  _("bad file number in macro information (%d)"),
18895                  file);
18896
18897       return xstrdup (fake_name);
18898     }
18899 }
18900
18901 /* Return the full name of file number I in *LH's file name table.
18902    Use COMP_DIR as the name of the current directory of the
18903    compilation.  The result is allocated using xmalloc; the caller is
18904    responsible for freeing it.  */
18905 static char *
18906 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18907 {
18908   /* Is the file number a valid index into the line header's file name
18909      table?  Remember that file numbers start with one, not zero.  */
18910   if (1 <= file && file <= lh->num_file_names)
18911     {
18912       char *relative = file_file_name (file, lh);
18913
18914       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18915         return relative;
18916       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18917     }
18918   else
18919     return file_file_name (file, lh);
18920 }
18921
18922
18923 static struct macro_source_file *
18924 macro_start_file (int file, int line,
18925                   struct macro_source_file *current_file,
18926                   const char *comp_dir,
18927                   struct line_header *lh, struct objfile *objfile)
18928 {
18929   /* File name relative to the compilation directory of this source file.  */
18930   char *file_name = file_file_name (file, lh);
18931
18932   /* We don't create a macro table for this compilation unit
18933      at all until we actually get a filename.  */
18934   if (! pending_macros)
18935     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18936                                       objfile->per_bfd->macro_cache,
18937                                       comp_dir);
18938
18939   if (! current_file)
18940     {
18941       /* If we have no current file, then this must be the start_file
18942          directive for the compilation unit's main source file.  */
18943       current_file = macro_set_main (pending_macros, file_name);
18944       macro_define_special (pending_macros);
18945     }
18946   else
18947     current_file = macro_include (current_file, line, file_name);
18948
18949   xfree (file_name);
18950
18951   return current_file;
18952 }
18953
18954
18955 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18956    followed by a null byte.  */
18957 static char *
18958 copy_string (const char *buf, int len)
18959 {
18960   char *s = xmalloc (len + 1);
18961
18962   memcpy (s, buf, len);
18963   s[len] = '\0';
18964   return s;
18965 }
18966
18967
18968 static const char *
18969 consume_improper_spaces (const char *p, const char *body)
18970 {
18971   if (*p == ' ')
18972     {
18973       complaint (&symfile_complaints,
18974                  _("macro definition contains spaces "
18975                    "in formal argument list:\n`%s'"),
18976                  body);
18977
18978       while (*p == ' ')
18979         p++;
18980     }
18981
18982   return p;
18983 }
18984
18985
18986 static void
18987 parse_macro_definition (struct macro_source_file *file, int line,
18988                         const char *body)
18989 {
18990   const char *p;
18991
18992   /* The body string takes one of two forms.  For object-like macro
18993      definitions, it should be:
18994
18995         <macro name> " " <definition>
18996
18997      For function-like macro definitions, it should be:
18998
18999         <macro name> "() " <definition>
19000      or
19001         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19002
19003      Spaces may appear only where explicitly indicated, and in the
19004      <definition>.
19005
19006      The Dwarf 2 spec says that an object-like macro's name is always
19007      followed by a space, but versions of GCC around March 2002 omit
19008      the space when the macro's definition is the empty string.
19009
19010      The Dwarf 2 spec says that there should be no spaces between the
19011      formal arguments in a function-like macro's formal argument list,
19012      but versions of GCC around March 2002 include spaces after the
19013      commas.  */
19014
19015
19016   /* Find the extent of the macro name.  The macro name is terminated
19017      by either a space or null character (for an object-like macro) or
19018      an opening paren (for a function-like macro).  */
19019   for (p = body; *p; p++)
19020     if (*p == ' ' || *p == '(')
19021       break;
19022
19023   if (*p == ' ' || *p == '\0')
19024     {
19025       /* It's an object-like macro.  */
19026       int name_len = p - body;
19027       char *name = copy_string (body, name_len);
19028       const char *replacement;
19029
19030       if (*p == ' ')
19031         replacement = body + name_len + 1;
19032       else
19033         {
19034           dwarf2_macro_malformed_definition_complaint (body);
19035           replacement = body + name_len;
19036         }
19037
19038       macro_define_object (file, line, name, replacement);
19039
19040       xfree (name);
19041     }
19042   else if (*p == '(')
19043     {
19044       /* It's a function-like macro.  */
19045       char *name = copy_string (body, p - body);
19046       int argc = 0;
19047       int argv_size = 1;
19048       char **argv = xmalloc (argv_size * sizeof (*argv));
19049
19050       p++;
19051
19052       p = consume_improper_spaces (p, body);
19053
19054       /* Parse the formal argument list.  */
19055       while (*p && *p != ')')
19056         {
19057           /* Find the extent of the current argument name.  */
19058           const char *arg_start = p;
19059
19060           while (*p && *p != ',' && *p != ')' && *p != ' ')
19061             p++;
19062
19063           if (! *p || p == arg_start)
19064             dwarf2_macro_malformed_definition_complaint (body);
19065           else
19066             {
19067               /* Make sure argv has room for the new argument.  */
19068               if (argc >= argv_size)
19069                 {
19070                   argv_size *= 2;
19071                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19072                 }
19073
19074               argv[argc++] = copy_string (arg_start, p - arg_start);
19075             }
19076
19077           p = consume_improper_spaces (p, body);
19078
19079           /* Consume the comma, if present.  */
19080           if (*p == ',')
19081             {
19082               p++;
19083
19084               p = consume_improper_spaces (p, body);
19085             }
19086         }
19087
19088       if (*p == ')')
19089         {
19090           p++;
19091
19092           if (*p == ' ')
19093             /* Perfectly formed definition, no complaints.  */
19094             macro_define_function (file, line, name,
19095                                    argc, (const char **) argv,
19096                                    p + 1);
19097           else if (*p == '\0')
19098             {
19099               /* Complain, but do define it.  */
19100               dwarf2_macro_malformed_definition_complaint (body);
19101               macro_define_function (file, line, name,
19102                                      argc, (const char **) argv,
19103                                      p);
19104             }
19105           else
19106             /* Just complain.  */
19107             dwarf2_macro_malformed_definition_complaint (body);
19108         }
19109       else
19110         /* Just complain.  */
19111         dwarf2_macro_malformed_definition_complaint (body);
19112
19113       xfree (name);
19114       {
19115         int i;
19116
19117         for (i = 0; i < argc; i++)
19118           xfree (argv[i]);
19119       }
19120       xfree (argv);
19121     }
19122   else
19123     dwarf2_macro_malformed_definition_complaint (body);
19124 }
19125
19126 /* Skip some bytes from BYTES according to the form given in FORM.
19127    Returns the new pointer.  */
19128
19129 static const gdb_byte *
19130 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19131                  enum dwarf_form form,
19132                  unsigned int offset_size,
19133                  struct dwarf2_section_info *section)
19134 {
19135   unsigned int bytes_read;
19136
19137   switch (form)
19138     {
19139     case DW_FORM_data1:
19140     case DW_FORM_flag:
19141       ++bytes;
19142       break;
19143
19144     case DW_FORM_data2:
19145       bytes += 2;
19146       break;
19147
19148     case DW_FORM_data4:
19149       bytes += 4;
19150       break;
19151
19152     case DW_FORM_data8:
19153       bytes += 8;
19154       break;
19155
19156     case DW_FORM_string:
19157       read_direct_string (abfd, bytes, &bytes_read);
19158       bytes += bytes_read;
19159       break;
19160
19161     case DW_FORM_sec_offset:
19162     case DW_FORM_strp:
19163     case DW_FORM_GNU_strp_alt:
19164       bytes += offset_size;
19165       break;
19166
19167     case DW_FORM_block:
19168       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
19169       bytes += bytes_read;
19170       break;
19171
19172     case DW_FORM_block1:
19173       bytes += 1 + read_1_byte (abfd, bytes);
19174       break;
19175     case DW_FORM_block2:
19176       bytes += 2 + read_2_bytes (abfd, bytes);
19177       break;
19178     case DW_FORM_block4:
19179       bytes += 4 + read_4_bytes (abfd, bytes);
19180       break;
19181
19182     case DW_FORM_sdata:
19183     case DW_FORM_udata:
19184     case DW_FORM_GNU_addr_index:
19185     case DW_FORM_GNU_str_index:
19186       bytes = gdb_skip_leb128 (bytes, buffer_end);
19187       if (bytes == NULL)
19188         {
19189           dwarf2_section_buffer_overflow_complaint (section);
19190           return NULL;
19191         }
19192       break;
19193
19194     default:
19195       {
19196       complain:
19197         complaint (&symfile_complaints,
19198                    _("invalid form 0x%x in `%s'"),
19199                    form,
19200                    section->asection->name);
19201         return NULL;
19202       }
19203     }
19204
19205   return bytes;
19206 }
19207
19208 /* A helper for dwarf_decode_macros that handles skipping an unknown
19209    opcode.  Returns an updated pointer to the macro data buffer; or,
19210    on error, issues a complaint and returns NULL.  */
19211
19212 static const gdb_byte *
19213 skip_unknown_opcode (unsigned int opcode,
19214                      const gdb_byte **opcode_definitions,
19215                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19216                      bfd *abfd,
19217                      unsigned int offset_size,
19218                      struct dwarf2_section_info *section)
19219 {
19220   unsigned int bytes_read, i;
19221   unsigned long arg;
19222   const gdb_byte *defn;
19223
19224   if (opcode_definitions[opcode] == NULL)
19225     {
19226       complaint (&symfile_complaints,
19227                  _("unrecognized DW_MACFINO opcode 0x%x"),
19228                  opcode);
19229       return NULL;
19230     }
19231
19232   defn = opcode_definitions[opcode];
19233   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
19234   defn += bytes_read;
19235
19236   for (i = 0; i < arg; ++i)
19237     {
19238       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
19239                                  section);
19240       if (mac_ptr == NULL)
19241         {
19242           /* skip_form_bytes already issued the complaint.  */
19243           return NULL;
19244         }
19245     }
19246
19247   return mac_ptr;
19248 }
19249
19250 /* A helper function which parses the header of a macro section.
19251    If the macro section is the extended (for now called "GNU") type,
19252    then this updates *OFFSET_SIZE.  Returns a pointer to just after
19253    the header, or issues a complaint and returns NULL on error.  */
19254
19255 static const gdb_byte *
19256 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
19257                           bfd *abfd,
19258                           const gdb_byte *mac_ptr,
19259                           unsigned int *offset_size,
19260                           int section_is_gnu)
19261 {
19262   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
19263
19264   if (section_is_gnu)
19265     {
19266       unsigned int version, flags;
19267
19268       version = read_2_bytes (abfd, mac_ptr);
19269       if (version != 4)
19270         {
19271           complaint (&symfile_complaints,
19272                      _("unrecognized version `%d' in .debug_macro section"),
19273                      version);
19274           return NULL;
19275         }
19276       mac_ptr += 2;
19277
19278       flags = read_1_byte (abfd, mac_ptr);
19279       ++mac_ptr;
19280       *offset_size = (flags & 1) ? 8 : 4;
19281
19282       if ((flags & 2) != 0)
19283         /* We don't need the line table offset.  */
19284         mac_ptr += *offset_size;
19285
19286       /* Vendor opcode descriptions.  */
19287       if ((flags & 4) != 0)
19288         {
19289           unsigned int i, count;
19290
19291           count = read_1_byte (abfd, mac_ptr);
19292           ++mac_ptr;
19293           for (i = 0; i < count; ++i)
19294             {
19295               unsigned int opcode, bytes_read;
19296               unsigned long arg;
19297
19298               opcode = read_1_byte (abfd, mac_ptr);
19299               ++mac_ptr;
19300               opcode_definitions[opcode] = mac_ptr;
19301               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19302               mac_ptr += bytes_read;
19303               mac_ptr += arg;
19304             }
19305         }
19306     }
19307
19308   return mac_ptr;
19309 }
19310
19311 /* A helper for dwarf_decode_macros that handles the GNU extensions,
19312    including DW_MACRO_GNU_transparent_include.  */
19313
19314 static void
19315 dwarf_decode_macro_bytes (bfd *abfd,
19316                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
19317                           struct macro_source_file *current_file,
19318                           struct line_header *lh, const char *comp_dir,
19319                           struct dwarf2_section_info *section,
19320                           int section_is_gnu, int section_is_dwz,
19321                           unsigned int offset_size,
19322                           struct objfile *objfile,
19323                           htab_t include_hash)
19324 {
19325   enum dwarf_macro_record_type macinfo_type;
19326   int at_commandline;
19327   const gdb_byte *opcode_definitions[256];
19328
19329   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19330                                       &offset_size, section_is_gnu);
19331   if (mac_ptr == NULL)
19332     {
19333       /* We already issued a complaint.  */
19334       return;
19335     }
19336
19337   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
19338      GDB is still reading the definitions from command line.  First
19339      DW_MACINFO_start_file will need to be ignored as it was already executed
19340      to create CURRENT_FILE for the main source holding also the command line
19341      definitions.  On first met DW_MACINFO_start_file this flag is reset to
19342      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
19343
19344   at_commandline = 1;
19345
19346   do
19347     {
19348       /* Do we at least have room for a macinfo type byte?  */
19349       if (mac_ptr >= mac_end)
19350         {
19351           dwarf2_section_buffer_overflow_complaint (section);
19352           break;
19353         }
19354
19355       macinfo_type = read_1_byte (abfd, mac_ptr);
19356       mac_ptr++;
19357
19358       /* Note that we rely on the fact that the corresponding GNU and
19359          DWARF constants are the same.  */
19360       switch (macinfo_type)
19361         {
19362           /* A zero macinfo type indicates the end of the macro
19363              information.  */
19364         case 0:
19365           break;
19366
19367         case DW_MACRO_GNU_define:
19368         case DW_MACRO_GNU_undef:
19369         case DW_MACRO_GNU_define_indirect:
19370         case DW_MACRO_GNU_undef_indirect:
19371         case DW_MACRO_GNU_define_indirect_alt:
19372         case DW_MACRO_GNU_undef_indirect_alt:
19373           {
19374             unsigned int bytes_read;
19375             int line;
19376             const char *body;
19377             int is_define;
19378
19379             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19380             mac_ptr += bytes_read;
19381
19382             if (macinfo_type == DW_MACRO_GNU_define
19383                 || macinfo_type == DW_MACRO_GNU_undef)
19384               {
19385                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
19386                 mac_ptr += bytes_read;
19387               }
19388             else
19389               {
19390                 LONGEST str_offset;
19391
19392                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
19393                 mac_ptr += offset_size;
19394
19395                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
19396                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
19397                     || section_is_dwz)
19398                   {
19399                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
19400
19401                     body = read_indirect_string_from_dwz (dwz, str_offset);
19402                   }
19403                 else
19404                   body = read_indirect_string_at_offset (abfd, str_offset);
19405               }
19406
19407             is_define = (macinfo_type == DW_MACRO_GNU_define
19408                          || macinfo_type == DW_MACRO_GNU_define_indirect
19409                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
19410             if (! current_file)
19411               {
19412                 /* DWARF violation as no main source is present.  */
19413                 complaint (&symfile_complaints,
19414                            _("debug info with no main source gives macro %s "
19415                              "on line %d: %s"),
19416                            is_define ? _("definition") : _("undefinition"),
19417                            line, body);
19418                 break;
19419               }
19420             if ((line == 0 && !at_commandline)
19421                 || (line != 0 && at_commandline))
19422               complaint (&symfile_complaints,
19423                          _("debug info gives %s macro %s with %s line %d: %s"),
19424                          at_commandline ? _("command-line") : _("in-file"),
19425                          is_define ? _("definition") : _("undefinition"),
19426                          line == 0 ? _("zero") : _("non-zero"), line, body);
19427
19428             if (is_define)
19429               parse_macro_definition (current_file, line, body);
19430             else
19431               {
19432                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
19433                             || macinfo_type == DW_MACRO_GNU_undef_indirect
19434                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
19435                 macro_undef (current_file, line, body);
19436               }
19437           }
19438           break;
19439
19440         case DW_MACRO_GNU_start_file:
19441           {
19442             unsigned int bytes_read;
19443             int line, file;
19444
19445             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19446             mac_ptr += bytes_read;
19447             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19448             mac_ptr += bytes_read;
19449
19450             if ((line == 0 && !at_commandline)
19451                 || (line != 0 && at_commandline))
19452               complaint (&symfile_complaints,
19453                          _("debug info gives source %d included "
19454                            "from %s at %s line %d"),
19455                          file, at_commandline ? _("command-line") : _("file"),
19456                          line == 0 ? _("zero") : _("non-zero"), line);
19457
19458             if (at_commandline)
19459               {
19460                 /* This DW_MACRO_GNU_start_file was executed in the
19461                    pass one.  */
19462                 at_commandline = 0;
19463               }
19464             else
19465               current_file = macro_start_file (file, line,
19466                                                current_file, comp_dir,
19467                                                lh, objfile);
19468           }
19469           break;
19470
19471         case DW_MACRO_GNU_end_file:
19472           if (! current_file)
19473             complaint (&symfile_complaints,
19474                        _("macro debug info has an unmatched "
19475                          "`close_file' directive"));
19476           else
19477             {
19478               current_file = current_file->included_by;
19479               if (! current_file)
19480                 {
19481                   enum dwarf_macro_record_type next_type;
19482
19483                   /* GCC circa March 2002 doesn't produce the zero
19484                      type byte marking the end of the compilation
19485                      unit.  Complain if it's not there, but exit no
19486                      matter what.  */
19487
19488                   /* Do we at least have room for a macinfo type byte?  */
19489                   if (mac_ptr >= mac_end)
19490                     {
19491                       dwarf2_section_buffer_overflow_complaint (section);
19492                       return;
19493                     }
19494
19495                   /* We don't increment mac_ptr here, so this is just
19496                      a look-ahead.  */
19497                   next_type = read_1_byte (abfd, mac_ptr);
19498                   if (next_type != 0)
19499                     complaint (&symfile_complaints,
19500                                _("no terminating 0-type entry for "
19501                                  "macros in `.debug_macinfo' section"));
19502
19503                   return;
19504                 }
19505             }
19506           break;
19507
19508         case DW_MACRO_GNU_transparent_include:
19509         case DW_MACRO_GNU_transparent_include_alt:
19510           {
19511             LONGEST offset;
19512             void **slot;
19513             bfd *include_bfd = abfd;
19514             struct dwarf2_section_info *include_section = section;
19515             struct dwarf2_section_info alt_section;
19516             const gdb_byte *include_mac_end = mac_end;
19517             int is_dwz = section_is_dwz;
19518             const gdb_byte *new_mac_ptr;
19519
19520             offset = read_offset_1 (abfd, mac_ptr, offset_size);
19521             mac_ptr += offset_size;
19522
19523             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
19524               {
19525                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
19526
19527                 dwarf2_read_section (dwarf2_per_objfile->objfile,
19528                                      &dwz->macro);
19529
19530                 include_bfd = dwz->macro.asection->owner;
19531                 include_section = &dwz->macro;
19532                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
19533                 is_dwz = 1;
19534               }
19535
19536             new_mac_ptr = include_section->buffer + offset;
19537             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
19538
19539             if (*slot != NULL)
19540               {
19541                 /* This has actually happened; see
19542                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
19543                 complaint (&symfile_complaints,
19544                            _("recursive DW_MACRO_GNU_transparent_include in "
19545                              ".debug_macro section"));
19546               }
19547             else
19548               {
19549                 *slot = (void *) new_mac_ptr;
19550
19551                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
19552                                           include_mac_end, current_file,
19553                                           lh, comp_dir,
19554                                           section, section_is_gnu, is_dwz,
19555                                           offset_size, objfile, include_hash);
19556
19557                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
19558               }
19559           }
19560           break;
19561
19562         case DW_MACINFO_vendor_ext:
19563           if (!section_is_gnu)
19564             {
19565               unsigned int bytes_read;
19566               int constant;
19567
19568               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19569               mac_ptr += bytes_read;
19570               read_direct_string (abfd, mac_ptr, &bytes_read);
19571               mac_ptr += bytes_read;
19572
19573               /* We don't recognize any vendor extensions.  */
19574               break;
19575             }
19576           /* FALLTHROUGH */
19577
19578         default:
19579           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19580                                          mac_ptr, mac_end, abfd, offset_size,
19581                                          section);
19582           if (mac_ptr == NULL)
19583             return;
19584           break;
19585         }
19586     } while (macinfo_type != 0);
19587 }
19588
19589 static void
19590 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
19591                      const char *comp_dir, int section_is_gnu)
19592 {
19593   struct objfile *objfile = dwarf2_per_objfile->objfile;
19594   struct line_header *lh = cu->line_header;
19595   bfd *abfd;
19596   const gdb_byte *mac_ptr, *mac_end;
19597   struct macro_source_file *current_file = 0;
19598   enum dwarf_macro_record_type macinfo_type;
19599   unsigned int offset_size = cu->header.offset_size;
19600   const gdb_byte *opcode_definitions[256];
19601   struct cleanup *cleanup;
19602   htab_t include_hash;
19603   void **slot;
19604   struct dwarf2_section_info *section;
19605   const char *section_name;
19606
19607   if (cu->dwo_unit != NULL)
19608     {
19609       if (section_is_gnu)
19610         {
19611           section = &cu->dwo_unit->dwo_file->sections.macro;
19612           section_name = ".debug_macro.dwo";
19613         }
19614       else
19615         {
19616           section = &cu->dwo_unit->dwo_file->sections.macinfo;
19617           section_name = ".debug_macinfo.dwo";
19618         }
19619     }
19620   else
19621     {
19622       if (section_is_gnu)
19623         {
19624           section = &dwarf2_per_objfile->macro;
19625           section_name = ".debug_macro";
19626         }
19627       else
19628         {
19629           section = &dwarf2_per_objfile->macinfo;
19630           section_name = ".debug_macinfo";
19631         }
19632     }
19633
19634   dwarf2_read_section (objfile, section);
19635   if (section->buffer == NULL)
19636     {
19637       complaint (&symfile_complaints, _("missing %s section"), section_name);
19638       return;
19639     }
19640   abfd = section->asection->owner;
19641
19642   /* First pass: Find the name of the base filename.
19643      This filename is needed in order to process all macros whose definition
19644      (or undefinition) comes from the command line.  These macros are defined
19645      before the first DW_MACINFO_start_file entry, and yet still need to be
19646      associated to the base file.
19647
19648      To determine the base file name, we scan the macro definitions until we
19649      reach the first DW_MACINFO_start_file entry.  We then initialize
19650      CURRENT_FILE accordingly so that any macro definition found before the
19651      first DW_MACINFO_start_file can still be associated to the base file.  */
19652
19653   mac_ptr = section->buffer + offset;
19654   mac_end = section->buffer + section->size;
19655
19656   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
19657                                       &offset_size, section_is_gnu);
19658   if (mac_ptr == NULL)
19659     {
19660       /* We already issued a complaint.  */
19661       return;
19662     }
19663
19664   do
19665     {
19666       /* Do we at least have room for a macinfo type byte?  */
19667       if (mac_ptr >= mac_end)
19668         {
19669           /* Complaint is printed during the second pass as GDB will probably
19670              stop the first pass earlier upon finding
19671              DW_MACINFO_start_file.  */
19672           break;
19673         }
19674
19675       macinfo_type = read_1_byte (abfd, mac_ptr);
19676       mac_ptr++;
19677
19678       /* Note that we rely on the fact that the corresponding GNU and
19679          DWARF constants are the same.  */
19680       switch (macinfo_type)
19681         {
19682           /* A zero macinfo type indicates the end of the macro
19683              information.  */
19684         case 0:
19685           break;
19686
19687         case DW_MACRO_GNU_define:
19688         case DW_MACRO_GNU_undef:
19689           /* Only skip the data by MAC_PTR.  */
19690           {
19691             unsigned int bytes_read;
19692
19693             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19694             mac_ptr += bytes_read;
19695             read_direct_string (abfd, mac_ptr, &bytes_read);
19696             mac_ptr += bytes_read;
19697           }
19698           break;
19699
19700         case DW_MACRO_GNU_start_file:
19701           {
19702             unsigned int bytes_read;
19703             int line, file;
19704
19705             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19706             mac_ptr += bytes_read;
19707             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19708             mac_ptr += bytes_read;
19709
19710             current_file = macro_start_file (file, line, current_file,
19711                                              comp_dir, lh, objfile);
19712           }
19713           break;
19714
19715         case DW_MACRO_GNU_end_file:
19716           /* No data to skip by MAC_PTR.  */
19717           break;
19718
19719         case DW_MACRO_GNU_define_indirect:
19720         case DW_MACRO_GNU_undef_indirect:
19721         case DW_MACRO_GNU_define_indirect_alt:
19722         case DW_MACRO_GNU_undef_indirect_alt:
19723           {
19724             unsigned int bytes_read;
19725
19726             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19727             mac_ptr += bytes_read;
19728             mac_ptr += offset_size;
19729           }
19730           break;
19731
19732         case DW_MACRO_GNU_transparent_include:
19733         case DW_MACRO_GNU_transparent_include_alt:
19734           /* Note that, according to the spec, a transparent include
19735              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19736              skip this opcode.  */
19737           mac_ptr += offset_size;
19738           break;
19739
19740         case DW_MACINFO_vendor_ext:
19741           /* Only skip the data by MAC_PTR.  */
19742           if (!section_is_gnu)
19743             {
19744               unsigned int bytes_read;
19745
19746               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19747               mac_ptr += bytes_read;
19748               read_direct_string (abfd, mac_ptr, &bytes_read);
19749               mac_ptr += bytes_read;
19750             }
19751           /* FALLTHROUGH */
19752
19753         default:
19754           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19755                                          mac_ptr, mac_end, abfd, offset_size,
19756                                          section);
19757           if (mac_ptr == NULL)
19758             return;
19759           break;
19760         }
19761     } while (macinfo_type != 0 && current_file == NULL);
19762
19763   /* Second pass: Process all entries.
19764
19765      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19766      command-line macro definitions/undefinitions.  This flag is unset when we
19767      reach the first DW_MACINFO_start_file entry.  */
19768
19769   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19770                                     NULL, xcalloc, xfree);
19771   cleanup = make_cleanup_htab_delete (include_hash);
19772   mac_ptr = section->buffer + offset;
19773   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19774   *slot = (void *) mac_ptr;
19775   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19776                             current_file, lh, comp_dir, section,
19777                             section_is_gnu, 0,
19778                             offset_size, objfile, include_hash);
19779   do_cleanups (cleanup);
19780 }
19781
19782 /* Check if the attribute's form is a DW_FORM_block*
19783    if so return true else false.  */
19784
19785 static int
19786 attr_form_is_block (struct attribute *attr)
19787 {
19788   return (attr == NULL ? 0 :
19789       attr->form == DW_FORM_block1
19790       || attr->form == DW_FORM_block2
19791       || attr->form == DW_FORM_block4
19792       || attr->form == DW_FORM_block
19793       || attr->form == DW_FORM_exprloc);
19794 }
19795
19796 /* Return non-zero if ATTR's value is a section offset --- classes
19797    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19798    You may use DW_UNSND (attr) to retrieve such offsets.
19799
19800    Section 7.5.4, "Attribute Encodings", explains that no attribute
19801    may have a value that belongs to more than one of these classes; it
19802    would be ambiguous if we did, because we use the same forms for all
19803    of them.  */
19804
19805 static int
19806 attr_form_is_section_offset (struct attribute *attr)
19807 {
19808   return (attr->form == DW_FORM_data4
19809           || attr->form == DW_FORM_data8
19810           || attr->form == DW_FORM_sec_offset);
19811 }
19812
19813 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19814    zero otherwise.  When this function returns true, you can apply
19815    dwarf2_get_attr_constant_value to it.
19816
19817    However, note that for some attributes you must check
19818    attr_form_is_section_offset before using this test.  DW_FORM_data4
19819    and DW_FORM_data8 are members of both the constant class, and of
19820    the classes that contain offsets into other debug sections
19821    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19822    that, if an attribute's can be either a constant or one of the
19823    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19824    taken as section offsets, not constants.  */
19825
19826 static int
19827 attr_form_is_constant (struct attribute *attr)
19828 {
19829   switch (attr->form)
19830     {
19831     case DW_FORM_sdata:
19832     case DW_FORM_udata:
19833     case DW_FORM_data1:
19834     case DW_FORM_data2:
19835     case DW_FORM_data4:
19836     case DW_FORM_data8:
19837       return 1;
19838     default:
19839       return 0;
19840     }
19841 }
19842
19843 /* Return the .debug_loc section to use for CU.
19844    For DWO files use .debug_loc.dwo.  */
19845
19846 static struct dwarf2_section_info *
19847 cu_debug_loc_section (struct dwarf2_cu *cu)
19848 {
19849   if (cu->dwo_unit)
19850     return &cu->dwo_unit->dwo_file->sections.loc;
19851   return &dwarf2_per_objfile->loc;
19852 }
19853
19854 /* A helper function that fills in a dwarf2_loclist_baton.  */
19855
19856 static void
19857 fill_in_loclist_baton (struct dwarf2_cu *cu,
19858                        struct dwarf2_loclist_baton *baton,
19859                        struct attribute *attr)
19860 {
19861   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19862
19863   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19864
19865   baton->per_cu = cu->per_cu;
19866   gdb_assert (baton->per_cu);
19867   /* We don't know how long the location list is, but make sure we
19868      don't run off the edge of the section.  */
19869   baton->size = section->size - DW_UNSND (attr);
19870   baton->data = section->buffer + DW_UNSND (attr);
19871   baton->base_address = cu->base_address;
19872   baton->from_dwo = cu->dwo_unit != NULL;
19873 }
19874
19875 static void
19876 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19877                              struct dwarf2_cu *cu, int is_block)
19878 {
19879   struct objfile *objfile = dwarf2_per_objfile->objfile;
19880   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19881
19882   if (attr_form_is_section_offset (attr)
19883       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19884          the section.  If so, fall through to the complaint in the
19885          other branch.  */
19886       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19887     {
19888       struct dwarf2_loclist_baton *baton;
19889
19890       baton = obstack_alloc (&objfile->objfile_obstack,
19891                              sizeof (struct dwarf2_loclist_baton));
19892
19893       fill_in_loclist_baton (cu, baton, attr);
19894
19895       if (cu->base_known == 0)
19896         complaint (&symfile_complaints,
19897                    _("Location list used without "
19898                      "specifying the CU base address."));
19899
19900       SYMBOL_ACLASS_INDEX (sym) = (is_block
19901                                    ? dwarf2_loclist_block_index
19902                                    : dwarf2_loclist_index);
19903       SYMBOL_LOCATION_BATON (sym) = baton;
19904     }
19905   else
19906     {
19907       struct dwarf2_locexpr_baton *baton;
19908
19909       baton = obstack_alloc (&objfile->objfile_obstack,
19910                              sizeof (struct dwarf2_locexpr_baton));
19911       baton->per_cu = cu->per_cu;
19912       gdb_assert (baton->per_cu);
19913
19914       if (attr_form_is_block (attr))
19915         {
19916           /* Note that we're just copying the block's data pointer
19917              here, not the actual data.  We're still pointing into the
19918              info_buffer for SYM's objfile; right now we never release
19919              that buffer, but when we do clean up properly this may
19920              need to change.  */
19921           baton->size = DW_BLOCK (attr)->size;
19922           baton->data = DW_BLOCK (attr)->data;
19923         }
19924       else
19925         {
19926           dwarf2_invalid_attrib_class_complaint ("location description",
19927                                                  SYMBOL_NATURAL_NAME (sym));
19928           baton->size = 0;
19929         }
19930
19931       SYMBOL_ACLASS_INDEX (sym) = (is_block
19932                                    ? dwarf2_locexpr_block_index
19933                                    : dwarf2_locexpr_index);
19934       SYMBOL_LOCATION_BATON (sym) = baton;
19935     }
19936 }
19937
19938 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19939    came from a separate debuginfo file, then the master objfile is
19940    returned.  */
19941
19942 struct objfile *
19943 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19944 {
19945   struct objfile *objfile = per_cu->objfile;
19946
19947   /* Return the master objfile, so that we can report and look up the
19948      correct file containing this variable.  */
19949   if (objfile->separate_debug_objfile_backlink)
19950     objfile = objfile->separate_debug_objfile_backlink;
19951
19952   return objfile;
19953 }
19954
19955 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19956    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19957    CU_HEADERP first.  */
19958
19959 static const struct comp_unit_head *
19960 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19961                        struct dwarf2_per_cu_data *per_cu)
19962 {
19963   const gdb_byte *info_ptr;
19964
19965   if (per_cu->cu)
19966     return &per_cu->cu->header;
19967
19968   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19969
19970   memset (cu_headerp, 0, sizeof (*cu_headerp));
19971   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19972
19973   return cu_headerp;
19974 }
19975
19976 /* Return the address size given in the compilation unit header for CU.  */
19977
19978 int
19979 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19980 {
19981   struct comp_unit_head cu_header_local;
19982   const struct comp_unit_head *cu_headerp;
19983
19984   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19985
19986   return cu_headerp->addr_size;
19987 }
19988
19989 /* Return the offset size given in the compilation unit header for CU.  */
19990
19991 int
19992 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19993 {
19994   struct comp_unit_head cu_header_local;
19995   const struct comp_unit_head *cu_headerp;
19996
19997   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19998
19999   return cu_headerp->offset_size;
20000 }
20001
20002 /* See its dwarf2loc.h declaration.  */
20003
20004 int
20005 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20006 {
20007   struct comp_unit_head cu_header_local;
20008   const struct comp_unit_head *cu_headerp;
20009
20010   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20011
20012   if (cu_headerp->version == 2)
20013     return cu_headerp->addr_size;
20014   else
20015     return cu_headerp->offset_size;
20016 }
20017
20018 /* Return the text offset of the CU.  The returned offset comes from
20019    this CU's objfile.  If this objfile came from a separate debuginfo
20020    file, then the offset may be different from the corresponding
20021    offset in the parent objfile.  */
20022
20023 CORE_ADDR
20024 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20025 {
20026   struct objfile *objfile = per_cu->objfile;
20027
20028   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20029 }
20030
20031 /* Locate the .debug_info compilation unit from CU's objfile which contains
20032    the DIE at OFFSET.  Raises an error on failure.  */
20033
20034 static struct dwarf2_per_cu_data *
20035 dwarf2_find_containing_comp_unit (sect_offset offset,
20036                                   unsigned int offset_in_dwz,
20037                                   struct objfile *objfile)
20038 {
20039   struct dwarf2_per_cu_data *this_cu;
20040   int low, high;
20041   const sect_offset *cu_off;
20042
20043   low = 0;
20044   high = dwarf2_per_objfile->n_comp_units - 1;
20045   while (high > low)
20046     {
20047       struct dwarf2_per_cu_data *mid_cu;
20048       int mid = low + (high - low) / 2;
20049
20050       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20051       cu_off = &mid_cu->offset;
20052       if (mid_cu->is_dwz > offset_in_dwz
20053           || (mid_cu->is_dwz == offset_in_dwz
20054               && cu_off->sect_off >= offset.sect_off))
20055         high = mid;
20056       else
20057         low = mid + 1;
20058     }
20059   gdb_assert (low == high);
20060   this_cu = dwarf2_per_objfile->all_comp_units[low];
20061   cu_off = &this_cu->offset;
20062   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20063     {
20064       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20065         error (_("Dwarf Error: could not find partial DIE containing "
20066                "offset 0x%lx [in module %s]"),
20067                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20068
20069       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20070                   <= offset.sect_off);
20071       return dwarf2_per_objfile->all_comp_units[low-1];
20072     }
20073   else
20074     {
20075       this_cu = dwarf2_per_objfile->all_comp_units[low];
20076       if (low == dwarf2_per_objfile->n_comp_units - 1
20077           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20078         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20079       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20080       return this_cu;
20081     }
20082 }
20083
20084 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20085
20086 static void
20087 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20088 {
20089   memset (cu, 0, sizeof (*cu));
20090   per_cu->cu = cu;
20091   cu->per_cu = per_cu;
20092   cu->objfile = per_cu->objfile;
20093   obstack_init (&cu->comp_unit_obstack);
20094 }
20095
20096 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20097
20098 static void
20099 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20100                        enum language pretend_language)
20101 {
20102   struct attribute *attr;
20103
20104   /* Set the language we're debugging.  */
20105   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20106   if (attr)
20107     set_cu_language (DW_UNSND (attr), cu);
20108   else
20109     {
20110       cu->language = pretend_language;
20111       cu->language_defn = language_def (cu->language);
20112     }
20113
20114   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20115   if (attr)
20116     cu->producer = DW_STRING (attr);
20117 }
20118
20119 /* Release one cached compilation unit, CU.  We unlink it from the tree
20120    of compilation units, but we don't remove it from the read_in_chain;
20121    the caller is responsible for that.
20122    NOTE: DATA is a void * because this function is also used as a
20123    cleanup routine.  */
20124
20125 static void
20126 free_heap_comp_unit (void *data)
20127 {
20128   struct dwarf2_cu *cu = data;
20129
20130   gdb_assert (cu->per_cu != NULL);
20131   cu->per_cu->cu = NULL;
20132   cu->per_cu = NULL;
20133
20134   obstack_free (&cu->comp_unit_obstack, NULL);
20135
20136   xfree (cu);
20137 }
20138
20139 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20140    when we're finished with it.  We can't free the pointer itself, but be
20141    sure to unlink it from the cache.  Also release any associated storage.  */
20142
20143 static void
20144 free_stack_comp_unit (void *data)
20145 {
20146   struct dwarf2_cu *cu = data;
20147
20148   gdb_assert (cu->per_cu != NULL);
20149   cu->per_cu->cu = NULL;
20150   cu->per_cu = NULL;
20151
20152   obstack_free (&cu->comp_unit_obstack, NULL);
20153   cu->partial_dies = NULL;
20154 }
20155
20156 /* Free all cached compilation units.  */
20157
20158 static void
20159 free_cached_comp_units (void *data)
20160 {
20161   struct dwarf2_per_cu_data *per_cu, **last_chain;
20162
20163   per_cu = dwarf2_per_objfile->read_in_chain;
20164   last_chain = &dwarf2_per_objfile->read_in_chain;
20165   while (per_cu != NULL)
20166     {
20167       struct dwarf2_per_cu_data *next_cu;
20168
20169       next_cu = per_cu->cu->read_in_chain;
20170
20171       free_heap_comp_unit (per_cu->cu);
20172       *last_chain = next_cu;
20173
20174       per_cu = next_cu;
20175     }
20176 }
20177
20178 /* Increase the age counter on each cached compilation unit, and free
20179    any that are too old.  */
20180
20181 static void
20182 age_cached_comp_units (void)
20183 {
20184   struct dwarf2_per_cu_data *per_cu, **last_chain;
20185
20186   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
20187   per_cu = dwarf2_per_objfile->read_in_chain;
20188   while (per_cu != NULL)
20189     {
20190       per_cu->cu->last_used ++;
20191       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
20192         dwarf2_mark (per_cu->cu);
20193       per_cu = per_cu->cu->read_in_chain;
20194     }
20195
20196   per_cu = dwarf2_per_objfile->read_in_chain;
20197   last_chain = &dwarf2_per_objfile->read_in_chain;
20198   while (per_cu != NULL)
20199     {
20200       struct dwarf2_per_cu_data *next_cu;
20201
20202       next_cu = per_cu->cu->read_in_chain;
20203
20204       if (!per_cu->cu->mark)
20205         {
20206           free_heap_comp_unit (per_cu->cu);
20207           *last_chain = next_cu;
20208         }
20209       else
20210         last_chain = &per_cu->cu->read_in_chain;
20211
20212       per_cu = next_cu;
20213     }
20214 }
20215
20216 /* Remove a single compilation unit from the cache.  */
20217
20218 static void
20219 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
20220 {
20221   struct dwarf2_per_cu_data *per_cu, **last_chain;
20222
20223   per_cu = dwarf2_per_objfile->read_in_chain;
20224   last_chain = &dwarf2_per_objfile->read_in_chain;
20225   while (per_cu != NULL)
20226     {
20227       struct dwarf2_per_cu_data *next_cu;
20228
20229       next_cu = per_cu->cu->read_in_chain;
20230
20231       if (per_cu == target_per_cu)
20232         {
20233           free_heap_comp_unit (per_cu->cu);
20234           per_cu->cu = NULL;
20235           *last_chain = next_cu;
20236           break;
20237         }
20238       else
20239         last_chain = &per_cu->cu->read_in_chain;
20240
20241       per_cu = next_cu;
20242     }
20243 }
20244
20245 /* Release all extra memory associated with OBJFILE.  */
20246
20247 void
20248 dwarf2_free_objfile (struct objfile *objfile)
20249 {
20250   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20251
20252   if (dwarf2_per_objfile == NULL)
20253     return;
20254
20255   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
20256   free_cached_comp_units (NULL);
20257
20258   if (dwarf2_per_objfile->quick_file_names_table)
20259     htab_delete (dwarf2_per_objfile->quick_file_names_table);
20260
20261   /* Everything else should be on the objfile obstack.  */
20262 }
20263
20264 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
20265    We store these in a hash table separate from the DIEs, and preserve them
20266    when the DIEs are flushed out of cache.
20267
20268    The CU "per_cu" pointer is needed because offset alone is not enough to
20269    uniquely identify the type.  A file may have multiple .debug_types sections,
20270    or the type may come from a DWO file.  Furthermore, while it's more logical
20271    to use per_cu->section+offset, with Fission the section with the data is in
20272    the DWO file but we don't know that section at the point we need it.
20273    We have to use something in dwarf2_per_cu_data (or the pointer to it)
20274    because we can enter the lookup routine, get_die_type_at_offset, from
20275    outside this file, and thus won't necessarily have PER_CU->cu.
20276    Fortunately, PER_CU is stable for the life of the objfile.  */
20277
20278 struct dwarf2_per_cu_offset_and_type
20279 {
20280   const struct dwarf2_per_cu_data *per_cu;
20281   sect_offset offset;
20282   struct type *type;
20283 };
20284
20285 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
20286
20287 static hashval_t
20288 per_cu_offset_and_type_hash (const void *item)
20289 {
20290   const struct dwarf2_per_cu_offset_and_type *ofs = item;
20291
20292   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
20293 }
20294
20295 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
20296
20297 static int
20298 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
20299 {
20300   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
20301   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
20302
20303   return (ofs_lhs->per_cu == ofs_rhs->per_cu
20304           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
20305 }
20306
20307 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
20308    table if necessary.  For convenience, return TYPE.
20309
20310    The DIEs reading must have careful ordering to:
20311     * Not cause infite loops trying to read in DIEs as a prerequisite for
20312       reading current DIE.
20313     * Not trying to dereference contents of still incompletely read in types
20314       while reading in other DIEs.
20315     * Enable referencing still incompletely read in types just by a pointer to
20316       the type without accessing its fields.
20317
20318    Therefore caller should follow these rules:
20319      * Try to fetch any prerequisite types we may need to build this DIE type
20320        before building the type and calling set_die_type.
20321      * After building type call set_die_type for current DIE as soon as
20322        possible before fetching more types to complete the current type.
20323      * Make the type as complete as possible before fetching more types.  */
20324
20325 static struct type *
20326 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20327 {
20328   struct dwarf2_per_cu_offset_and_type **slot, ofs;
20329   struct objfile *objfile = cu->objfile;
20330
20331   /* For Ada types, make sure that the gnat-specific data is always
20332      initialized (if not already set).  There are a few types where
20333      we should not be doing so, because the type-specific area is
20334      already used to hold some other piece of info (eg: TYPE_CODE_FLT
20335      where the type-specific area is used to store the floatformat).
20336      But this is not a problem, because the gnat-specific information
20337      is actually not needed for these types.  */
20338   if (need_gnat_info (cu)
20339       && TYPE_CODE (type) != TYPE_CODE_FUNC
20340       && TYPE_CODE (type) != TYPE_CODE_FLT
20341       && !HAVE_GNAT_AUX_INFO (type))
20342     INIT_GNAT_SPECIFIC (type);
20343
20344   if (dwarf2_per_objfile->die_type_hash == NULL)
20345     {
20346       dwarf2_per_objfile->die_type_hash =
20347         htab_create_alloc_ex (127,
20348                               per_cu_offset_and_type_hash,
20349                               per_cu_offset_and_type_eq,
20350                               NULL,
20351                               &objfile->objfile_obstack,
20352                               hashtab_obstack_allocate,
20353                               dummy_obstack_deallocate);
20354     }
20355
20356   ofs.per_cu = cu->per_cu;
20357   ofs.offset = die->offset;
20358   ofs.type = type;
20359   slot = (struct dwarf2_per_cu_offset_and_type **)
20360     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
20361   if (*slot)
20362     complaint (&symfile_complaints,
20363                _("A problem internal to GDB: DIE 0x%x has type already set"),
20364                die->offset.sect_off);
20365   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
20366   **slot = ofs;
20367   return type;
20368 }
20369
20370 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
20371    or return NULL if the die does not have a saved type.  */
20372
20373 static struct type *
20374 get_die_type_at_offset (sect_offset offset,
20375                         struct dwarf2_per_cu_data *per_cu)
20376 {
20377   struct dwarf2_per_cu_offset_and_type *slot, ofs;
20378
20379   if (dwarf2_per_objfile->die_type_hash == NULL)
20380     return NULL;
20381
20382   ofs.per_cu = per_cu;
20383   ofs.offset = offset;
20384   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
20385   if (slot)
20386     return slot->type;
20387   else
20388     return NULL;
20389 }
20390
20391 /* Look up the type for DIE in CU in die_type_hash,
20392    or return NULL if DIE does not have a saved type.  */
20393
20394 static struct type *
20395 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
20396 {
20397   return get_die_type_at_offset (die->offset, cu->per_cu);
20398 }
20399
20400 /* Add a dependence relationship from CU to REF_PER_CU.  */
20401
20402 static void
20403 dwarf2_add_dependence (struct dwarf2_cu *cu,
20404                        struct dwarf2_per_cu_data *ref_per_cu)
20405 {
20406   void **slot;
20407
20408   if (cu->dependencies == NULL)
20409     cu->dependencies
20410       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
20411                               NULL, &cu->comp_unit_obstack,
20412                               hashtab_obstack_allocate,
20413                               dummy_obstack_deallocate);
20414
20415   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
20416   if (*slot == NULL)
20417     *slot = ref_per_cu;
20418 }
20419
20420 /* Subroutine of dwarf2_mark to pass to htab_traverse.
20421    Set the mark field in every compilation unit in the
20422    cache that we must keep because we are keeping CU.  */
20423
20424 static int
20425 dwarf2_mark_helper (void **slot, void *data)
20426 {
20427   struct dwarf2_per_cu_data *per_cu;
20428
20429   per_cu = (struct dwarf2_per_cu_data *) *slot;
20430
20431   /* cu->dependencies references may not yet have been ever read if QUIT aborts
20432      reading of the chain.  As such dependencies remain valid it is not much
20433      useful to track and undo them during QUIT cleanups.  */
20434   if (per_cu->cu == NULL)
20435     return 1;
20436
20437   if (per_cu->cu->mark)
20438     return 1;
20439   per_cu->cu->mark = 1;
20440
20441   if (per_cu->cu->dependencies != NULL)
20442     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
20443
20444   return 1;
20445 }
20446
20447 /* Set the mark field in CU and in every other compilation unit in the
20448    cache that we must keep because we are keeping CU.  */
20449
20450 static void
20451 dwarf2_mark (struct dwarf2_cu *cu)
20452 {
20453   if (cu->mark)
20454     return;
20455   cu->mark = 1;
20456   if (cu->dependencies != NULL)
20457     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
20458 }
20459
20460 static void
20461 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
20462 {
20463   while (per_cu)
20464     {
20465       per_cu->cu->mark = 0;
20466       per_cu = per_cu->cu->read_in_chain;
20467     }
20468 }
20469
20470 /* Trivial hash function for partial_die_info: the hash value of a DIE
20471    is its offset in .debug_info for this objfile.  */
20472
20473 static hashval_t
20474 partial_die_hash (const void *item)
20475 {
20476   const struct partial_die_info *part_die = item;
20477
20478   return part_die->offset.sect_off;
20479 }
20480
20481 /* Trivial comparison function for partial_die_info structures: two DIEs
20482    are equal if they have the same offset.  */
20483
20484 static int
20485 partial_die_eq (const void *item_lhs, const void *item_rhs)
20486 {
20487   const struct partial_die_info *part_die_lhs = item_lhs;
20488   const struct partial_die_info *part_die_rhs = item_rhs;
20489
20490   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
20491 }
20492
20493 static struct cmd_list_element *set_dwarf2_cmdlist;
20494 static struct cmd_list_element *show_dwarf2_cmdlist;
20495
20496 static void
20497 set_dwarf2_cmd (char *args, int from_tty)
20498 {
20499   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
20500 }
20501
20502 static void
20503 show_dwarf2_cmd (char *args, int from_tty)
20504 {
20505   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
20506 }
20507
20508 /* Free data associated with OBJFILE, if necessary.  */
20509
20510 static void
20511 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
20512 {
20513   struct dwarf2_per_objfile *data = d;
20514   int ix;
20515
20516   for (ix = 0; ix < data->n_comp_units; ++ix)
20517    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
20518
20519   for (ix = 0; ix < data->n_type_units; ++ix)
20520     VEC_free (dwarf2_per_cu_ptr,
20521               data->all_type_units[ix]->per_cu.imported_symtabs);
20522   xfree (data->all_type_units);
20523
20524   VEC_free (dwarf2_section_info_def, data->types);
20525
20526   if (data->dwo_files)
20527     free_dwo_files (data->dwo_files, objfile);
20528   if (data->dwp_file)
20529     gdb_bfd_unref (data->dwp_file->dbfd);
20530
20531   if (data->dwz_file && data->dwz_file->dwz_bfd)
20532     gdb_bfd_unref (data->dwz_file->dwz_bfd);
20533 }
20534
20535 \f
20536 /* The "save gdb-index" command.  */
20537
20538 /* The contents of the hash table we create when building the string
20539    table.  */
20540 struct strtab_entry
20541 {
20542   offset_type offset;
20543   const char *str;
20544 };
20545
20546 /* Hash function for a strtab_entry.
20547
20548    Function is used only during write_hash_table so no index format backward
20549    compatibility is needed.  */
20550
20551 static hashval_t
20552 hash_strtab_entry (const void *e)
20553 {
20554   const struct strtab_entry *entry = e;
20555   return mapped_index_string_hash (INT_MAX, entry->str);
20556 }
20557
20558 /* Equality function for a strtab_entry.  */
20559
20560 static int
20561 eq_strtab_entry (const void *a, const void *b)
20562 {
20563   const struct strtab_entry *ea = a;
20564   const struct strtab_entry *eb = b;
20565   return !strcmp (ea->str, eb->str);
20566 }
20567
20568 /* Create a strtab_entry hash table.  */
20569
20570 static htab_t
20571 create_strtab (void)
20572 {
20573   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
20574                             xfree, xcalloc, xfree);
20575 }
20576
20577 /* Add a string to the constant pool.  Return the string's offset in
20578    host order.  */
20579
20580 static offset_type
20581 add_string (htab_t table, struct obstack *cpool, const char *str)
20582 {
20583   void **slot;
20584   struct strtab_entry entry;
20585   struct strtab_entry *result;
20586
20587   entry.str = str;
20588   slot = htab_find_slot (table, &entry, INSERT);
20589   if (*slot)
20590     result = *slot;
20591   else
20592     {
20593       result = XNEW (struct strtab_entry);
20594       result->offset = obstack_object_size (cpool);
20595       result->str = str;
20596       obstack_grow_str0 (cpool, str);
20597       *slot = result;
20598     }
20599   return result->offset;
20600 }
20601
20602 /* An entry in the symbol table.  */
20603 struct symtab_index_entry
20604 {
20605   /* The name of the symbol.  */
20606   const char *name;
20607   /* The offset of the name in the constant pool.  */
20608   offset_type index_offset;
20609   /* A sorted vector of the indices of all the CUs that hold an object
20610      of this name.  */
20611   VEC (offset_type) *cu_indices;
20612 };
20613
20614 /* The symbol table.  This is a power-of-2-sized hash table.  */
20615 struct mapped_symtab
20616 {
20617   offset_type n_elements;
20618   offset_type size;
20619   struct symtab_index_entry **data;
20620 };
20621
20622 /* Hash function for a symtab_index_entry.  */
20623
20624 static hashval_t
20625 hash_symtab_entry (const void *e)
20626 {
20627   const struct symtab_index_entry *entry = e;
20628   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
20629                          sizeof (offset_type) * VEC_length (offset_type,
20630                                                             entry->cu_indices),
20631                          0);
20632 }
20633
20634 /* Equality function for a symtab_index_entry.  */
20635
20636 static int
20637 eq_symtab_entry (const void *a, const void *b)
20638 {
20639   const struct symtab_index_entry *ea = a;
20640   const struct symtab_index_entry *eb = b;
20641   int len = VEC_length (offset_type, ea->cu_indices);
20642   if (len != VEC_length (offset_type, eb->cu_indices))
20643     return 0;
20644   return !memcmp (VEC_address (offset_type, ea->cu_indices),
20645                   VEC_address (offset_type, eb->cu_indices),
20646                   sizeof (offset_type) * len);
20647 }
20648
20649 /* Destroy a symtab_index_entry.  */
20650
20651 static void
20652 delete_symtab_entry (void *p)
20653 {
20654   struct symtab_index_entry *entry = p;
20655   VEC_free (offset_type, entry->cu_indices);
20656   xfree (entry);
20657 }
20658
20659 /* Create a hash table holding symtab_index_entry objects.  */
20660
20661 static htab_t
20662 create_symbol_hash_table (void)
20663 {
20664   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
20665                             delete_symtab_entry, xcalloc, xfree);
20666 }
20667
20668 /* Create a new mapped symtab object.  */
20669
20670 static struct mapped_symtab *
20671 create_mapped_symtab (void)
20672 {
20673   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20674   symtab->n_elements = 0;
20675   symtab->size = 1024;
20676   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20677   return symtab;
20678 }
20679
20680 /* Destroy a mapped_symtab.  */
20681
20682 static void
20683 cleanup_mapped_symtab (void *p)
20684 {
20685   struct mapped_symtab *symtab = p;
20686   /* The contents of the array are freed when the other hash table is
20687      destroyed.  */
20688   xfree (symtab->data);
20689   xfree (symtab);
20690 }
20691
20692 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20693    the slot.
20694    
20695    Function is used only during write_hash_table so no index format backward
20696    compatibility is needed.  */
20697
20698 static struct symtab_index_entry **
20699 find_slot (struct mapped_symtab *symtab, const char *name)
20700 {
20701   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20702
20703   index = hash & (symtab->size - 1);
20704   step = ((hash * 17) & (symtab->size - 1)) | 1;
20705
20706   for (;;)
20707     {
20708       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20709         return &symtab->data[index];
20710       index = (index + step) & (symtab->size - 1);
20711     }
20712 }
20713
20714 /* Expand SYMTAB's hash table.  */
20715
20716 static void
20717 hash_expand (struct mapped_symtab *symtab)
20718 {
20719   offset_type old_size = symtab->size;
20720   offset_type i;
20721   struct symtab_index_entry **old_entries = symtab->data;
20722
20723   symtab->size *= 2;
20724   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20725
20726   for (i = 0; i < old_size; ++i)
20727     {
20728       if (old_entries[i])
20729         {
20730           struct symtab_index_entry **slot = find_slot (symtab,
20731                                                         old_entries[i]->name);
20732           *slot = old_entries[i];
20733         }
20734     }
20735
20736   xfree (old_entries);
20737 }
20738
20739 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20740    CU_INDEX is the index of the CU in which the symbol appears.
20741    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20742
20743 static void
20744 add_index_entry (struct mapped_symtab *symtab, const char *name,
20745                  int is_static, gdb_index_symbol_kind kind,
20746                  offset_type cu_index)
20747 {
20748   struct symtab_index_entry **slot;
20749   offset_type cu_index_and_attrs;
20750
20751   ++symtab->n_elements;
20752   if (4 * symtab->n_elements / 3 >= symtab->size)
20753     hash_expand (symtab);
20754
20755   slot = find_slot (symtab, name);
20756   if (!*slot)
20757     {
20758       *slot = XNEW (struct symtab_index_entry);
20759       (*slot)->name = name;
20760       /* index_offset is set later.  */
20761       (*slot)->cu_indices = NULL;
20762     }
20763
20764   cu_index_and_attrs = 0;
20765   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20766   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20767   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20768
20769   /* We don't want to record an index value twice as we want to avoid the
20770      duplication.
20771      We process all global symbols and then all static symbols
20772      (which would allow us to avoid the duplication by only having to check
20773      the last entry pushed), but a symbol could have multiple kinds in one CU.
20774      To keep things simple we don't worry about the duplication here and
20775      sort and uniqufy the list after we've processed all symbols.  */
20776   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20777 }
20778
20779 /* qsort helper routine for uniquify_cu_indices.  */
20780
20781 static int
20782 offset_type_compare (const void *ap, const void *bp)
20783 {
20784   offset_type a = *(offset_type *) ap;
20785   offset_type b = *(offset_type *) bp;
20786
20787   return (a > b) - (b > a);
20788 }
20789
20790 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20791
20792 static void
20793 uniquify_cu_indices (struct mapped_symtab *symtab)
20794 {
20795   int i;
20796
20797   for (i = 0; i < symtab->size; ++i)
20798     {
20799       struct symtab_index_entry *entry = symtab->data[i];
20800
20801       if (entry
20802           && entry->cu_indices != NULL)
20803         {
20804           unsigned int next_to_insert, next_to_check;
20805           offset_type last_value;
20806
20807           qsort (VEC_address (offset_type, entry->cu_indices),
20808                  VEC_length (offset_type, entry->cu_indices),
20809                  sizeof (offset_type), offset_type_compare);
20810
20811           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20812           next_to_insert = 1;
20813           for (next_to_check = 1;
20814                next_to_check < VEC_length (offset_type, entry->cu_indices);
20815                ++next_to_check)
20816             {
20817               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20818                   != last_value)
20819                 {
20820                   last_value = VEC_index (offset_type, entry->cu_indices,
20821                                           next_to_check);
20822                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20823                                last_value);
20824                   ++next_to_insert;
20825                 }
20826             }
20827           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20828         }
20829     }
20830 }
20831
20832 /* Add a vector of indices to the constant pool.  */
20833
20834 static offset_type
20835 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20836                       struct symtab_index_entry *entry)
20837 {
20838   void **slot;
20839
20840   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20841   if (!*slot)
20842     {
20843       offset_type len = VEC_length (offset_type, entry->cu_indices);
20844       offset_type val = MAYBE_SWAP (len);
20845       offset_type iter;
20846       int i;
20847
20848       *slot = entry;
20849       entry->index_offset = obstack_object_size (cpool);
20850
20851       obstack_grow (cpool, &val, sizeof (val));
20852       for (i = 0;
20853            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20854            ++i)
20855         {
20856           val = MAYBE_SWAP (iter);
20857           obstack_grow (cpool, &val, sizeof (val));
20858         }
20859     }
20860   else
20861     {
20862       struct symtab_index_entry *old_entry = *slot;
20863       entry->index_offset = old_entry->index_offset;
20864       entry = old_entry;
20865     }
20866   return entry->index_offset;
20867 }
20868
20869 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20870    constant pool entries going into the obstack CPOOL.  */
20871
20872 static void
20873 write_hash_table (struct mapped_symtab *symtab,
20874                   struct obstack *output, struct obstack *cpool)
20875 {
20876   offset_type i;
20877   htab_t symbol_hash_table;
20878   htab_t str_table;
20879
20880   symbol_hash_table = create_symbol_hash_table ();
20881   str_table = create_strtab ();
20882
20883   /* We add all the index vectors to the constant pool first, to
20884      ensure alignment is ok.  */
20885   for (i = 0; i < symtab->size; ++i)
20886     {
20887       if (symtab->data[i])
20888         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20889     }
20890
20891   /* Now write out the hash table.  */
20892   for (i = 0; i < symtab->size; ++i)
20893     {
20894       offset_type str_off, vec_off;
20895
20896       if (symtab->data[i])
20897         {
20898           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20899           vec_off = symtab->data[i]->index_offset;
20900         }
20901       else
20902         {
20903           /* While 0 is a valid constant pool index, it is not valid
20904              to have 0 for both offsets.  */
20905           str_off = 0;
20906           vec_off = 0;
20907         }
20908
20909       str_off = MAYBE_SWAP (str_off);
20910       vec_off = MAYBE_SWAP (vec_off);
20911
20912       obstack_grow (output, &str_off, sizeof (str_off));
20913       obstack_grow (output, &vec_off, sizeof (vec_off));
20914     }
20915
20916   htab_delete (str_table);
20917   htab_delete (symbol_hash_table);
20918 }
20919
20920 /* Struct to map psymtab to CU index in the index file.  */
20921 struct psymtab_cu_index_map
20922 {
20923   struct partial_symtab *psymtab;
20924   unsigned int cu_index;
20925 };
20926
20927 static hashval_t
20928 hash_psymtab_cu_index (const void *item)
20929 {
20930   const struct psymtab_cu_index_map *map = item;
20931
20932   return htab_hash_pointer (map->psymtab);
20933 }
20934
20935 static int
20936 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20937 {
20938   const struct psymtab_cu_index_map *lhs = item_lhs;
20939   const struct psymtab_cu_index_map *rhs = item_rhs;
20940
20941   return lhs->psymtab == rhs->psymtab;
20942 }
20943
20944 /* Helper struct for building the address table.  */
20945 struct addrmap_index_data
20946 {
20947   struct objfile *objfile;
20948   struct obstack *addr_obstack;
20949   htab_t cu_index_htab;
20950
20951   /* Non-zero if the previous_* fields are valid.
20952      We can't write an entry until we see the next entry (since it is only then
20953      that we know the end of the entry).  */
20954   int previous_valid;
20955   /* Index of the CU in the table of all CUs in the index file.  */
20956   unsigned int previous_cu_index;
20957   /* Start address of the CU.  */
20958   CORE_ADDR previous_cu_start;
20959 };
20960
20961 /* Write an address entry to OBSTACK.  */
20962
20963 static void
20964 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20965                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20966 {
20967   offset_type cu_index_to_write;
20968   gdb_byte addr[8];
20969   CORE_ADDR baseaddr;
20970
20971   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20972
20973   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20974   obstack_grow (obstack, addr, 8);
20975   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20976   obstack_grow (obstack, addr, 8);
20977   cu_index_to_write = MAYBE_SWAP (cu_index);
20978   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20979 }
20980
20981 /* Worker function for traversing an addrmap to build the address table.  */
20982
20983 static int
20984 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20985 {
20986   struct addrmap_index_data *data = datap;
20987   struct partial_symtab *pst = obj;
20988
20989   if (data->previous_valid)
20990     add_address_entry (data->objfile, data->addr_obstack,
20991                        data->previous_cu_start, start_addr,
20992                        data->previous_cu_index);
20993
20994   data->previous_cu_start = start_addr;
20995   if (pst != NULL)
20996     {
20997       struct psymtab_cu_index_map find_map, *map;
20998       find_map.psymtab = pst;
20999       map = htab_find (data->cu_index_htab, &find_map);
21000       gdb_assert (map != NULL);
21001       data->previous_cu_index = map->cu_index;
21002       data->previous_valid = 1;
21003     }
21004   else
21005       data->previous_valid = 0;
21006
21007   return 0;
21008 }
21009
21010 /* Write OBJFILE's address map to OBSTACK.
21011    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21012    in the index file.  */
21013
21014 static void
21015 write_address_map (struct objfile *objfile, struct obstack *obstack,
21016                    htab_t cu_index_htab)
21017 {
21018   struct addrmap_index_data addrmap_index_data;
21019
21020   /* When writing the address table, we have to cope with the fact that
21021      the addrmap iterator only provides the start of a region; we have to
21022      wait until the next invocation to get the start of the next region.  */
21023
21024   addrmap_index_data.objfile = objfile;
21025   addrmap_index_data.addr_obstack = obstack;
21026   addrmap_index_data.cu_index_htab = cu_index_htab;
21027   addrmap_index_data.previous_valid = 0;
21028
21029   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21030                    &addrmap_index_data);
21031
21032   /* It's highly unlikely the last entry (end address = 0xff...ff)
21033      is valid, but we should still handle it.
21034      The end address is recorded as the start of the next region, but that
21035      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21036      anyway.  */
21037   if (addrmap_index_data.previous_valid)
21038     add_address_entry (objfile, obstack,
21039                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21040                        addrmap_index_data.previous_cu_index);
21041 }
21042
21043 /* Return the symbol kind of PSYM.  */
21044
21045 static gdb_index_symbol_kind
21046 symbol_kind (struct partial_symbol *psym)
21047 {
21048   domain_enum domain = PSYMBOL_DOMAIN (psym);
21049   enum address_class aclass = PSYMBOL_CLASS (psym);
21050
21051   switch (domain)
21052     {
21053     case VAR_DOMAIN:
21054       switch (aclass)
21055         {
21056         case LOC_BLOCK:
21057           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21058         case LOC_TYPEDEF:
21059           return GDB_INDEX_SYMBOL_KIND_TYPE;
21060         case LOC_COMPUTED:
21061         case LOC_CONST_BYTES:
21062         case LOC_OPTIMIZED_OUT:
21063         case LOC_STATIC:
21064           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21065         case LOC_CONST:
21066           /* Note: It's currently impossible to recognize psyms as enum values
21067              short of reading the type info.  For now punt.  */
21068           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21069         default:
21070           /* There are other LOC_FOO values that one might want to classify
21071              as variables, but dwarf2read.c doesn't currently use them.  */
21072           return GDB_INDEX_SYMBOL_KIND_OTHER;
21073         }
21074     case STRUCT_DOMAIN:
21075       return GDB_INDEX_SYMBOL_KIND_TYPE;
21076     default:
21077       return GDB_INDEX_SYMBOL_KIND_OTHER;
21078     }
21079 }
21080
21081 /* Add a list of partial symbols to SYMTAB.  */
21082
21083 static void
21084 write_psymbols (struct mapped_symtab *symtab,
21085                 htab_t psyms_seen,
21086                 struct partial_symbol **psymp,
21087                 int count,
21088                 offset_type cu_index,
21089                 int is_static)
21090 {
21091   for (; count-- > 0; ++psymp)
21092     {
21093       struct partial_symbol *psym = *psymp;
21094       void **slot;
21095
21096       if (SYMBOL_LANGUAGE (psym) == language_ada)
21097         error (_("Ada is not currently supported by the index"));
21098
21099       /* Only add a given psymbol once.  */
21100       slot = htab_find_slot (psyms_seen, psym, INSERT);
21101       if (!*slot)
21102         {
21103           gdb_index_symbol_kind kind = symbol_kind (psym);
21104
21105           *slot = psym;
21106           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21107                            is_static, kind, cu_index);
21108         }
21109     }
21110 }
21111
21112 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21113    exception if there is an error.  */
21114
21115 static void
21116 write_obstack (FILE *file, struct obstack *obstack)
21117 {
21118   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21119               file)
21120       != obstack_object_size (obstack))
21121     error (_("couldn't data write to file"));
21122 }
21123
21124 /* Unlink a file if the argument is not NULL.  */
21125
21126 static void
21127 unlink_if_set (void *p)
21128 {
21129   char **filename = p;
21130   if (*filename)
21131     unlink (*filename);
21132 }
21133
21134 /* A helper struct used when iterating over debug_types.  */
21135 struct signatured_type_index_data
21136 {
21137   struct objfile *objfile;
21138   struct mapped_symtab *symtab;
21139   struct obstack *types_list;
21140   htab_t psyms_seen;
21141   int cu_index;
21142 };
21143
21144 /* A helper function that writes a single signatured_type to an
21145    obstack.  */
21146
21147 static int
21148 write_one_signatured_type (void **slot, void *d)
21149 {
21150   struct signatured_type_index_data *info = d;
21151   struct signatured_type *entry = (struct signatured_type *) *slot;
21152   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
21153   gdb_byte val[8];
21154
21155   write_psymbols (info->symtab,
21156                   info->psyms_seen,
21157                   info->objfile->global_psymbols.list
21158                   + psymtab->globals_offset,
21159                   psymtab->n_global_syms, info->cu_index,
21160                   0);
21161   write_psymbols (info->symtab,
21162                   info->psyms_seen,
21163                   info->objfile->static_psymbols.list
21164                   + psymtab->statics_offset,
21165                   psymtab->n_static_syms, info->cu_index,
21166                   1);
21167
21168   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21169                           entry->per_cu.offset.sect_off);
21170   obstack_grow (info->types_list, val, 8);
21171   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21172                           entry->type_offset_in_tu.cu_off);
21173   obstack_grow (info->types_list, val, 8);
21174   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
21175   obstack_grow (info->types_list, val, 8);
21176
21177   ++info->cu_index;
21178
21179   return 1;
21180 }
21181
21182 /* Recurse into all "included" dependencies and write their symbols as
21183    if they appeared in this psymtab.  */
21184
21185 static void
21186 recursively_write_psymbols (struct objfile *objfile,
21187                             struct partial_symtab *psymtab,
21188                             struct mapped_symtab *symtab,
21189                             htab_t psyms_seen,
21190                             offset_type cu_index)
21191 {
21192   int i;
21193
21194   for (i = 0; i < psymtab->number_of_dependencies; ++i)
21195     if (psymtab->dependencies[i]->user != NULL)
21196       recursively_write_psymbols (objfile, psymtab->dependencies[i],
21197                                   symtab, psyms_seen, cu_index);
21198
21199   write_psymbols (symtab,
21200                   psyms_seen,
21201                   objfile->global_psymbols.list + psymtab->globals_offset,
21202                   psymtab->n_global_syms, cu_index,
21203                   0);
21204   write_psymbols (symtab,
21205                   psyms_seen,
21206                   objfile->static_psymbols.list + psymtab->statics_offset,
21207                   psymtab->n_static_syms, cu_index,
21208                   1);
21209 }
21210
21211 /* Create an index file for OBJFILE in the directory DIR.  */
21212
21213 static void
21214 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
21215 {
21216   struct cleanup *cleanup;
21217   char *filename, *cleanup_filename;
21218   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
21219   struct obstack cu_list, types_cu_list;
21220   int i;
21221   FILE *out_file;
21222   struct mapped_symtab *symtab;
21223   offset_type val, size_of_contents, total_len;
21224   struct stat st;
21225   htab_t psyms_seen;
21226   htab_t cu_index_htab;
21227   struct psymtab_cu_index_map *psymtab_cu_index_map;
21228
21229   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
21230     return;
21231
21232   if (dwarf2_per_objfile->using_index)
21233     error (_("Cannot use an index to create the index"));
21234
21235   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
21236     error (_("Cannot make an index when the file has multiple .debug_types sections"));
21237
21238   if (stat (objfile->name, &st) < 0)
21239     perror_with_name (objfile->name);
21240
21241   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
21242                      INDEX_SUFFIX, (char *) NULL);
21243   cleanup = make_cleanup (xfree, filename);
21244
21245   out_file = gdb_fopen_cloexec (filename, "wb");
21246   if (!out_file)
21247     error (_("Can't open `%s' for writing"), filename);
21248
21249   cleanup_filename = filename;
21250   make_cleanup (unlink_if_set, &cleanup_filename);
21251
21252   symtab = create_mapped_symtab ();
21253   make_cleanup (cleanup_mapped_symtab, symtab);
21254
21255   obstack_init (&addr_obstack);
21256   make_cleanup_obstack_free (&addr_obstack);
21257
21258   obstack_init (&cu_list);
21259   make_cleanup_obstack_free (&cu_list);
21260
21261   obstack_init (&types_cu_list);
21262   make_cleanup_obstack_free (&types_cu_list);
21263
21264   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
21265                                   NULL, xcalloc, xfree);
21266   make_cleanup_htab_delete (psyms_seen);
21267
21268   /* While we're scanning CU's create a table that maps a psymtab pointer
21269      (which is what addrmap records) to its index (which is what is recorded
21270      in the index file).  This will later be needed to write the address
21271      table.  */
21272   cu_index_htab = htab_create_alloc (100,
21273                                      hash_psymtab_cu_index,
21274                                      eq_psymtab_cu_index,
21275                                      NULL, xcalloc, xfree);
21276   make_cleanup_htab_delete (cu_index_htab);
21277   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
21278     xmalloc (sizeof (struct psymtab_cu_index_map)
21279              * dwarf2_per_objfile->n_comp_units);
21280   make_cleanup (xfree, psymtab_cu_index_map);
21281
21282   /* The CU list is already sorted, so we don't need to do additional
21283      work here.  Also, the debug_types entries do not appear in
21284      all_comp_units, but only in their own hash table.  */
21285   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
21286     {
21287       struct dwarf2_per_cu_data *per_cu
21288         = dwarf2_per_objfile->all_comp_units[i];
21289       struct partial_symtab *psymtab = per_cu->v.psymtab;
21290       gdb_byte val[8];
21291       struct psymtab_cu_index_map *map;
21292       void **slot;
21293
21294       /* CU of a shared file from 'dwz -m' may be unused by this main file.
21295          It may be referenced from a local scope but in such case it does not
21296          need to be present in .gdb_index.  */
21297       if (psymtab == NULL)
21298         continue;
21299
21300       if (psymtab->user == NULL)
21301         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
21302
21303       map = &psymtab_cu_index_map[i];
21304       map->psymtab = psymtab;
21305       map->cu_index = i;
21306       slot = htab_find_slot (cu_index_htab, map, INSERT);
21307       gdb_assert (slot != NULL);
21308       gdb_assert (*slot == NULL);
21309       *slot = map;
21310
21311       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
21312                               per_cu->offset.sect_off);
21313       obstack_grow (&cu_list, val, 8);
21314       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
21315       obstack_grow (&cu_list, val, 8);
21316     }
21317
21318   /* Dump the address map.  */
21319   write_address_map (objfile, &addr_obstack, cu_index_htab);
21320
21321   /* Write out the .debug_type entries, if any.  */
21322   if (dwarf2_per_objfile->signatured_types)
21323     {
21324       struct signatured_type_index_data sig_data;
21325
21326       sig_data.objfile = objfile;
21327       sig_data.symtab = symtab;
21328       sig_data.types_list = &types_cu_list;
21329       sig_data.psyms_seen = psyms_seen;
21330       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
21331       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
21332                               write_one_signatured_type, &sig_data);
21333     }
21334
21335   /* Now that we've processed all symbols we can shrink their cu_indices
21336      lists.  */
21337   uniquify_cu_indices (symtab);
21338
21339   obstack_init (&constant_pool);
21340   make_cleanup_obstack_free (&constant_pool);
21341   obstack_init (&symtab_obstack);
21342   make_cleanup_obstack_free (&symtab_obstack);
21343   write_hash_table (symtab, &symtab_obstack, &constant_pool);
21344
21345   obstack_init (&contents);
21346   make_cleanup_obstack_free (&contents);
21347   size_of_contents = 6 * sizeof (offset_type);
21348   total_len = size_of_contents;
21349
21350   /* The version number.  */
21351   val = MAYBE_SWAP (8);
21352   obstack_grow (&contents, &val, sizeof (val));
21353
21354   /* The offset of the CU list from the start of the file.  */
21355   val = MAYBE_SWAP (total_len);
21356   obstack_grow (&contents, &val, sizeof (val));
21357   total_len += obstack_object_size (&cu_list);
21358
21359   /* The offset of the types CU list from the start of the file.  */
21360   val = MAYBE_SWAP (total_len);
21361   obstack_grow (&contents, &val, sizeof (val));
21362   total_len += obstack_object_size (&types_cu_list);
21363
21364   /* The offset of the address table from the start of the file.  */
21365   val = MAYBE_SWAP (total_len);
21366   obstack_grow (&contents, &val, sizeof (val));
21367   total_len += obstack_object_size (&addr_obstack);
21368
21369   /* The offset of the symbol table from the start of the file.  */
21370   val = MAYBE_SWAP (total_len);
21371   obstack_grow (&contents, &val, sizeof (val));
21372   total_len += obstack_object_size (&symtab_obstack);
21373
21374   /* The offset of the constant pool from the start of the file.  */
21375   val = MAYBE_SWAP (total_len);
21376   obstack_grow (&contents, &val, sizeof (val));
21377   total_len += obstack_object_size (&constant_pool);
21378
21379   gdb_assert (obstack_object_size (&contents) == size_of_contents);
21380
21381   write_obstack (out_file, &contents);
21382   write_obstack (out_file, &cu_list);
21383   write_obstack (out_file, &types_cu_list);
21384   write_obstack (out_file, &addr_obstack);
21385   write_obstack (out_file, &symtab_obstack);
21386   write_obstack (out_file, &constant_pool);
21387
21388   fclose (out_file);
21389
21390   /* We want to keep the file, so we set cleanup_filename to NULL
21391      here.  See unlink_if_set.  */
21392   cleanup_filename = NULL;
21393
21394   do_cleanups (cleanup);
21395 }
21396
21397 /* Implementation of the `save gdb-index' command.
21398    
21399    Note that the file format used by this command is documented in the
21400    GDB manual.  Any changes here must be documented there.  */
21401
21402 static void
21403 save_gdb_index_command (char *arg, int from_tty)
21404 {
21405   struct objfile *objfile;
21406
21407   if (!arg || !*arg)
21408     error (_("usage: save gdb-index DIRECTORY"));
21409
21410   ALL_OBJFILES (objfile)
21411   {
21412     struct stat st;
21413
21414     /* If the objfile does not correspond to an actual file, skip it.  */
21415     if (stat (objfile->name, &st) < 0)
21416       continue;
21417
21418     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21419     if (dwarf2_per_objfile)
21420       {
21421         volatile struct gdb_exception except;
21422
21423         TRY_CATCH (except, RETURN_MASK_ERROR)
21424           {
21425             write_psymtabs_to_index (objfile, arg);
21426           }
21427         if (except.reason < 0)
21428           exception_fprintf (gdb_stderr, except,
21429                              _("Error while writing index for `%s': "),
21430                              objfile->name);
21431       }
21432   }
21433 }
21434
21435 \f
21436
21437 int dwarf2_always_disassemble;
21438
21439 static void
21440 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
21441                                 struct cmd_list_element *c, const char *value)
21442 {
21443   fprintf_filtered (file,
21444                     _("Whether to always disassemble "
21445                       "DWARF expressions is %s.\n"),
21446                     value);
21447 }
21448
21449 static void
21450 show_check_physname (struct ui_file *file, int from_tty,
21451                      struct cmd_list_element *c, const char *value)
21452 {
21453   fprintf_filtered (file,
21454                     _("Whether to check \"physname\" is %s.\n"),
21455                     value);
21456 }
21457
21458 void _initialize_dwarf2_read (void);
21459
21460 void
21461 _initialize_dwarf2_read (void)
21462 {
21463   struct cmd_list_element *c;
21464
21465   dwarf2_objfile_data_key
21466     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
21467
21468   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
21469 Set DWARF 2 specific variables.\n\
21470 Configure DWARF 2 variables such as the cache size"),
21471                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
21472                   0/*allow-unknown*/, &maintenance_set_cmdlist);
21473
21474   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
21475 Show DWARF 2 specific variables\n\
21476 Show DWARF 2 variables such as the cache size"),
21477                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
21478                   0/*allow-unknown*/, &maintenance_show_cmdlist);
21479
21480   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
21481                             &dwarf2_max_cache_age, _("\
21482 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
21483 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
21484 A higher limit means that cached compilation units will be stored\n\
21485 in memory longer, and more total memory will be used.  Zero disables\n\
21486 caching, which can slow down startup."),
21487                             NULL,
21488                             show_dwarf2_max_cache_age,
21489                             &set_dwarf2_cmdlist,
21490                             &show_dwarf2_cmdlist);
21491
21492   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
21493                            &dwarf2_always_disassemble, _("\
21494 Set whether `info address' always disassembles DWARF expressions."), _("\
21495 Show whether `info address' always disassembles DWARF expressions."), _("\
21496 When enabled, DWARF expressions are always printed in an assembly-like\n\
21497 syntax.  When disabled, expressions will be printed in a more\n\
21498 conversational style, when possible."),
21499                            NULL,
21500                            show_dwarf2_always_disassemble,
21501                            &set_dwarf2_cmdlist,
21502                            &show_dwarf2_cmdlist);
21503
21504   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
21505 Set debugging of the dwarf2 reader."), _("\
21506 Show debugging of the dwarf2 reader."), _("\
21507 When enabled, debugging messages are printed during dwarf2 reading\n\
21508 and symtab expansion."),
21509                             NULL,
21510                             NULL,
21511                             &setdebuglist, &showdebuglist);
21512
21513   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
21514 Set debugging of the dwarf2 DIE reader."), _("\
21515 Show debugging of the dwarf2 DIE reader."), _("\
21516 When enabled (non-zero), DIEs are dumped after they are read in.\n\
21517 The value is the maximum depth to print."),
21518                              NULL,
21519                              NULL,
21520                              &setdebuglist, &showdebuglist);
21521
21522   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
21523 Set cross-checking of \"physname\" code against demangler."), _("\
21524 Show cross-checking of \"physname\" code against demangler."), _("\
21525 When enabled, GDB's internal \"physname\" code is checked against\n\
21526 the demangler."),
21527                            NULL, show_check_physname,
21528                            &setdebuglist, &showdebuglist);
21529
21530   add_setshow_boolean_cmd ("use-deprecated-index-sections",
21531                            no_class, &use_deprecated_index_sections, _("\
21532 Set whether to use deprecated gdb_index sections."), _("\
21533 Show whether to use deprecated gdb_index sections."), _("\
21534 When enabled, deprecated .gdb_index sections are used anyway.\n\
21535 Normally they are ignored either because of a missing feature or\n\
21536 performance issue.\n\
21537 Warning: This option must be enabled before gdb reads the file."),
21538                            NULL,
21539                            NULL,
21540                            &setlist, &showlist);
21541
21542   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
21543                _("\
21544 Save a gdb-index file.\n\
21545 Usage: save gdb-index DIRECTORY"),
21546                &save_cmdlist);
21547   set_cmd_completer (c, filename_completer);
21548
21549   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
21550                                                         &dwarf2_locexpr_funcs);
21551   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
21552                                                         &dwarf2_loclist_funcs);
21553
21554   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
21555                                         &dwarf2_block_frame_base_locexpr_funcs);
21556   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
21557                                         &dwarf2_block_frame_base_loclist_funcs);
21558 }