PR c++/11990:
[external/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
72 #include <fcntl.h>
73 #include "gdb_string.h"
74 #include "gdb_assert.h"
75 #include <sys/types.h>
76
77 typedef struct symbol *symbolp;
78 DEF_VEC_P (symbolp);
79
80 /* When non-zero, print basic high level tracing messages.
81    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
82 static int dwarf2_read_debug = 0;
83
84 /* When non-zero, dump DIEs after they are read in.  */
85 static unsigned int dwarf2_die_debug = 0;
86
87 /* When non-zero, cross-check physname against demangler.  */
88 static int check_physname = 0;
89
90 /* When non-zero, do not reject deprecated .gdb_index sections.  */
91 static int use_deprecated_index_sections = 0;
92
93 static const struct objfile_data *dwarf2_objfile_data_key;
94
95 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
96
97 static int dwarf2_locexpr_index;
98 static int dwarf2_loclist_index;
99 static int dwarf2_locexpr_block_index;
100 static int dwarf2_loclist_block_index;
101
102 struct dwarf2_section_info
103 {
104   asection *asection;
105   const gdb_byte *buffer;
106   bfd_size_type size;
107   /* True if we have tried to read this section.  */
108   int readin;
109 };
110
111 typedef struct dwarf2_section_info dwarf2_section_info_def;
112 DEF_VEC_O (dwarf2_section_info_def);
113
114 /* All offsets in the index are of this type.  It must be
115    architecture-independent.  */
116 typedef uint32_t offset_type;
117
118 DEF_VEC_I (offset_type);
119
120 /* Ensure only legit values are used.  */
121 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
122   do { \
123     gdb_assert ((unsigned int) (value) <= 1); \
124     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
125   } while (0)
126
127 /* Ensure only legit values are used.  */
128 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
129   do { \
130     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
131                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
132     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
133   } while (0)
134
135 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
136 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
137   do { \
138     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
139     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
140   } while (0)
141
142 /* A description of the mapped index.  The file format is described in
143    a comment by the code that writes the index.  */
144 struct mapped_index
145 {
146   /* Index data format version.  */
147   int version;
148
149   /* The total length of the buffer.  */
150   off_t total_size;
151
152   /* A pointer to the address table data.  */
153   const gdb_byte *address_table;
154
155   /* Size of the address table data in bytes.  */
156   offset_type address_table_size;
157
158   /* The symbol table, implemented as a hash table.  */
159   const offset_type *symbol_table;
160
161   /* Size in slots, each slot is 2 offset_types.  */
162   offset_type symbol_table_slots;
163
164   /* A pointer to the constant pool.  */
165   const char *constant_pool;
166 };
167
168 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
169 DEF_VEC_P (dwarf2_per_cu_ptr);
170
171 /* Collection of data recorded per objfile.
172    This hangs off of dwarf2_objfile_data_key.  */
173
174 struct dwarf2_per_objfile
175 {
176   struct dwarf2_section_info info;
177   struct dwarf2_section_info abbrev;
178   struct dwarf2_section_info line;
179   struct dwarf2_section_info loc;
180   struct dwarf2_section_info macinfo;
181   struct dwarf2_section_info macro;
182   struct dwarf2_section_info str;
183   struct dwarf2_section_info ranges;
184   struct dwarf2_section_info addr;
185   struct dwarf2_section_info frame;
186   struct dwarf2_section_info eh_frame;
187   struct dwarf2_section_info gdb_index;
188
189   VEC (dwarf2_section_info_def) *types;
190
191   /* Back link.  */
192   struct objfile *objfile;
193
194   /* Table of all the compilation units.  This is used to locate
195      the target compilation unit of a particular reference.  */
196   struct dwarf2_per_cu_data **all_comp_units;
197
198   /* The number of compilation units in ALL_COMP_UNITS.  */
199   int n_comp_units;
200
201   /* The number of .debug_types-related CUs.  */
202   int n_type_units;
203
204   /* The .debug_types-related CUs (TUs).  */
205   struct signatured_type **all_type_units;
206
207   /* The number of entries in all_type_unit_groups.  */
208   int n_type_unit_groups;
209
210   /* Table of type unit groups.
211      This exists to make it easy to iterate over all CUs and TU groups.  */
212   struct type_unit_group **all_type_unit_groups;
213
214   /* Table of struct type_unit_group objects.
215      The hash key is the DW_AT_stmt_list value.  */
216   htab_t type_unit_groups;
217
218   /* A table mapping .debug_types signatures to its signatured_type entry.
219      This is NULL if the .debug_types section hasn't been read in yet.  */
220   htab_t signatured_types;
221
222   /* Type unit statistics, to see how well the scaling improvements
223      are doing.  */
224   struct tu_stats
225   {
226     int nr_uniq_abbrev_tables;
227     int nr_symtabs;
228     int nr_symtab_sharers;
229     int nr_stmt_less_type_units;
230   } tu_stats;
231
232   /* A chain of compilation units that are currently read in, so that
233      they can be freed later.  */
234   struct dwarf2_per_cu_data *read_in_chain;
235
236   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
237      This is NULL if the table hasn't been allocated yet.  */
238   htab_t dwo_files;
239
240   /* Non-zero if we've check for whether there is a DWP file.  */
241   int dwp_checked;
242
243   /* The DWP file if there is one, or NULL.  */
244   struct dwp_file *dwp_file;
245
246   /* The shared '.dwz' file, if one exists.  This is used when the
247      original data was compressed using 'dwz -m'.  */
248   struct dwz_file *dwz_file;
249
250   /* A flag indicating wether this objfile has a section loaded at a
251      VMA of 0.  */
252   int has_section_at_zero;
253
254   /* True if we are using the mapped index,
255      or we are faking it for OBJF_READNOW's sake.  */
256   unsigned char using_index;
257
258   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
259   struct mapped_index *index_table;
260
261   /* When using index_table, this keeps track of all quick_file_names entries.
262      TUs typically share line table entries with a CU, so we maintain a
263      separate table of all line table entries to support the sharing.
264      Note that while there can be way more TUs than CUs, we've already
265      sorted all the TUs into "type unit groups", grouped by their
266      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
267      CU and its associated TU group if there is one.  */
268   htab_t quick_file_names_table;
269
270   /* Set during partial symbol reading, to prevent queueing of full
271      symbols.  */
272   int reading_partial_symbols;
273
274   /* Table mapping type DIEs to their struct type *.
275      This is NULL if not allocated yet.
276      The mapping is done via (CU/TU + DIE offset) -> type.  */
277   htab_t die_type_hash;
278
279   /* The CUs we recently read.  */
280   VEC (dwarf2_per_cu_ptr) *just_read_cus;
281 };
282
283 static struct dwarf2_per_objfile *dwarf2_per_objfile;
284
285 /* Default names of the debugging sections.  */
286
287 /* Note that if the debugging section has been compressed, it might
288    have a name like .zdebug_info.  */
289
290 static const struct dwarf2_debug_sections dwarf2_elf_names =
291 {
292   { ".debug_info", ".zdebug_info" },
293   { ".debug_abbrev", ".zdebug_abbrev" },
294   { ".debug_line", ".zdebug_line" },
295   { ".debug_loc", ".zdebug_loc" },
296   { ".debug_macinfo", ".zdebug_macinfo" },
297   { ".debug_macro", ".zdebug_macro" },
298   { ".debug_str", ".zdebug_str" },
299   { ".debug_ranges", ".zdebug_ranges" },
300   { ".debug_types", ".zdebug_types" },
301   { ".debug_addr", ".zdebug_addr" },
302   { ".debug_frame", ".zdebug_frame" },
303   { ".eh_frame", NULL },
304   { ".gdb_index", ".zgdb_index" },
305   23
306 };
307
308 /* List of DWO/DWP sections.  */
309
310 static const struct dwop_section_names
311 {
312   struct dwarf2_section_names abbrev_dwo;
313   struct dwarf2_section_names info_dwo;
314   struct dwarf2_section_names line_dwo;
315   struct dwarf2_section_names loc_dwo;
316   struct dwarf2_section_names macinfo_dwo;
317   struct dwarf2_section_names macro_dwo;
318   struct dwarf2_section_names str_dwo;
319   struct dwarf2_section_names str_offsets_dwo;
320   struct dwarf2_section_names types_dwo;
321   struct dwarf2_section_names cu_index;
322   struct dwarf2_section_names tu_index;
323 }
324 dwop_section_names =
325 {
326   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
327   { ".debug_info.dwo", ".zdebug_info.dwo" },
328   { ".debug_line.dwo", ".zdebug_line.dwo" },
329   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
330   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
331   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
332   { ".debug_str.dwo", ".zdebug_str.dwo" },
333   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
334   { ".debug_types.dwo", ".zdebug_types.dwo" },
335   { ".debug_cu_index", ".zdebug_cu_index" },
336   { ".debug_tu_index", ".zdebug_tu_index" },
337 };
338
339 /* local data types */
340
341 /* The data in a compilation unit header, after target2host
342    translation, looks like this.  */
343 struct comp_unit_head
344 {
345   unsigned int length;
346   short version;
347   unsigned char addr_size;
348   unsigned char signed_addr_p;
349   sect_offset abbrev_offset;
350
351   /* Size of file offsets; either 4 or 8.  */
352   unsigned int offset_size;
353
354   /* Size of the length field; either 4 or 12.  */
355   unsigned int initial_length_size;
356
357   /* Offset to the first byte of this compilation unit header in the
358      .debug_info section, for resolving relative reference dies.  */
359   sect_offset offset;
360
361   /* Offset to first die in this cu from the start of the cu.
362      This will be the first byte following the compilation unit header.  */
363   cu_offset first_die_offset;
364 };
365
366 /* Type used for delaying computation of method physnames.
367    See comments for compute_delayed_physnames.  */
368 struct delayed_method_info
369 {
370   /* The type to which the method is attached, i.e., its parent class.  */
371   struct type *type;
372
373   /* The index of the method in the type's function fieldlists.  */
374   int fnfield_index;
375
376   /* The index of the method in the fieldlist.  */
377   int index;
378
379   /* The name of the DIE.  */
380   const char *name;
381
382   /*  The DIE associated with this method.  */
383   struct die_info *die;
384 };
385
386 typedef struct delayed_method_info delayed_method_info;
387 DEF_VEC_O (delayed_method_info);
388
389 /* Internal state when decoding a particular compilation unit.  */
390 struct dwarf2_cu
391 {
392   /* The objfile containing this compilation unit.  */
393   struct objfile *objfile;
394
395   /* The header of the compilation unit.  */
396   struct comp_unit_head header;
397
398   /* Base address of this compilation unit.  */
399   CORE_ADDR base_address;
400
401   /* Non-zero if base_address has been set.  */
402   int base_known;
403
404   /* The language we are debugging.  */
405   enum language language;
406   const struct language_defn *language_defn;
407
408   const char *producer;
409
410   /* The generic symbol table building routines have separate lists for
411      file scope symbols and all all other scopes (local scopes).  So
412      we need to select the right one to pass to add_symbol_to_list().
413      We do it by keeping a pointer to the correct list in list_in_scope.
414
415      FIXME: The original dwarf code just treated the file scope as the
416      first local scope, and all other local scopes as nested local
417      scopes, and worked fine.  Check to see if we really need to
418      distinguish these in buildsym.c.  */
419   struct pending **list_in_scope;
420
421   /* The abbrev table for this CU.
422      Normally this points to the abbrev table in the objfile.
423      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
424   struct abbrev_table *abbrev_table;
425
426   /* Hash table holding all the loaded partial DIEs
427      with partial_die->offset.SECT_OFF as hash.  */
428   htab_t partial_dies;
429
430   /* Storage for things with the same lifetime as this read-in compilation
431      unit, including partial DIEs.  */
432   struct obstack comp_unit_obstack;
433
434   /* When multiple dwarf2_cu structures are living in memory, this field
435      chains them all together, so that they can be released efficiently.
436      We will probably also want a generation counter so that most-recently-used
437      compilation units are cached...  */
438   struct dwarf2_per_cu_data *read_in_chain;
439
440   /* Backchain to our per_cu entry if the tree has been built.  */
441   struct dwarf2_per_cu_data *per_cu;
442
443   /* How many compilation units ago was this CU last referenced?  */
444   int last_used;
445
446   /* A hash table of DIE cu_offset for following references with
447      die_info->offset.sect_off as hash.  */
448   htab_t die_hash;
449
450   /* Full DIEs if read in.  */
451   struct die_info *dies;
452
453   /* A set of pointers to dwarf2_per_cu_data objects for compilation
454      units referenced by this one.  Only set during full symbol processing;
455      partial symbol tables do not have dependencies.  */
456   htab_t dependencies;
457
458   /* Header data from the line table, during full symbol processing.  */
459   struct line_header *line_header;
460
461   /* A list of methods which need to have physnames computed
462      after all type information has been read.  */
463   VEC (delayed_method_info) *method_list;
464
465   /* To be copied to symtab->call_site_htab.  */
466   htab_t call_site_htab;
467
468   /* Non-NULL if this CU came from a DWO file.
469      There is an invariant here that is important to remember:
470      Except for attributes copied from the top level DIE in the "main"
471      (or "stub") file in preparation for reading the DWO file
472      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
473      Either there isn't a DWO file (in which case this is NULL and the point
474      is moot), or there is and either we're not going to read it (in which
475      case this is NULL) or there is and we are reading it (in which case this
476      is non-NULL).  */
477   struct dwo_unit *dwo_unit;
478
479   /* The DW_AT_addr_base attribute if present, zero otherwise
480      (zero is a valid value though).
481      Note this value comes from the stub CU/TU's DIE.  */
482   ULONGEST addr_base;
483
484   /* The DW_AT_ranges_base attribute if present, zero otherwise
485      (zero is a valid value though).
486      Note this value comes from the stub CU/TU's DIE.
487      Also note that the value is zero in the non-DWO case so this value can
488      be used without needing to know whether DWO files are in use or not.
489      N.B. This does not apply to DW_AT_ranges appearing in
490      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
491      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
492      DW_AT_ranges_base *would* have to be applied, and we'd have to care
493      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
494   ULONGEST ranges_base;
495
496   /* Mark used when releasing cached dies.  */
497   unsigned int mark : 1;
498
499   /* This CU references .debug_loc.  See the symtab->locations_valid field.
500      This test is imperfect as there may exist optimized debug code not using
501      any location list and still facing inlining issues if handled as
502      unoptimized code.  For a future better test see GCC PR other/32998.  */
503   unsigned int has_loclist : 1;
504
505   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
506      if all the producer_is_* fields are valid.  This information is cached
507      because profiling CU expansion showed excessive time spent in
508      producer_is_gxx_lt_4_6.  */
509   unsigned int checked_producer : 1;
510   unsigned int producer_is_gxx_lt_4_6 : 1;
511   unsigned int producer_is_gcc_lt_4_3 : 1;
512   unsigned int producer_is_icc : 1;
513
514   /* When set, the file that we're processing is known to have
515      debugging info for C++ namespaces.  GCC 3.3.x did not produce
516      this information, but later versions do.  */
517
518   unsigned int processing_has_namespace_info : 1;
519 };
520
521 /* Persistent data held for a compilation unit, even when not
522    processing it.  We put a pointer to this structure in the
523    read_symtab_private field of the psymtab.  */
524
525 struct dwarf2_per_cu_data
526 {
527   /* The start offset and length of this compilation unit.
528      NOTE: Unlike comp_unit_head.length, this length includes
529      initial_length_size.
530      If the DIE refers to a DWO file, this is always of the original die,
531      not the DWO file.  */
532   sect_offset offset;
533   unsigned int length;
534
535   /* Flag indicating this compilation unit will be read in before
536      any of the current compilation units are processed.  */
537   unsigned int queued : 1;
538
539   /* This flag will be set when reading partial DIEs if we need to load
540      absolutely all DIEs for this compilation unit, instead of just the ones
541      we think are interesting.  It gets set if we look for a DIE in the
542      hash table and don't find it.  */
543   unsigned int load_all_dies : 1;
544
545   /* Non-zero if this CU is from .debug_types.
546      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
547      this is non-zero.  */
548   unsigned int is_debug_types : 1;
549
550   /* Non-zero if this CU is from the .dwz file.  */
551   unsigned int is_dwz : 1;
552
553   /* The section this CU/TU lives in.
554      If the DIE refers to a DWO file, this is always the original die,
555      not the DWO file.  */
556   struct dwarf2_section_info *section;
557
558   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
559      of the CU cache it gets reset to NULL again.  */
560   struct dwarf2_cu *cu;
561
562   /* The corresponding objfile.
563      Normally we can get the objfile from dwarf2_per_objfile.
564      However we can enter this file with just a "per_cu" handle.  */
565   struct objfile *objfile;
566
567   /* When using partial symbol tables, the 'psymtab' field is active.
568      Otherwise the 'quick' field is active.  */
569   union
570   {
571     /* The partial symbol table associated with this compilation unit,
572        or NULL for unread partial units.  */
573     struct partial_symtab *psymtab;
574
575     /* Data needed by the "quick" functions.  */
576     struct dwarf2_per_cu_quick_data *quick;
577   } v;
578
579   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
580      while reading psymtabs, used to compute the psymtab dependencies,
581      and then cleared.  Then it is filled in again while reading full
582      symbols, and only deleted when the objfile is destroyed.
583
584      This is also used to work around a difference between the way gold
585      generates .gdb_index version <=7 and the way gdb does.  Arguably this
586      is a gold bug.  For symbols coming from TUs, gold records in the index
587      the CU that includes the TU instead of the TU itself.  This breaks
588      dw2_lookup_symbol: It assumes that if the index says symbol X lives
589      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
590      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
591      we need to look in TU Z to find X.  Fortunately, this is akin to
592      DW_TAG_imported_unit, so we just use the same mechanism: For
593      .gdb_index version <=7 this also records the TUs that the CU referred
594      to.  Concurrently with this change gdb was modified to emit version 8
595      indices so we only pay a price for gold generated indices.  */
596   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
597 };
598
599 /* Entry in the signatured_types hash table.  */
600
601 struct signatured_type
602 {
603   /* The "per_cu" object of this type.
604      N.B.: This is the first member so that it's easy to convert pointers
605      between them.  */
606   struct dwarf2_per_cu_data per_cu;
607
608   /* The type's signature.  */
609   ULONGEST signature;
610
611   /* Offset in the TU of the type's DIE, as read from the TU header.
612      If this TU is a DWO stub and the definition lives in a DWO file
613      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
614   cu_offset type_offset_in_tu;
615
616   /* Offset in the section of the type's DIE.
617      If the definition lives in a DWO file, this is the offset in the
618      .debug_types.dwo section.
619      The value is zero until the actual value is known.
620      Zero is otherwise not a valid section offset.  */
621   sect_offset type_offset_in_section;
622
623   /* Type units are grouped by their DW_AT_stmt_list entry so that they
624      can share them.  This points to the containing symtab.  */
625   struct type_unit_group *type_unit_group;
626 };
627
628 typedef struct signatured_type *sig_type_ptr;
629 DEF_VEC_P (sig_type_ptr);
630
631 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
632    This includes type_unit_group and quick_file_names.  */
633
634 struct stmt_list_hash
635 {
636   /* The DWO unit this table is from or NULL if there is none.  */
637   struct dwo_unit *dwo_unit;
638
639   /* Offset in .debug_line or .debug_line.dwo.  */
640   sect_offset line_offset;
641 };
642
643 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
644    an object of this type.  */
645
646 struct type_unit_group
647 {
648   /* dwarf2read.c's main "handle" on a TU symtab.
649      To simplify things we create an artificial CU that "includes" all the
650      type units using this stmt_list so that the rest of the code still has
651      a "per_cu" handle on the symtab.
652      This PER_CU is recognized by having no section.  */
653 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
654   struct dwarf2_per_cu_data per_cu;
655
656   /* The TUs that share this DW_AT_stmt_list entry.
657      This is added to while parsing type units to build partial symtabs,
658      and is deleted afterwards and not used again.  */
659   VEC (sig_type_ptr) *tus;
660
661   /* The primary symtab.
662      Type units in a group needn't all be defined in the same source file,
663      so we create an essentially anonymous symtab as the primary symtab.  */
664   struct symtab *primary_symtab;
665
666   /* The data used to construct the hash key.  */
667   struct stmt_list_hash hash;
668
669   /* The number of symtabs from the line header.
670      The value here must match line_header.num_file_names.  */
671   unsigned int num_symtabs;
672
673   /* The symbol tables for this TU (obtained from the files listed in
674      DW_AT_stmt_list).
675      WARNING: The order of entries here must match the order of entries
676      in the line header.  After the first TU using this type_unit_group, the
677      line header for the subsequent TUs is recreated from this.  This is done
678      because we need to use the same symtabs for each TU using the same
679      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
680      there's no guarantee the line header doesn't have duplicate entries.  */
681   struct symtab **symtabs;
682 };
683
684 /* These sections are what may appear in a DWO file.  */
685
686 struct dwo_sections
687 {
688   struct dwarf2_section_info abbrev;
689   struct dwarf2_section_info line;
690   struct dwarf2_section_info loc;
691   struct dwarf2_section_info macinfo;
692   struct dwarf2_section_info macro;
693   struct dwarf2_section_info str;
694   struct dwarf2_section_info str_offsets;
695   /* In the case of a virtual DWO file, these two are unused.  */
696   struct dwarf2_section_info info;
697   VEC (dwarf2_section_info_def) *types;
698 };
699
700 /* CUs/TUs in DWP/DWO files.  */
701
702 struct dwo_unit
703 {
704   /* Backlink to the containing struct dwo_file.  */
705   struct dwo_file *dwo_file;
706
707   /* The "id" that distinguishes this CU/TU.
708      .debug_info calls this "dwo_id", .debug_types calls this "signature".
709      Since signatures came first, we stick with it for consistency.  */
710   ULONGEST signature;
711
712   /* The section this CU/TU lives in, in the DWO file.  */
713   struct dwarf2_section_info *section;
714
715   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
716   sect_offset offset;
717   unsigned int length;
718
719   /* For types, offset in the type's DIE of the type defined by this TU.  */
720   cu_offset type_offset_in_tu;
721 };
722
723 /* Data for one DWO file.
724    This includes virtual DWO files that have been packaged into a
725    DWP file.  */
726
727 struct dwo_file
728 {
729   /* The DW_AT_GNU_dwo_name attribute.
730      For virtual DWO files the name is constructed from the section offsets
731      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
732      from related CU+TUs.  */
733   const char *dwo_name;
734
735   /* The DW_AT_comp_dir attribute.  */
736   const char *comp_dir;
737
738   /* The bfd, when the file is open.  Otherwise this is NULL.
739      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
740   bfd *dbfd;
741
742   /* Section info for this file.  */
743   struct dwo_sections sections;
744
745   /* Table of CUs in the file.
746      Each element is a struct dwo_unit.  */
747   htab_t cus;
748
749   /* Table of TUs in the file.
750      Each element is a struct dwo_unit.  */
751   htab_t tus;
752 };
753
754 /* These sections are what may appear in a DWP file.  */
755
756 struct dwp_sections
757 {
758   struct dwarf2_section_info str;
759   struct dwarf2_section_info cu_index;
760   struct dwarf2_section_info tu_index;
761   /* The .debug_info.dwo, .debug_types.dwo, and other sections are referenced
762      by section number.  We don't need to record them here.  */
763 };
764
765 /* These sections are what may appear in a virtual DWO file.  */
766
767 struct virtual_dwo_sections
768 {
769   struct dwarf2_section_info abbrev;
770   struct dwarf2_section_info line;
771   struct dwarf2_section_info loc;
772   struct dwarf2_section_info macinfo;
773   struct dwarf2_section_info macro;
774   struct dwarf2_section_info str_offsets;
775   /* Each DWP hash table entry records one CU or one TU.
776      That is recorded here, and copied to dwo_unit.section.  */
777   struct dwarf2_section_info info_or_types;
778 };
779
780 /* Contents of DWP hash tables.  */
781
782 struct dwp_hash_table
783 {
784   uint32_t nr_units, nr_slots;
785   const gdb_byte *hash_table, *unit_table, *section_pool;
786 };
787
788 /* Data for one DWP file.  */
789
790 struct dwp_file
791 {
792   /* Name of the file.  */
793   const char *name;
794
795   /* The bfd, when the file is open.  Otherwise this is NULL.  */
796   bfd *dbfd;
797
798   /* Section info for this file.  */
799   struct dwp_sections sections;
800
801   /* Table of CUs in the file. */
802   const struct dwp_hash_table *cus;
803
804   /* Table of TUs in the file.  */
805   const struct dwp_hash_table *tus;
806
807   /* Table of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
808   htab_t loaded_cutus;
809
810   /* Table to map ELF section numbers to their sections.  */
811   unsigned int num_sections;
812   asection **elf_sections;
813 };
814
815 /* This represents a '.dwz' file.  */
816
817 struct dwz_file
818 {
819   /* A dwz file can only contain a few sections.  */
820   struct dwarf2_section_info abbrev;
821   struct dwarf2_section_info info;
822   struct dwarf2_section_info str;
823   struct dwarf2_section_info line;
824   struct dwarf2_section_info macro;
825   struct dwarf2_section_info gdb_index;
826
827   /* The dwz's BFD.  */
828   bfd *dwz_bfd;
829 };
830
831 /* Struct used to pass misc. parameters to read_die_and_children, et
832    al.  which are used for both .debug_info and .debug_types dies.
833    All parameters here are unchanging for the life of the call.  This
834    struct exists to abstract away the constant parameters of die reading.  */
835
836 struct die_reader_specs
837 {
838   /* die_section->asection->owner.  */
839   bfd* abfd;
840
841   /* The CU of the DIE we are parsing.  */
842   struct dwarf2_cu *cu;
843
844   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
845   struct dwo_file *dwo_file;
846
847   /* The section the die comes from.
848      This is either .debug_info or .debug_types, or the .dwo variants.  */
849   struct dwarf2_section_info *die_section;
850
851   /* die_section->buffer.  */
852   const gdb_byte *buffer;
853
854   /* The end of the buffer.  */
855   const gdb_byte *buffer_end;
856 };
857
858 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
859 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
860                                       const gdb_byte *info_ptr,
861                                       struct die_info *comp_unit_die,
862                                       int has_children,
863                                       void *data);
864
865 /* The line number information for a compilation unit (found in the
866    .debug_line section) begins with a "statement program header",
867    which contains the following information.  */
868 struct line_header
869 {
870   unsigned int total_length;
871   unsigned short version;
872   unsigned int header_length;
873   unsigned char minimum_instruction_length;
874   unsigned char maximum_ops_per_instruction;
875   unsigned char default_is_stmt;
876   int line_base;
877   unsigned char line_range;
878   unsigned char opcode_base;
879
880   /* standard_opcode_lengths[i] is the number of operands for the
881      standard opcode whose value is i.  This means that
882      standard_opcode_lengths[0] is unused, and the last meaningful
883      element is standard_opcode_lengths[opcode_base - 1].  */
884   unsigned char *standard_opcode_lengths;
885
886   /* The include_directories table.  NOTE!  These strings are not
887      allocated with xmalloc; instead, they are pointers into
888      debug_line_buffer.  If you try to free them, `free' will get
889      indigestion.  */
890   unsigned int num_include_dirs, include_dirs_size;
891   const char **include_dirs;
892
893   /* The file_names table.  NOTE!  These strings are not allocated
894      with xmalloc; instead, they are pointers into debug_line_buffer.
895      Don't try to free them directly.  */
896   unsigned int num_file_names, file_names_size;
897   struct file_entry
898   {
899     const char *name;
900     unsigned int dir_index;
901     unsigned int mod_time;
902     unsigned int length;
903     int included_p; /* Non-zero if referenced by the Line Number Program.  */
904     struct symtab *symtab; /* The associated symbol table, if any.  */
905   } *file_names;
906
907   /* The start and end of the statement program following this
908      header.  These point into dwarf2_per_objfile->line_buffer.  */
909   const gdb_byte *statement_program_start, *statement_program_end;
910 };
911
912 /* When we construct a partial symbol table entry we only
913    need this much information.  */
914 struct partial_die_info
915   {
916     /* Offset of this DIE.  */
917     sect_offset offset;
918
919     /* DWARF-2 tag for this DIE.  */
920     ENUM_BITFIELD(dwarf_tag) tag : 16;
921
922     /* Assorted flags describing the data found in this DIE.  */
923     unsigned int has_children : 1;
924     unsigned int is_external : 1;
925     unsigned int is_declaration : 1;
926     unsigned int has_type : 1;
927     unsigned int has_specification : 1;
928     unsigned int has_pc_info : 1;
929     unsigned int may_be_inlined : 1;
930
931     /* Flag set if the SCOPE field of this structure has been
932        computed.  */
933     unsigned int scope_set : 1;
934
935     /* Flag set if the DIE has a byte_size attribute.  */
936     unsigned int has_byte_size : 1;
937
938     /* Flag set if any of the DIE's children are template arguments.  */
939     unsigned int has_template_arguments : 1;
940
941     /* Flag set if fixup_partial_die has been called on this die.  */
942     unsigned int fixup_called : 1;
943
944     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
945     unsigned int is_dwz : 1;
946
947     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
948     unsigned int spec_is_dwz : 1;
949
950     /* The name of this DIE.  Normally the value of DW_AT_name, but
951        sometimes a default name for unnamed DIEs.  */
952     const char *name;
953
954     /* The linkage name, if present.  */
955     const char *linkage_name;
956
957     /* The scope to prepend to our children.  This is generally
958        allocated on the comp_unit_obstack, so will disappear
959        when this compilation unit leaves the cache.  */
960     const char *scope;
961
962     /* Some data associated with the partial DIE.  The tag determines
963        which field is live.  */
964     union
965     {
966       /* The location description associated with this DIE, if any.  */
967       struct dwarf_block *locdesc;
968       /* The offset of an import, for DW_TAG_imported_unit.  */
969       sect_offset offset;
970     } d;
971
972     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
973     CORE_ADDR lowpc;
974     CORE_ADDR highpc;
975
976     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
977        DW_AT_sibling, if any.  */
978     /* NOTE: This member isn't strictly necessary, read_partial_die could
979        return DW_AT_sibling values to its caller load_partial_dies.  */
980     const gdb_byte *sibling;
981
982     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
983        DW_AT_specification (or DW_AT_abstract_origin or
984        DW_AT_extension).  */
985     sect_offset spec_offset;
986
987     /* Pointers to this DIE's parent, first child, and next sibling,
988        if any.  */
989     struct partial_die_info *die_parent, *die_child, *die_sibling;
990   };
991
992 /* This data structure holds the information of an abbrev.  */
993 struct abbrev_info
994   {
995     unsigned int number;        /* number identifying abbrev */
996     enum dwarf_tag tag;         /* dwarf tag */
997     unsigned short has_children;                /* boolean */
998     unsigned short num_attrs;   /* number of attributes */
999     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1000     struct abbrev_info *next;   /* next in chain */
1001   };
1002
1003 struct attr_abbrev
1004   {
1005     ENUM_BITFIELD(dwarf_attribute) name : 16;
1006     ENUM_BITFIELD(dwarf_form) form : 16;
1007   };
1008
1009 /* Size of abbrev_table.abbrev_hash_table.  */
1010 #define ABBREV_HASH_SIZE 121
1011
1012 /* Top level data structure to contain an abbreviation table.  */
1013
1014 struct abbrev_table
1015 {
1016   /* Where the abbrev table came from.
1017      This is used as a sanity check when the table is used.  */
1018   sect_offset offset;
1019
1020   /* Storage for the abbrev table.  */
1021   struct obstack abbrev_obstack;
1022
1023   /* Hash table of abbrevs.
1024      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1025      It could be statically allocated, but the previous code didn't so we
1026      don't either.  */
1027   struct abbrev_info **abbrevs;
1028 };
1029
1030 /* Attributes have a name and a value.  */
1031 struct attribute
1032   {
1033     ENUM_BITFIELD(dwarf_attribute) name : 16;
1034     ENUM_BITFIELD(dwarf_form) form : 15;
1035
1036     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1037        field should be in u.str (existing only for DW_STRING) but it is kept
1038        here for better struct attribute alignment.  */
1039     unsigned int string_is_canonical : 1;
1040
1041     union
1042       {
1043         const char *str;
1044         struct dwarf_block *blk;
1045         ULONGEST unsnd;
1046         LONGEST snd;
1047         CORE_ADDR addr;
1048         struct signatured_type *signatured_type;
1049       }
1050     u;
1051   };
1052
1053 /* This data structure holds a complete die structure.  */
1054 struct die_info
1055   {
1056     /* DWARF-2 tag for this DIE.  */
1057     ENUM_BITFIELD(dwarf_tag) tag : 16;
1058
1059     /* Number of attributes */
1060     unsigned char num_attrs;
1061
1062     /* True if we're presently building the full type name for the
1063        type derived from this DIE.  */
1064     unsigned char building_fullname : 1;
1065
1066     /* Abbrev number */
1067     unsigned int abbrev;
1068
1069     /* Offset in .debug_info or .debug_types section.  */
1070     sect_offset offset;
1071
1072     /* The dies in a compilation unit form an n-ary tree.  PARENT
1073        points to this die's parent; CHILD points to the first child of
1074        this node; and all the children of a given node are chained
1075        together via their SIBLING fields.  */
1076     struct die_info *child;     /* Its first child, if any.  */
1077     struct die_info *sibling;   /* Its next sibling, if any.  */
1078     struct die_info *parent;    /* Its parent, if any.  */
1079
1080     /* An array of attributes, with NUM_ATTRS elements.  There may be
1081        zero, but it's not common and zero-sized arrays are not
1082        sufficiently portable C.  */
1083     struct attribute attrs[1];
1084   };
1085
1086 /* Get at parts of an attribute structure.  */
1087
1088 #define DW_STRING(attr)    ((attr)->u.str)
1089 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1090 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1091 #define DW_BLOCK(attr)     ((attr)->u.blk)
1092 #define DW_SND(attr)       ((attr)->u.snd)
1093 #define DW_ADDR(attr)      ((attr)->u.addr)
1094 #define DW_SIGNATURED_TYPE(attr) ((attr)->u.signatured_type)
1095
1096 /* Blocks are a bunch of untyped bytes.  */
1097 struct dwarf_block
1098   {
1099     size_t size;
1100
1101     /* Valid only if SIZE is not zero.  */
1102     const gdb_byte *data;
1103   };
1104
1105 #ifndef ATTR_ALLOC_CHUNK
1106 #define ATTR_ALLOC_CHUNK 4
1107 #endif
1108
1109 /* Allocate fields for structs, unions and enums in this size.  */
1110 #ifndef DW_FIELD_ALLOC_CHUNK
1111 #define DW_FIELD_ALLOC_CHUNK 4
1112 #endif
1113
1114 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1115    but this would require a corresponding change in unpack_field_as_long
1116    and friends.  */
1117 static int bits_per_byte = 8;
1118
1119 /* The routines that read and process dies for a C struct or C++ class
1120    pass lists of data member fields and lists of member function fields
1121    in an instance of a field_info structure, as defined below.  */
1122 struct field_info
1123   {
1124     /* List of data member and baseclasses fields.  */
1125     struct nextfield
1126       {
1127         struct nextfield *next;
1128         int accessibility;
1129         int virtuality;
1130         struct field field;
1131       }
1132      *fields, *baseclasses;
1133
1134     /* Number of fields (including baseclasses).  */
1135     int nfields;
1136
1137     /* Number of baseclasses.  */
1138     int nbaseclasses;
1139
1140     /* Set if the accesibility of one of the fields is not public.  */
1141     int non_public_fields;
1142
1143     /* Member function fields array, entries are allocated in the order they
1144        are encountered in the object file.  */
1145     struct nextfnfield
1146       {
1147         struct nextfnfield *next;
1148         struct fn_field fnfield;
1149       }
1150      *fnfields;
1151
1152     /* Member function fieldlist array, contains name of possibly overloaded
1153        member function, number of overloaded member functions and a pointer
1154        to the head of the member function field chain.  */
1155     struct fnfieldlist
1156       {
1157         const char *name;
1158         int length;
1159         struct nextfnfield *head;
1160       }
1161      *fnfieldlists;
1162
1163     /* Number of entries in the fnfieldlists array.  */
1164     int nfnfields;
1165
1166     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1167        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1168     struct typedef_field_list
1169       {
1170         struct typedef_field field;
1171         struct typedef_field_list *next;
1172       }
1173     *typedef_field_list;
1174     unsigned typedef_field_list_count;
1175   };
1176
1177 /* One item on the queue of compilation units to read in full symbols
1178    for.  */
1179 struct dwarf2_queue_item
1180 {
1181   struct dwarf2_per_cu_data *per_cu;
1182   enum language pretend_language;
1183   struct dwarf2_queue_item *next;
1184 };
1185
1186 /* The current queue.  */
1187 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1188
1189 /* Loaded secondary compilation units are kept in memory until they
1190    have not been referenced for the processing of this many
1191    compilation units.  Set this to zero to disable caching.  Cache
1192    sizes of up to at least twenty will improve startup time for
1193    typical inter-CU-reference binaries, at an obvious memory cost.  */
1194 static int dwarf2_max_cache_age = 5;
1195 static void
1196 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1197                            struct cmd_list_element *c, const char *value)
1198 {
1199   fprintf_filtered (file, _("The upper bound on the age of cached "
1200                             "dwarf2 compilation units is %s.\n"),
1201                     value);
1202 }
1203
1204
1205 /* Various complaints about symbol reading that don't abort the process.  */
1206
1207 static void
1208 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1209 {
1210   complaint (&symfile_complaints,
1211              _("statement list doesn't fit in .debug_line section"));
1212 }
1213
1214 static void
1215 dwarf2_debug_line_missing_file_complaint (void)
1216 {
1217   complaint (&symfile_complaints,
1218              _(".debug_line section has line data without a file"));
1219 }
1220
1221 static void
1222 dwarf2_debug_line_missing_end_sequence_complaint (void)
1223 {
1224   complaint (&symfile_complaints,
1225              _(".debug_line section has line "
1226                "program sequence without an end"));
1227 }
1228
1229 static void
1230 dwarf2_complex_location_expr_complaint (void)
1231 {
1232   complaint (&symfile_complaints, _("location expression too complex"));
1233 }
1234
1235 static void
1236 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1237                                               int arg3)
1238 {
1239   complaint (&symfile_complaints,
1240              _("const value length mismatch for '%s', got %d, expected %d"),
1241              arg1, arg2, arg3);
1242 }
1243
1244 static void
1245 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1246 {
1247   complaint (&symfile_complaints,
1248              _("debug info runs off end of %s section"
1249                " [in module %s]"),
1250              section->asection->name,
1251              bfd_get_filename (section->asection->owner));
1252 }
1253
1254 static void
1255 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1256 {
1257   complaint (&symfile_complaints,
1258              _("macro debug info contains a "
1259                "malformed macro definition:\n`%s'"),
1260              arg1);
1261 }
1262
1263 static void
1264 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1265 {
1266   complaint (&symfile_complaints,
1267              _("invalid attribute class or form for '%s' in '%s'"),
1268              arg1, arg2);
1269 }
1270
1271 /* local function prototypes */
1272
1273 static void dwarf2_locate_sections (bfd *, asection *, void *);
1274
1275 static void dwarf2_find_base_address (struct die_info *die,
1276                                       struct dwarf2_cu *cu);
1277
1278 static struct partial_symtab *create_partial_symtab
1279   (struct dwarf2_per_cu_data *per_cu, const char *name);
1280
1281 static void dwarf2_build_psymtabs_hard (struct objfile *);
1282
1283 static void scan_partial_symbols (struct partial_die_info *,
1284                                   CORE_ADDR *, CORE_ADDR *,
1285                                   int, struct dwarf2_cu *);
1286
1287 static void add_partial_symbol (struct partial_die_info *,
1288                                 struct dwarf2_cu *);
1289
1290 static void add_partial_namespace (struct partial_die_info *pdi,
1291                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1292                                    int need_pc, struct dwarf2_cu *cu);
1293
1294 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1295                                 CORE_ADDR *highpc, int need_pc,
1296                                 struct dwarf2_cu *cu);
1297
1298 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1299                                      struct dwarf2_cu *cu);
1300
1301 static void add_partial_subprogram (struct partial_die_info *pdi,
1302                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1303                                     int need_pc, struct dwarf2_cu *cu);
1304
1305 static void dwarf2_read_symtab (struct partial_symtab *,
1306                                 struct objfile *);
1307
1308 static void psymtab_to_symtab_1 (struct partial_symtab *);
1309
1310 static struct abbrev_info *abbrev_table_lookup_abbrev
1311   (const struct abbrev_table *, unsigned int);
1312
1313 static struct abbrev_table *abbrev_table_read_table
1314   (struct dwarf2_section_info *, sect_offset);
1315
1316 static void abbrev_table_free (struct abbrev_table *);
1317
1318 static void abbrev_table_free_cleanup (void *);
1319
1320 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1321                                  struct dwarf2_section_info *);
1322
1323 static void dwarf2_free_abbrev_table (void *);
1324
1325 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1326
1327 static struct partial_die_info *load_partial_dies
1328   (const struct die_reader_specs *, const gdb_byte *, int);
1329
1330 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1331                                          struct partial_die_info *,
1332                                          struct abbrev_info *,
1333                                          unsigned int,
1334                                          const gdb_byte *);
1335
1336 static struct partial_die_info *find_partial_die (sect_offset, int,
1337                                                   struct dwarf2_cu *);
1338
1339 static void fixup_partial_die (struct partial_die_info *,
1340                                struct dwarf2_cu *);
1341
1342 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1343                                        struct attribute *, struct attr_abbrev *,
1344                                        const gdb_byte *);
1345
1346 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1347
1348 static int read_1_signed_byte (bfd *, const gdb_byte *);
1349
1350 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1351
1352 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1353
1354 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1355
1356 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1357                                unsigned int *);
1358
1359 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1360
1361 static LONGEST read_checked_initial_length_and_offset
1362   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1363    unsigned int *, unsigned int *);
1364
1365 static LONGEST read_offset (bfd *, const gdb_byte *,
1366                             const struct comp_unit_head *,
1367                             unsigned int *);
1368
1369 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1370
1371 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1372                                        sect_offset);
1373
1374 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1375
1376 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1377
1378 static const char *read_indirect_string (bfd *, const gdb_byte *,
1379                                          const struct comp_unit_head *,
1380                                          unsigned int *);
1381
1382 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1383
1384 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1385
1386 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1387
1388 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1389                                               const gdb_byte *,
1390                                               unsigned int *);
1391
1392 static const char *read_str_index (const struct die_reader_specs *reader,
1393                                    struct dwarf2_cu *cu, ULONGEST str_index);
1394
1395 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1396
1397 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1398                                       struct dwarf2_cu *);
1399
1400 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1401                                                 unsigned int);
1402
1403 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1404                                struct dwarf2_cu *cu);
1405
1406 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1407
1408 static struct die_info *die_specification (struct die_info *die,
1409                                            struct dwarf2_cu **);
1410
1411 static void free_line_header (struct line_header *lh);
1412
1413 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1414                                                      struct dwarf2_cu *cu);
1415
1416 static void dwarf_decode_lines (struct line_header *, const char *,
1417                                 struct dwarf2_cu *, struct partial_symtab *,
1418                                 int);
1419
1420 static void dwarf2_start_subfile (const char *, const char *, const char *);
1421
1422 static void dwarf2_start_symtab (struct dwarf2_cu *,
1423                                  const char *, const char *, CORE_ADDR);
1424
1425 static struct symbol *new_symbol (struct die_info *, struct type *,
1426                                   struct dwarf2_cu *);
1427
1428 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1429                                        struct dwarf2_cu *, struct symbol *);
1430
1431 static void dwarf2_const_value (struct attribute *, struct symbol *,
1432                                 struct dwarf2_cu *);
1433
1434 static void dwarf2_const_value_attr (struct attribute *attr,
1435                                      struct type *type,
1436                                      const char *name,
1437                                      struct obstack *obstack,
1438                                      struct dwarf2_cu *cu, LONGEST *value,
1439                                      const gdb_byte **bytes,
1440                                      struct dwarf2_locexpr_baton **baton);
1441
1442 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1443
1444 static int need_gnat_info (struct dwarf2_cu *);
1445
1446 static struct type *die_descriptive_type (struct die_info *,
1447                                           struct dwarf2_cu *);
1448
1449 static void set_descriptive_type (struct type *, struct die_info *,
1450                                   struct dwarf2_cu *);
1451
1452 static struct type *die_containing_type (struct die_info *,
1453                                          struct dwarf2_cu *);
1454
1455 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1456                                      struct dwarf2_cu *);
1457
1458 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1459
1460 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1461
1462 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1463
1464 static char *typename_concat (struct obstack *obs, const char *prefix,
1465                               const char *suffix, int physname,
1466                               struct dwarf2_cu *cu);
1467
1468 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1469
1470 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1471
1472 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1473
1474 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1475
1476 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1477
1478 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1479                                struct dwarf2_cu *, struct partial_symtab *);
1480
1481 static int dwarf2_get_pc_bounds (struct die_info *,
1482                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1483                                  struct partial_symtab *);
1484
1485 static void get_scope_pc_bounds (struct die_info *,
1486                                  CORE_ADDR *, CORE_ADDR *,
1487                                  struct dwarf2_cu *);
1488
1489 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1490                                         CORE_ADDR, struct dwarf2_cu *);
1491
1492 static void dwarf2_add_field (struct field_info *, struct die_info *,
1493                               struct dwarf2_cu *);
1494
1495 static void dwarf2_attach_fields_to_type (struct field_info *,
1496                                           struct type *, struct dwarf2_cu *);
1497
1498 static void dwarf2_add_member_fn (struct field_info *,
1499                                   struct die_info *, struct type *,
1500                                   struct dwarf2_cu *);
1501
1502 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1503                                              struct type *,
1504                                              struct dwarf2_cu *);
1505
1506 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1507
1508 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1509
1510 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1511
1512 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1513
1514 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1515
1516 static struct type *read_module_type (struct die_info *die,
1517                                       struct dwarf2_cu *cu);
1518
1519 static const char *namespace_name (struct die_info *die,
1520                                    int *is_anonymous, struct dwarf2_cu *);
1521
1522 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1523
1524 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1525
1526 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1527                                                        struct dwarf2_cu *);
1528
1529 static struct die_info *read_die_and_siblings_1
1530   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1531    struct die_info *);
1532
1533 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1534                                                const gdb_byte *info_ptr,
1535                                                const gdb_byte **new_info_ptr,
1536                                                struct die_info *parent);
1537
1538 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1539                                         struct die_info **, const gdb_byte *,
1540                                         int *, int);
1541
1542 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1543                                       struct die_info **, const gdb_byte *,
1544                                       int *);
1545
1546 static void process_die (struct die_info *, struct dwarf2_cu *);
1547
1548 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1549                                              struct obstack *);
1550
1551 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1552
1553 static const char *dwarf2_full_name (const char *name,
1554                                      struct die_info *die,
1555                                      struct dwarf2_cu *cu);
1556
1557 static const char *dwarf2_physname (const char *name, struct die_info *die,
1558                                     struct dwarf2_cu *cu);
1559
1560 static struct die_info *dwarf2_extension (struct die_info *die,
1561                                           struct dwarf2_cu **);
1562
1563 static const char *dwarf_tag_name (unsigned int);
1564
1565 static const char *dwarf_attr_name (unsigned int);
1566
1567 static const char *dwarf_form_name (unsigned int);
1568
1569 static char *dwarf_bool_name (unsigned int);
1570
1571 static const char *dwarf_type_encoding_name (unsigned int);
1572
1573 static struct die_info *sibling_die (struct die_info *);
1574
1575 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1576
1577 static void dump_die_for_error (struct die_info *);
1578
1579 static void dump_die_1 (struct ui_file *, int level, int max_level,
1580                         struct die_info *);
1581
1582 /*static*/ void dump_die (struct die_info *, int max_level);
1583
1584 static void store_in_ref_table (struct die_info *,
1585                                 struct dwarf2_cu *);
1586
1587 static int is_ref_attr (struct attribute *);
1588
1589 static sect_offset dwarf2_get_ref_die_offset (struct attribute *);
1590
1591 static LONGEST dwarf2_get_attr_constant_value (struct attribute *, int);
1592
1593 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1594                                                struct attribute *,
1595                                                struct dwarf2_cu **);
1596
1597 static struct die_info *follow_die_ref (struct die_info *,
1598                                         struct attribute *,
1599                                         struct dwarf2_cu **);
1600
1601 static struct die_info *follow_die_sig (struct die_info *,
1602                                         struct attribute *,
1603                                         struct dwarf2_cu **);
1604
1605 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1606
1607 static void read_signatured_type (struct signatured_type *);
1608
1609 static struct type_unit_group *get_type_unit_group
1610     (struct dwarf2_cu *, struct attribute *);
1611
1612 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1613
1614 /* memory allocation interface */
1615
1616 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1617
1618 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1619
1620 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1621                                  const char *, int);
1622
1623 static int attr_form_is_block (struct attribute *);
1624
1625 static int attr_form_is_section_offset (struct attribute *);
1626
1627 static int attr_form_is_constant (struct attribute *);
1628
1629 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1630                                    struct dwarf2_loclist_baton *baton,
1631                                    struct attribute *attr);
1632
1633 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1634                                          struct symbol *sym,
1635                                          struct dwarf2_cu *cu,
1636                                          int is_block);
1637
1638 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1639                                      const gdb_byte *info_ptr,
1640                                      struct abbrev_info *abbrev);
1641
1642 static void free_stack_comp_unit (void *);
1643
1644 static hashval_t partial_die_hash (const void *item);
1645
1646 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1647
1648 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1649   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1650
1651 static void init_one_comp_unit (struct dwarf2_cu *cu,
1652                                 struct dwarf2_per_cu_data *per_cu);
1653
1654 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1655                                    struct die_info *comp_unit_die,
1656                                    enum language pretend_language);
1657
1658 static void free_heap_comp_unit (void *);
1659
1660 static void free_cached_comp_units (void *);
1661
1662 static void age_cached_comp_units (void);
1663
1664 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1665
1666 static struct type *set_die_type (struct die_info *, struct type *,
1667                                   struct dwarf2_cu *);
1668
1669 static void create_all_comp_units (struct objfile *);
1670
1671 static int create_all_type_units (struct objfile *);
1672
1673 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1674                                  enum language);
1675
1676 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1677                                     enum language);
1678
1679 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1680                                     enum language);
1681
1682 static void dwarf2_add_dependence (struct dwarf2_cu *,
1683                                    struct dwarf2_per_cu_data *);
1684
1685 static void dwarf2_mark (struct dwarf2_cu *);
1686
1687 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1688
1689 static struct type *get_die_type_at_offset (sect_offset,
1690                                             struct dwarf2_per_cu_data *per_cu);
1691
1692 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1693
1694 static void dwarf2_release_queue (void *dummy);
1695
1696 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1697                              enum language pretend_language);
1698
1699 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1700                                   struct dwarf2_per_cu_data *per_cu,
1701                                   enum language pretend_language);
1702
1703 static void process_queue (void);
1704
1705 static void find_file_and_directory (struct die_info *die,
1706                                      struct dwarf2_cu *cu,
1707                                      const char **name, const char **comp_dir);
1708
1709 static char *file_full_name (int file, struct line_header *lh,
1710                              const char *comp_dir);
1711
1712 static const gdb_byte *read_and_check_comp_unit_head
1713   (struct comp_unit_head *header,
1714    struct dwarf2_section_info *section,
1715    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1716    int is_debug_types_section);
1717
1718 static void init_cutu_and_read_dies
1719   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1720    int use_existing_cu, int keep,
1721    die_reader_func_ftype *die_reader_func, void *data);
1722
1723 static void init_cutu_and_read_dies_simple
1724   (struct dwarf2_per_cu_data *this_cu,
1725    die_reader_func_ftype *die_reader_func, void *data);
1726
1727 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1728
1729 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1730
1731 static struct dwo_unit *lookup_dwo_comp_unit
1732   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1733
1734 static struct dwo_unit *lookup_dwo_type_unit
1735   (struct signatured_type *, const char *, const char *);
1736
1737 static void free_dwo_file_cleanup (void *);
1738
1739 static void process_cu_includes (void);
1740
1741 static void check_producer (struct dwarf2_cu *cu);
1742
1743 #if WORDS_BIGENDIAN
1744
1745 /* Convert VALUE between big- and little-endian.  */
1746 static offset_type
1747 byte_swap (offset_type value)
1748 {
1749   offset_type result;
1750
1751   result = (value & 0xff) << 24;
1752   result |= (value & 0xff00) << 8;
1753   result |= (value & 0xff0000) >> 8;
1754   result |= (value & 0xff000000) >> 24;
1755   return result;
1756 }
1757
1758 #define MAYBE_SWAP(V)  byte_swap (V)
1759
1760 #else
1761 #define MAYBE_SWAP(V) (V)
1762 #endif /* WORDS_BIGENDIAN */
1763
1764 /* The suffix for an index file.  */
1765 #define INDEX_SUFFIX ".gdb-index"
1766
1767 /* Try to locate the sections we need for DWARF 2 debugging
1768    information and return true if we have enough to do something.
1769    NAMES points to the dwarf2 section names, or is NULL if the standard
1770    ELF names are used.  */
1771
1772 int
1773 dwarf2_has_info (struct objfile *objfile,
1774                  const struct dwarf2_debug_sections *names)
1775 {
1776   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1777   if (!dwarf2_per_objfile)
1778     {
1779       /* Initialize per-objfile state.  */
1780       struct dwarf2_per_objfile *data
1781         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1782
1783       memset (data, 0, sizeof (*data));
1784       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1785       dwarf2_per_objfile = data;
1786
1787       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1788                              (void *) names);
1789       dwarf2_per_objfile->objfile = objfile;
1790     }
1791   return (dwarf2_per_objfile->info.asection != NULL
1792           && dwarf2_per_objfile->abbrev.asection != NULL);
1793 }
1794
1795 /* When loading sections, we look either for uncompressed section or for
1796    compressed section names.  */
1797
1798 static int
1799 section_is_p (const char *section_name,
1800               const struct dwarf2_section_names *names)
1801 {
1802   if (names->normal != NULL
1803       && strcmp (section_name, names->normal) == 0)
1804     return 1;
1805   if (names->compressed != NULL
1806       && strcmp (section_name, names->compressed) == 0)
1807     return 1;
1808   return 0;
1809 }
1810
1811 /* This function is mapped across the sections and remembers the
1812    offset and size of each of the debugging sections we are interested
1813    in.  */
1814
1815 static void
1816 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1817 {
1818   const struct dwarf2_debug_sections *names;
1819   flagword aflag = bfd_get_section_flags (abfd, sectp);
1820
1821   if (vnames == NULL)
1822     names = &dwarf2_elf_names;
1823   else
1824     names = (const struct dwarf2_debug_sections *) vnames;
1825
1826   if ((aflag & SEC_HAS_CONTENTS) == 0)
1827     {
1828     }
1829   else if (section_is_p (sectp->name, &names->info))
1830     {
1831       dwarf2_per_objfile->info.asection = sectp;
1832       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1833     }
1834   else if (section_is_p (sectp->name, &names->abbrev))
1835     {
1836       dwarf2_per_objfile->abbrev.asection = sectp;
1837       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1838     }
1839   else if (section_is_p (sectp->name, &names->line))
1840     {
1841       dwarf2_per_objfile->line.asection = sectp;
1842       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1843     }
1844   else if (section_is_p (sectp->name, &names->loc))
1845     {
1846       dwarf2_per_objfile->loc.asection = sectp;
1847       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1848     }
1849   else if (section_is_p (sectp->name, &names->macinfo))
1850     {
1851       dwarf2_per_objfile->macinfo.asection = sectp;
1852       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1853     }
1854   else if (section_is_p (sectp->name, &names->macro))
1855     {
1856       dwarf2_per_objfile->macro.asection = sectp;
1857       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1858     }
1859   else if (section_is_p (sectp->name, &names->str))
1860     {
1861       dwarf2_per_objfile->str.asection = sectp;
1862       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1863     }
1864   else if (section_is_p (sectp->name, &names->addr))
1865     {
1866       dwarf2_per_objfile->addr.asection = sectp;
1867       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1868     }
1869   else if (section_is_p (sectp->name, &names->frame))
1870     {
1871       dwarf2_per_objfile->frame.asection = sectp;
1872       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1873     }
1874   else if (section_is_p (sectp->name, &names->eh_frame))
1875     {
1876       dwarf2_per_objfile->eh_frame.asection = sectp;
1877       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1878     }
1879   else if (section_is_p (sectp->name, &names->ranges))
1880     {
1881       dwarf2_per_objfile->ranges.asection = sectp;
1882       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1883     }
1884   else if (section_is_p (sectp->name, &names->types))
1885     {
1886       struct dwarf2_section_info type_section;
1887
1888       memset (&type_section, 0, sizeof (type_section));
1889       type_section.asection = sectp;
1890       type_section.size = bfd_get_section_size (sectp);
1891
1892       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1893                      &type_section);
1894     }
1895   else if (section_is_p (sectp->name, &names->gdb_index))
1896     {
1897       dwarf2_per_objfile->gdb_index.asection = sectp;
1898       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1899     }
1900
1901   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1902       && bfd_section_vma (abfd, sectp) == 0)
1903     dwarf2_per_objfile->has_section_at_zero = 1;
1904 }
1905
1906 /* A helper function that decides whether a section is empty,
1907    or not present.  */
1908
1909 static int
1910 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1911 {
1912   return info->asection == NULL || info->size == 0;
1913 }
1914
1915 /* Read the contents of the section INFO.
1916    OBJFILE is the main object file, but not necessarily the file where
1917    the section comes from.  E.g., for DWO files INFO->asection->owner
1918    is the bfd of the DWO file.
1919    If the section is compressed, uncompress it before returning.  */
1920
1921 static void
1922 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1923 {
1924   asection *sectp = info->asection;
1925   bfd *abfd;
1926   gdb_byte *buf, *retbuf;
1927   unsigned char header[4];
1928
1929   if (info->readin)
1930     return;
1931   info->buffer = NULL;
1932   info->readin = 1;
1933
1934   if (dwarf2_section_empty_p (info))
1935     return;
1936
1937   abfd = sectp->owner;
1938
1939   /* If the section has relocations, we must read it ourselves.
1940      Otherwise we attach it to the BFD.  */
1941   if ((sectp->flags & SEC_RELOC) == 0)
1942     {
1943       info->buffer = gdb_bfd_map_section (sectp, &info->size);
1944       return;
1945     }
1946
1947   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1948   info->buffer = buf;
1949
1950   /* When debugging .o files, we may need to apply relocations; see
1951      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1952      We never compress sections in .o files, so we only need to
1953      try this when the section is not compressed.  */
1954   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1955   if (retbuf != NULL)
1956     {
1957       info->buffer = retbuf;
1958       return;
1959     }
1960
1961   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1962       || bfd_bread (buf, info->size, abfd) != info->size)
1963     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1964            bfd_get_filename (abfd));
1965 }
1966
1967 /* A helper function that returns the size of a section in a safe way.
1968    If you are positive that the section has been read before using the
1969    size, then it is safe to refer to the dwarf2_section_info object's
1970    "size" field directly.  In other cases, you must call this
1971    function, because for compressed sections the size field is not set
1972    correctly until the section has been read.  */
1973
1974 static bfd_size_type
1975 dwarf2_section_size (struct objfile *objfile,
1976                      struct dwarf2_section_info *info)
1977 {
1978   if (!info->readin)
1979     dwarf2_read_section (objfile, info);
1980   return info->size;
1981 }
1982
1983 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1984    SECTION_NAME.  */
1985
1986 void
1987 dwarf2_get_section_info (struct objfile *objfile,
1988                          enum dwarf2_section_enum sect,
1989                          asection **sectp, const gdb_byte **bufp,
1990                          bfd_size_type *sizep)
1991 {
1992   struct dwarf2_per_objfile *data
1993     = objfile_data (objfile, dwarf2_objfile_data_key);
1994   struct dwarf2_section_info *info;
1995
1996   /* We may see an objfile without any DWARF, in which case we just
1997      return nothing.  */
1998   if (data == NULL)
1999     {
2000       *sectp = NULL;
2001       *bufp = NULL;
2002       *sizep = 0;
2003       return;
2004     }
2005   switch (sect)
2006     {
2007     case DWARF2_DEBUG_FRAME:
2008       info = &data->frame;
2009       break;
2010     case DWARF2_EH_FRAME:
2011       info = &data->eh_frame;
2012       break;
2013     default:
2014       gdb_assert_not_reached ("unexpected section");
2015     }
2016
2017   dwarf2_read_section (objfile, info);
2018
2019   *sectp = info->asection;
2020   *bufp = info->buffer;
2021   *sizep = info->size;
2022 }
2023
2024 /* A helper function to find the sections for a .dwz file.  */
2025
2026 static void
2027 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2028 {
2029   struct dwz_file *dwz_file = arg;
2030
2031   /* Note that we only support the standard ELF names, because .dwz
2032      is ELF-only (at the time of writing).  */
2033   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2034     {
2035       dwz_file->abbrev.asection = sectp;
2036       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2037     }
2038   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2039     {
2040       dwz_file->info.asection = sectp;
2041       dwz_file->info.size = bfd_get_section_size (sectp);
2042     }
2043   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2044     {
2045       dwz_file->str.asection = sectp;
2046       dwz_file->str.size = bfd_get_section_size (sectp);
2047     }
2048   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2049     {
2050       dwz_file->line.asection = sectp;
2051       dwz_file->line.size = bfd_get_section_size (sectp);
2052     }
2053   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2054     {
2055       dwz_file->macro.asection = sectp;
2056       dwz_file->macro.size = bfd_get_section_size (sectp);
2057     }
2058   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2059     {
2060       dwz_file->gdb_index.asection = sectp;
2061       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2062     }
2063 }
2064
2065 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2066    cannot be found.  */
2067
2068 static struct dwz_file *
2069 dwarf2_get_dwz_file (void)
2070 {
2071   bfd *abfd, *dwz_bfd;
2072   asection *section;
2073   gdb_byte *data;
2074   struct cleanup *cleanup;
2075   const char *filename;
2076   struct dwz_file *result;
2077
2078   if (dwarf2_per_objfile->dwz_file != NULL)
2079     return dwarf2_per_objfile->dwz_file;
2080
2081   abfd = dwarf2_per_objfile->objfile->obfd;
2082   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2083   if (section == NULL)
2084     error (_("could not find '.gnu_debugaltlink' section"));
2085   if (!bfd_malloc_and_get_section (abfd, section, &data))
2086     error (_("could not read '.gnu_debugaltlink' section: %s"),
2087            bfd_errmsg (bfd_get_error ()));
2088   cleanup = make_cleanup (xfree, data);
2089
2090   filename = data;
2091   if (!IS_ABSOLUTE_PATH (filename))
2092     {
2093       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2094       char *rel;
2095
2096       make_cleanup (xfree, abs);
2097       abs = ldirname (abs);
2098       make_cleanup (xfree, abs);
2099
2100       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2101       make_cleanup (xfree, rel);
2102       filename = rel;
2103     }
2104
2105   /* The format is just a NUL-terminated file name, followed by the
2106      build-id.  For now, though, we ignore the build-id.  */
2107   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2108   if (dwz_bfd == NULL)
2109     error (_("could not read '%s': %s"), filename,
2110            bfd_errmsg (bfd_get_error ()));
2111
2112   if (!bfd_check_format (dwz_bfd, bfd_object))
2113     {
2114       gdb_bfd_unref (dwz_bfd);
2115       error (_("file '%s' was not usable: %s"), filename,
2116              bfd_errmsg (bfd_get_error ()));
2117     }
2118
2119   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2120                            struct dwz_file);
2121   result->dwz_bfd = dwz_bfd;
2122
2123   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2124
2125   do_cleanups (cleanup);
2126
2127   dwarf2_per_objfile->dwz_file = result;
2128   return result;
2129 }
2130 \f
2131 /* DWARF quick_symbols_functions support.  */
2132
2133 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2134    unique line tables, so we maintain a separate table of all .debug_line
2135    derived entries to support the sharing.
2136    All the quick functions need is the list of file names.  We discard the
2137    line_header when we're done and don't need to record it here.  */
2138 struct quick_file_names
2139 {
2140   /* The data used to construct the hash key.  */
2141   struct stmt_list_hash hash;
2142
2143   /* The number of entries in file_names, real_names.  */
2144   unsigned int num_file_names;
2145
2146   /* The file names from the line table, after being run through
2147      file_full_name.  */
2148   const char **file_names;
2149
2150   /* The file names from the line table after being run through
2151      gdb_realpath.  These are computed lazily.  */
2152   const char **real_names;
2153 };
2154
2155 /* When using the index (and thus not using psymtabs), each CU has an
2156    object of this type.  This is used to hold information needed by
2157    the various "quick" methods.  */
2158 struct dwarf2_per_cu_quick_data
2159 {
2160   /* The file table.  This can be NULL if there was no file table
2161      or it's currently not read in.
2162      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2163   struct quick_file_names *file_names;
2164
2165   /* The corresponding symbol table.  This is NULL if symbols for this
2166      CU have not yet been read.  */
2167   struct symtab *symtab;
2168
2169   /* A temporary mark bit used when iterating over all CUs in
2170      expand_symtabs_matching.  */
2171   unsigned int mark : 1;
2172
2173   /* True if we've tried to read the file table and found there isn't one.
2174      There will be no point in trying to read it again next time.  */
2175   unsigned int no_file_data : 1;
2176 };
2177
2178 /* Utility hash function for a stmt_list_hash.  */
2179
2180 static hashval_t
2181 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2182 {
2183   hashval_t v = 0;
2184
2185   if (stmt_list_hash->dwo_unit != NULL)
2186     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2187   v += stmt_list_hash->line_offset.sect_off;
2188   return v;
2189 }
2190
2191 /* Utility equality function for a stmt_list_hash.  */
2192
2193 static int
2194 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2195                     const struct stmt_list_hash *rhs)
2196 {
2197   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2198     return 0;
2199   if (lhs->dwo_unit != NULL
2200       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2201     return 0;
2202
2203   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2204 }
2205
2206 /* Hash function for a quick_file_names.  */
2207
2208 static hashval_t
2209 hash_file_name_entry (const void *e)
2210 {
2211   const struct quick_file_names *file_data = e;
2212
2213   return hash_stmt_list_entry (&file_data->hash);
2214 }
2215
2216 /* Equality function for a quick_file_names.  */
2217
2218 static int
2219 eq_file_name_entry (const void *a, const void *b)
2220 {
2221   const struct quick_file_names *ea = a;
2222   const struct quick_file_names *eb = b;
2223
2224   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2225 }
2226
2227 /* Delete function for a quick_file_names.  */
2228
2229 static void
2230 delete_file_name_entry (void *e)
2231 {
2232   struct quick_file_names *file_data = e;
2233   int i;
2234
2235   for (i = 0; i < file_data->num_file_names; ++i)
2236     {
2237       xfree ((void*) file_data->file_names[i]);
2238       if (file_data->real_names)
2239         xfree ((void*) file_data->real_names[i]);
2240     }
2241
2242   /* The space for the struct itself lives on objfile_obstack,
2243      so we don't free it here.  */
2244 }
2245
2246 /* Create a quick_file_names hash table.  */
2247
2248 static htab_t
2249 create_quick_file_names_table (unsigned int nr_initial_entries)
2250 {
2251   return htab_create_alloc (nr_initial_entries,
2252                             hash_file_name_entry, eq_file_name_entry,
2253                             delete_file_name_entry, xcalloc, xfree);
2254 }
2255
2256 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2257    have to be created afterwards.  You should call age_cached_comp_units after
2258    processing PER_CU->CU.  dw2_setup must have been already called.  */
2259
2260 static void
2261 load_cu (struct dwarf2_per_cu_data *per_cu)
2262 {
2263   if (per_cu->is_debug_types)
2264     load_full_type_unit (per_cu);
2265   else
2266     load_full_comp_unit (per_cu, language_minimal);
2267
2268   gdb_assert (per_cu->cu != NULL);
2269
2270   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2271 }
2272
2273 /* Read in the symbols for PER_CU.  */
2274
2275 static void
2276 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2277 {
2278   struct cleanup *back_to;
2279
2280   /* Skip type_unit_groups, reading the type units they contain
2281      is handled elsewhere.  */
2282   if (IS_TYPE_UNIT_GROUP (per_cu))
2283     return;
2284
2285   back_to = make_cleanup (dwarf2_release_queue, NULL);
2286
2287   if (dwarf2_per_objfile->using_index
2288       ? per_cu->v.quick->symtab == NULL
2289       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2290     {
2291       queue_comp_unit (per_cu, language_minimal);
2292       load_cu (per_cu);
2293     }
2294
2295   process_queue ();
2296
2297   /* Age the cache, releasing compilation units that have not
2298      been used recently.  */
2299   age_cached_comp_units ();
2300
2301   do_cleanups (back_to);
2302 }
2303
2304 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2305    the objfile from which this CU came.  Returns the resulting symbol
2306    table.  */
2307
2308 static struct symtab *
2309 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2310 {
2311   gdb_assert (dwarf2_per_objfile->using_index);
2312   if (!per_cu->v.quick->symtab)
2313     {
2314       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2315       increment_reading_symtab ();
2316       dw2_do_instantiate_symtab (per_cu);
2317       process_cu_includes ();
2318       do_cleanups (back_to);
2319     }
2320   return per_cu->v.quick->symtab;
2321 }
2322
2323 /* Return the CU given its index.
2324
2325    This is intended for loops like:
2326
2327    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2328                     + dwarf2_per_objfile->n_type_units); ++i)
2329      {
2330        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2331
2332        ...;
2333      }
2334 */
2335
2336 static struct dwarf2_per_cu_data *
2337 dw2_get_cu (int index)
2338 {
2339   if (index >= dwarf2_per_objfile->n_comp_units)
2340     {
2341       index -= dwarf2_per_objfile->n_comp_units;
2342       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2343       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2344     }
2345
2346   return dwarf2_per_objfile->all_comp_units[index];
2347 }
2348
2349 /* Return the primary CU given its index.
2350    The difference between this function and dw2_get_cu is in the handling
2351    of type units (TUs).  Here we return the type_unit_group object.
2352
2353    This is intended for loops like:
2354
2355    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2356                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2357      {
2358        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2359
2360        ...;
2361      }
2362 */
2363
2364 static struct dwarf2_per_cu_data *
2365 dw2_get_primary_cu (int index)
2366 {
2367   if (index >= dwarf2_per_objfile->n_comp_units)
2368     {
2369       index -= dwarf2_per_objfile->n_comp_units;
2370       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2371       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2372     }
2373
2374   return dwarf2_per_objfile->all_comp_units[index];
2375 }
2376
2377 /* A helper for create_cus_from_index that handles a given list of
2378    CUs.  */
2379
2380 static void
2381 create_cus_from_index_list (struct objfile *objfile,
2382                             const gdb_byte *cu_list, offset_type n_elements,
2383                             struct dwarf2_section_info *section,
2384                             int is_dwz,
2385                             int base_offset)
2386 {
2387   offset_type i;
2388
2389   for (i = 0; i < n_elements; i += 2)
2390     {
2391       struct dwarf2_per_cu_data *the_cu;
2392       ULONGEST offset, length;
2393
2394       gdb_static_assert (sizeof (ULONGEST) >= 8);
2395       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2396       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2397       cu_list += 2 * 8;
2398
2399       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2400                                struct dwarf2_per_cu_data);
2401       the_cu->offset.sect_off = offset;
2402       the_cu->length = length;
2403       the_cu->objfile = objfile;
2404       the_cu->section = section;
2405       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2406                                         struct dwarf2_per_cu_quick_data);
2407       the_cu->is_dwz = is_dwz;
2408       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2409     }
2410 }
2411
2412 /* Read the CU list from the mapped index, and use it to create all
2413    the CU objects for this objfile.  */
2414
2415 static void
2416 create_cus_from_index (struct objfile *objfile,
2417                        const gdb_byte *cu_list, offset_type cu_list_elements,
2418                        const gdb_byte *dwz_list, offset_type dwz_elements)
2419 {
2420   struct dwz_file *dwz;
2421
2422   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2423   dwarf2_per_objfile->all_comp_units
2424     = obstack_alloc (&objfile->objfile_obstack,
2425                      dwarf2_per_objfile->n_comp_units
2426                      * sizeof (struct dwarf2_per_cu_data *));
2427
2428   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2429                               &dwarf2_per_objfile->info, 0, 0);
2430
2431   if (dwz_elements == 0)
2432     return;
2433
2434   dwz = dwarf2_get_dwz_file ();
2435   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2436                               cu_list_elements / 2);
2437 }
2438
2439 /* Create the signatured type hash table from the index.  */
2440
2441 static void
2442 create_signatured_type_table_from_index (struct objfile *objfile,
2443                                          struct dwarf2_section_info *section,
2444                                          const gdb_byte *bytes,
2445                                          offset_type elements)
2446 {
2447   offset_type i;
2448   htab_t sig_types_hash;
2449
2450   dwarf2_per_objfile->n_type_units = elements / 3;
2451   dwarf2_per_objfile->all_type_units
2452     = obstack_alloc (&objfile->objfile_obstack,
2453                      dwarf2_per_objfile->n_type_units
2454                      * sizeof (struct signatured_type *));
2455
2456   sig_types_hash = allocate_signatured_type_table (objfile);
2457
2458   for (i = 0; i < elements; i += 3)
2459     {
2460       struct signatured_type *sig_type;
2461       ULONGEST offset, type_offset_in_tu, signature;
2462       void **slot;
2463
2464       gdb_static_assert (sizeof (ULONGEST) >= 8);
2465       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2466       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2467                                                     BFD_ENDIAN_LITTLE);
2468       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2469       bytes += 3 * 8;
2470
2471       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2472                                  struct signatured_type);
2473       sig_type->signature = signature;
2474       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2475       sig_type->per_cu.is_debug_types = 1;
2476       sig_type->per_cu.section = section;
2477       sig_type->per_cu.offset.sect_off = offset;
2478       sig_type->per_cu.objfile = objfile;
2479       sig_type->per_cu.v.quick
2480         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2481                           struct dwarf2_per_cu_quick_data);
2482
2483       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2484       *slot = sig_type;
2485
2486       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2487     }
2488
2489   dwarf2_per_objfile->signatured_types = sig_types_hash;
2490 }
2491
2492 /* Read the address map data from the mapped index, and use it to
2493    populate the objfile's psymtabs_addrmap.  */
2494
2495 static void
2496 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2497 {
2498   const gdb_byte *iter, *end;
2499   struct obstack temp_obstack;
2500   struct addrmap *mutable_map;
2501   struct cleanup *cleanup;
2502   CORE_ADDR baseaddr;
2503
2504   obstack_init (&temp_obstack);
2505   cleanup = make_cleanup_obstack_free (&temp_obstack);
2506   mutable_map = addrmap_create_mutable (&temp_obstack);
2507
2508   iter = index->address_table;
2509   end = iter + index->address_table_size;
2510
2511   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2512
2513   while (iter < end)
2514     {
2515       ULONGEST hi, lo, cu_index;
2516       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2517       iter += 8;
2518       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2519       iter += 8;
2520       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2521       iter += 4;
2522
2523       if (cu_index < dwarf2_per_objfile->n_comp_units)
2524         {
2525           addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2526                              dw2_get_cu (cu_index));
2527         }
2528       else
2529         {
2530           complaint (&symfile_complaints,
2531                      _(".gdb_index address table has invalid CU number %u"),
2532                      (unsigned) cu_index);
2533         }
2534     }
2535
2536   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2537                                                     &objfile->objfile_obstack);
2538   do_cleanups (cleanup);
2539 }
2540
2541 /* The hash function for strings in the mapped index.  This is the same as
2542    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2543    implementation.  This is necessary because the hash function is tied to the
2544    format of the mapped index file.  The hash values do not have to match with
2545    SYMBOL_HASH_NEXT.
2546    
2547    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2548
2549 static hashval_t
2550 mapped_index_string_hash (int index_version, const void *p)
2551 {
2552   const unsigned char *str = (const unsigned char *) p;
2553   hashval_t r = 0;
2554   unsigned char c;
2555
2556   while ((c = *str++) != 0)
2557     {
2558       if (index_version >= 5)
2559         c = tolower (c);
2560       r = r * 67 + c - 113;
2561     }
2562
2563   return r;
2564 }
2565
2566 /* Find a slot in the mapped index INDEX for the object named NAME.
2567    If NAME is found, set *VEC_OUT to point to the CU vector in the
2568    constant pool and return 1.  If NAME cannot be found, return 0.  */
2569
2570 static int
2571 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2572                           offset_type **vec_out)
2573 {
2574   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2575   offset_type hash;
2576   offset_type slot, step;
2577   int (*cmp) (const char *, const char *);
2578
2579   if (current_language->la_language == language_cplus
2580       || current_language->la_language == language_java
2581       || current_language->la_language == language_fortran)
2582     {
2583       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2584          not contain any.  */
2585       const char *paren = strchr (name, '(');
2586
2587       if (paren)
2588         {
2589           char *dup;
2590
2591           dup = xmalloc (paren - name + 1);
2592           memcpy (dup, name, paren - name);
2593           dup[paren - name] = 0;
2594
2595           make_cleanup (xfree, dup);
2596           name = dup;
2597         }
2598     }
2599
2600   /* Index version 4 did not support case insensitive searches.  But the
2601      indices for case insensitive languages are built in lowercase, therefore
2602      simulate our NAME being searched is also lowercased.  */
2603   hash = mapped_index_string_hash ((index->version == 4
2604                                     && case_sensitivity == case_sensitive_off
2605                                     ? 5 : index->version),
2606                                    name);
2607
2608   slot = hash & (index->symbol_table_slots - 1);
2609   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2610   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2611
2612   for (;;)
2613     {
2614       /* Convert a slot number to an offset into the table.  */
2615       offset_type i = 2 * slot;
2616       const char *str;
2617       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2618         {
2619           do_cleanups (back_to);
2620           return 0;
2621         }
2622
2623       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2624       if (!cmp (name, str))
2625         {
2626           *vec_out = (offset_type *) (index->constant_pool
2627                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2628           do_cleanups (back_to);
2629           return 1;
2630         }
2631
2632       slot = (slot + step) & (index->symbol_table_slots - 1);
2633     }
2634 }
2635
2636 /* A helper function that reads the .gdb_index from SECTION and fills
2637    in MAP.  FILENAME is the name of the file containing the section;
2638    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2639    ok to use deprecated sections.
2640
2641    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2642    out parameters that are filled in with information about the CU and
2643    TU lists in the section.
2644
2645    Returns 1 if all went well, 0 otherwise.  */
2646
2647 static int
2648 read_index_from_section (struct objfile *objfile,
2649                          const char *filename,
2650                          int deprecated_ok,
2651                          struct dwarf2_section_info *section,
2652                          struct mapped_index *map,
2653                          const gdb_byte **cu_list,
2654                          offset_type *cu_list_elements,
2655                          const gdb_byte **types_list,
2656                          offset_type *types_list_elements)
2657 {
2658   const char *addr;
2659   offset_type version;
2660   offset_type *metadata;
2661   int i;
2662
2663   if (dwarf2_section_empty_p (section))
2664     return 0;
2665
2666   /* Older elfutils strip versions could keep the section in the main
2667      executable while splitting it for the separate debug info file.  */
2668   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2669     return 0;
2670
2671   dwarf2_read_section (objfile, section);
2672
2673   addr = section->buffer;
2674   /* Version check.  */
2675   version = MAYBE_SWAP (*(offset_type *) addr);
2676   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2677      causes the index to behave very poorly for certain requests.  Version 3
2678      contained incomplete addrmap.  So, it seems better to just ignore such
2679      indices.  */
2680   if (version < 4)
2681     {
2682       static int warning_printed = 0;
2683       if (!warning_printed)
2684         {
2685           warning (_("Skipping obsolete .gdb_index section in %s."),
2686                    filename);
2687           warning_printed = 1;
2688         }
2689       return 0;
2690     }
2691   /* Index version 4 uses a different hash function than index version
2692      5 and later.
2693
2694      Versions earlier than 6 did not emit psymbols for inlined
2695      functions.  Using these files will cause GDB not to be able to
2696      set breakpoints on inlined functions by name, so we ignore these
2697      indices unless the user has done
2698      "set use-deprecated-index-sections on".  */
2699   if (version < 6 && !deprecated_ok)
2700     {
2701       static int warning_printed = 0;
2702       if (!warning_printed)
2703         {
2704           warning (_("\
2705 Skipping deprecated .gdb_index section in %s.\n\
2706 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2707 to use the section anyway."),
2708                    filename);
2709           warning_printed = 1;
2710         }
2711       return 0;
2712     }
2713   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2714      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2715      we can't distinguish gdb-generated indices from gold-generated ones, so
2716      nothing to do here.  */
2717
2718   /* Indexes with higher version than the one supported by GDB may be no
2719      longer backward compatible.  */
2720   if (version > 8)
2721     return 0;
2722
2723   map->version = version;
2724   map->total_size = section->size;
2725
2726   metadata = (offset_type *) (addr + sizeof (offset_type));
2727
2728   i = 0;
2729   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2730   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2731                        / 8);
2732   ++i;
2733
2734   *types_list = addr + MAYBE_SWAP (metadata[i]);
2735   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2736                            - MAYBE_SWAP (metadata[i]))
2737                           / 8);
2738   ++i;
2739
2740   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2741   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2742                              - MAYBE_SWAP (metadata[i]));
2743   ++i;
2744
2745   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2746   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2747                               - MAYBE_SWAP (metadata[i]))
2748                              / (2 * sizeof (offset_type)));
2749   ++i;
2750
2751   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2752
2753   return 1;
2754 }
2755
2756
2757 /* Read the index file.  If everything went ok, initialize the "quick"
2758    elements of all the CUs and return 1.  Otherwise, return 0.  */
2759
2760 static int
2761 dwarf2_read_index (struct objfile *objfile)
2762 {
2763   struct mapped_index local_map, *map;
2764   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2765   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2766
2767   if (!read_index_from_section (objfile, objfile->name,
2768                                 use_deprecated_index_sections,
2769                                 &dwarf2_per_objfile->gdb_index, &local_map,
2770                                 &cu_list, &cu_list_elements,
2771                                 &types_list, &types_list_elements))
2772     return 0;
2773
2774   /* Don't use the index if it's empty.  */
2775   if (local_map.symbol_table_slots == 0)
2776     return 0;
2777
2778   /* If there is a .dwz file, read it so we can get its CU list as
2779      well.  */
2780   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2781     {
2782       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2783       struct mapped_index dwz_map;
2784       const gdb_byte *dwz_types_ignore;
2785       offset_type dwz_types_elements_ignore;
2786
2787       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2788                                     1,
2789                                     &dwz->gdb_index, &dwz_map,
2790                                     &dwz_list, &dwz_list_elements,
2791                                     &dwz_types_ignore,
2792                                     &dwz_types_elements_ignore))
2793         {
2794           warning (_("could not read '.gdb_index' section from %s; skipping"),
2795                    bfd_get_filename (dwz->dwz_bfd));
2796           return 0;
2797         }
2798     }
2799
2800   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2801                          dwz_list_elements);
2802
2803   if (types_list_elements)
2804     {
2805       struct dwarf2_section_info *section;
2806
2807       /* We can only handle a single .debug_types when we have an
2808          index.  */
2809       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2810         return 0;
2811
2812       section = VEC_index (dwarf2_section_info_def,
2813                            dwarf2_per_objfile->types, 0);
2814
2815       create_signatured_type_table_from_index (objfile, section, types_list,
2816                                                types_list_elements);
2817     }
2818
2819   create_addrmap_from_index (objfile, &local_map);
2820
2821   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2822   *map = local_map;
2823
2824   dwarf2_per_objfile->index_table = map;
2825   dwarf2_per_objfile->using_index = 1;
2826   dwarf2_per_objfile->quick_file_names_table =
2827     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2828
2829   return 1;
2830 }
2831
2832 /* A helper for the "quick" functions which sets the global
2833    dwarf2_per_objfile according to OBJFILE.  */
2834
2835 static void
2836 dw2_setup (struct objfile *objfile)
2837 {
2838   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2839   gdb_assert (dwarf2_per_objfile);
2840 }
2841
2842 /* die_reader_func for dw2_get_file_names.  */
2843
2844 static void
2845 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2846                            const gdb_byte *info_ptr,
2847                            struct die_info *comp_unit_die,
2848                            int has_children,
2849                            void *data)
2850 {
2851   struct dwarf2_cu *cu = reader->cu;
2852   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2853   struct objfile *objfile = dwarf2_per_objfile->objfile;
2854   struct dwarf2_per_cu_data *lh_cu;
2855   struct line_header *lh;
2856   struct attribute *attr;
2857   int i;
2858   const char *name, *comp_dir;
2859   void **slot;
2860   struct quick_file_names *qfn;
2861   unsigned int line_offset;
2862
2863   gdb_assert (! this_cu->is_debug_types);
2864
2865   /* Our callers never want to match partial units -- instead they
2866      will match the enclosing full CU.  */
2867   if (comp_unit_die->tag == DW_TAG_partial_unit)
2868     {
2869       this_cu->v.quick->no_file_data = 1;
2870       return;
2871     }
2872
2873   lh_cu = this_cu;
2874   lh = NULL;
2875   slot = NULL;
2876   line_offset = 0;
2877
2878   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2879   if (attr)
2880     {
2881       struct quick_file_names find_entry;
2882
2883       line_offset = DW_UNSND (attr);
2884
2885       /* We may have already read in this line header (TU line header sharing).
2886          If we have we're done.  */
2887       find_entry.hash.dwo_unit = cu->dwo_unit;
2888       find_entry.hash.line_offset.sect_off = line_offset;
2889       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2890                              &find_entry, INSERT);
2891       if (*slot != NULL)
2892         {
2893           lh_cu->v.quick->file_names = *slot;
2894           return;
2895         }
2896
2897       lh = dwarf_decode_line_header (line_offset, cu);
2898     }
2899   if (lh == NULL)
2900     {
2901       lh_cu->v.quick->no_file_data = 1;
2902       return;
2903     }
2904
2905   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2906   qfn->hash.dwo_unit = cu->dwo_unit;
2907   qfn->hash.line_offset.sect_off = line_offset;
2908   gdb_assert (slot != NULL);
2909   *slot = qfn;
2910
2911   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2912
2913   qfn->num_file_names = lh->num_file_names;
2914   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2915                                    lh->num_file_names * sizeof (char *));
2916   for (i = 0; i < lh->num_file_names; ++i)
2917     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2918   qfn->real_names = NULL;
2919
2920   free_line_header (lh);
2921
2922   lh_cu->v.quick->file_names = qfn;
2923 }
2924
2925 /* A helper for the "quick" functions which attempts to read the line
2926    table for THIS_CU.  */
2927
2928 static struct quick_file_names *
2929 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
2930 {
2931   /* This should never be called for TUs.  */
2932   gdb_assert (! this_cu->is_debug_types);
2933   /* Nor type unit groups.  */
2934   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
2935
2936   if (this_cu->v.quick->file_names != NULL)
2937     return this_cu->v.quick->file_names;
2938   /* If we know there is no line data, no point in looking again.  */
2939   if (this_cu->v.quick->no_file_data)
2940     return NULL;
2941
2942   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2943
2944   if (this_cu->v.quick->no_file_data)
2945     return NULL;
2946   return this_cu->v.quick->file_names;
2947 }
2948
2949 /* A helper for the "quick" functions which computes and caches the
2950    real path for a given file name from the line table.  */
2951
2952 static const char *
2953 dw2_get_real_path (struct objfile *objfile,
2954                    struct quick_file_names *qfn, int index)
2955 {
2956   if (qfn->real_names == NULL)
2957     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2958                                       qfn->num_file_names, sizeof (char *));
2959
2960   if (qfn->real_names[index] == NULL)
2961     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2962
2963   return qfn->real_names[index];
2964 }
2965
2966 static struct symtab *
2967 dw2_find_last_source_symtab (struct objfile *objfile)
2968 {
2969   int index;
2970
2971   dw2_setup (objfile);
2972   index = dwarf2_per_objfile->n_comp_units - 1;
2973   return dw2_instantiate_symtab (dw2_get_cu (index));
2974 }
2975
2976 /* Traversal function for dw2_forget_cached_source_info.  */
2977
2978 static int
2979 dw2_free_cached_file_names (void **slot, void *info)
2980 {
2981   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
2982
2983   if (file_data->real_names)
2984     {
2985       int i;
2986
2987       for (i = 0; i < file_data->num_file_names; ++i)
2988         {
2989           xfree ((void*) file_data->real_names[i]);
2990           file_data->real_names[i] = NULL;
2991         }
2992     }
2993
2994   return 1;
2995 }
2996
2997 static void
2998 dw2_forget_cached_source_info (struct objfile *objfile)
2999 {
3000   dw2_setup (objfile);
3001
3002   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3003                           dw2_free_cached_file_names, NULL);
3004 }
3005
3006 /* Helper function for dw2_map_symtabs_matching_filename that expands
3007    the symtabs and calls the iterator.  */
3008
3009 static int
3010 dw2_map_expand_apply (struct objfile *objfile,
3011                       struct dwarf2_per_cu_data *per_cu,
3012                       const char *name, const char *real_path,
3013                       int (*callback) (struct symtab *, void *),
3014                       void *data)
3015 {
3016   struct symtab *last_made = objfile->symtabs;
3017
3018   /* Don't visit already-expanded CUs.  */
3019   if (per_cu->v.quick->symtab)
3020     return 0;
3021
3022   /* This may expand more than one symtab, and we want to iterate over
3023      all of them.  */
3024   dw2_instantiate_symtab (per_cu);
3025
3026   return iterate_over_some_symtabs (name, real_path, callback, data,
3027                                     objfile->symtabs, last_made);
3028 }
3029
3030 /* Implementation of the map_symtabs_matching_filename method.  */
3031
3032 static int
3033 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3034                                    const char *real_path,
3035                                    int (*callback) (struct symtab *, void *),
3036                                    void *data)
3037 {
3038   int i;
3039   const char *name_basename = lbasename (name);
3040
3041   dw2_setup (objfile);
3042
3043   /* The rule is CUs specify all the files, including those used by
3044      any TU, so there's no need to scan TUs here.  */
3045
3046   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3047     {
3048       int j;
3049       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3050       struct quick_file_names *file_data;
3051
3052       /* We only need to look at symtabs not already expanded.  */
3053       if (per_cu->v.quick->symtab)
3054         continue;
3055
3056       file_data = dw2_get_file_names (per_cu);
3057       if (file_data == NULL)
3058         continue;
3059
3060       for (j = 0; j < file_data->num_file_names; ++j)
3061         {
3062           const char *this_name = file_data->file_names[j];
3063           const char *this_real_name;
3064
3065           if (compare_filenames_for_search (this_name, name))
3066             {
3067               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3068                                         callback, data))
3069                 return 1;
3070               continue;
3071             }
3072
3073           /* Before we invoke realpath, which can get expensive when many
3074              files are involved, do a quick comparison of the basenames.  */
3075           if (! basenames_may_differ
3076               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3077             continue;
3078
3079           this_real_name = dw2_get_real_path (objfile, file_data, j);
3080           if (compare_filenames_for_search (this_real_name, name))
3081             {
3082               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3083                                         callback, data))
3084                 return 1;
3085               continue;
3086             }
3087
3088           if (real_path != NULL)
3089             {
3090               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3091               gdb_assert (IS_ABSOLUTE_PATH (name));
3092               if (this_real_name != NULL
3093                   && FILENAME_CMP (real_path, this_real_name) == 0)
3094                 {
3095                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3096                                             callback, data))
3097                     return 1;
3098                   continue;
3099                 }
3100             }
3101         }
3102     }
3103
3104   return 0;
3105 }
3106
3107 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3108
3109 struct dw2_symtab_iterator
3110 {
3111   /* The internalized form of .gdb_index.  */
3112   struct mapped_index *index;
3113   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3114   int want_specific_block;
3115   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3116      Unused if !WANT_SPECIFIC_BLOCK.  */
3117   int block_index;
3118   /* The kind of symbol we're looking for.  */
3119   domain_enum domain;
3120   /* The list of CUs from the index entry of the symbol,
3121      or NULL if not found.  */
3122   offset_type *vec;
3123   /* The next element in VEC to look at.  */
3124   int next;
3125   /* The number of elements in VEC, or zero if there is no match.  */
3126   int length;
3127 };
3128
3129 /* Initialize the index symtab iterator ITER.
3130    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3131    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3132
3133 static void
3134 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3135                       struct mapped_index *index,
3136                       int want_specific_block,
3137                       int block_index,
3138                       domain_enum domain,
3139                       const char *name)
3140 {
3141   iter->index = index;
3142   iter->want_specific_block = want_specific_block;
3143   iter->block_index = block_index;
3144   iter->domain = domain;
3145   iter->next = 0;
3146
3147   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3148     iter->length = MAYBE_SWAP (*iter->vec);
3149   else
3150     {
3151       iter->vec = NULL;
3152       iter->length = 0;
3153     }
3154 }
3155
3156 /* Return the next matching CU or NULL if there are no more.  */
3157
3158 static struct dwarf2_per_cu_data *
3159 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3160 {
3161   for ( ; iter->next < iter->length; ++iter->next)
3162     {
3163       offset_type cu_index_and_attrs =
3164         MAYBE_SWAP (iter->vec[iter->next + 1]);
3165       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3166       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3167       int want_static = iter->block_index != GLOBAL_BLOCK;
3168       /* This value is only valid for index versions >= 7.  */
3169       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3170       gdb_index_symbol_kind symbol_kind =
3171         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3172       /* Only check the symbol attributes if they're present.
3173          Indices prior to version 7 don't record them,
3174          and indices >= 7 may elide them for certain symbols
3175          (gold does this).  */
3176       int attrs_valid =
3177         (iter->index->version >= 7
3178          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3179
3180       /* Skip if already read in.  */
3181       if (per_cu->v.quick->symtab)
3182         continue;
3183
3184       if (attrs_valid
3185           && iter->want_specific_block
3186           && want_static != is_static)
3187         continue;
3188
3189       /* Only check the symbol's kind if it has one.  */
3190       if (attrs_valid)
3191         {
3192           switch (iter->domain)
3193             {
3194             case VAR_DOMAIN:
3195               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3196                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3197                   /* Some types are also in VAR_DOMAIN.  */
3198                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3199                 continue;
3200               break;
3201             case STRUCT_DOMAIN:
3202               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3203                 continue;
3204               break;
3205             case LABEL_DOMAIN:
3206               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3207                 continue;
3208               break;
3209             default:
3210               break;
3211             }
3212         }
3213
3214       ++iter->next;
3215       return per_cu;
3216     }
3217
3218   return NULL;
3219 }
3220
3221 static struct symtab *
3222 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3223                    const char *name, domain_enum domain)
3224 {
3225   struct symtab *stab_best = NULL;
3226   struct mapped_index *index;
3227
3228   dw2_setup (objfile);
3229
3230   index = dwarf2_per_objfile->index_table;
3231
3232   /* index is NULL if OBJF_READNOW.  */
3233   if (index)
3234     {
3235       struct dw2_symtab_iterator iter;
3236       struct dwarf2_per_cu_data *per_cu;
3237
3238       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3239
3240       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3241         {
3242           struct symbol *sym = NULL;
3243           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3244
3245           /* Some caution must be observed with overloaded functions
3246              and methods, since the index will not contain any overload
3247              information (but NAME might contain it).  */
3248           if (stab->primary)
3249             {
3250               struct blockvector *bv = BLOCKVECTOR (stab);
3251               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3252
3253               sym = lookup_block_symbol (block, name, domain);
3254             }
3255
3256           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3257             {
3258               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3259                 return stab;
3260
3261               stab_best = stab;
3262             }
3263
3264           /* Keep looking through other CUs.  */
3265         }
3266     }
3267
3268   return stab_best;
3269 }
3270
3271 static void
3272 dw2_print_stats (struct objfile *objfile)
3273 {
3274   int i, total, count;
3275
3276   dw2_setup (objfile);
3277   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3278   count = 0;
3279   for (i = 0; i < total; ++i)
3280     {
3281       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3282
3283       if (!per_cu->v.quick->symtab)
3284         ++count;
3285     }
3286   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3287   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3288 }
3289
3290 static void
3291 dw2_dump (struct objfile *objfile)
3292 {
3293   /* Nothing worth printing.  */
3294 }
3295
3296 static void
3297 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3298               struct section_offsets *delta)
3299 {
3300   /* There's nothing to relocate here.  */
3301 }
3302
3303 static void
3304 dw2_expand_symtabs_for_function (struct objfile *objfile,
3305                                  const char *func_name)
3306 {
3307   struct mapped_index *index;
3308
3309   dw2_setup (objfile);
3310
3311   index = dwarf2_per_objfile->index_table;
3312
3313   /* index is NULL if OBJF_READNOW.  */
3314   if (index)
3315     {
3316       struct dw2_symtab_iterator iter;
3317       struct dwarf2_per_cu_data *per_cu;
3318
3319       /* Note: It doesn't matter what we pass for block_index here.  */
3320       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3321                             func_name);
3322
3323       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3324         dw2_instantiate_symtab (per_cu);
3325     }
3326 }
3327
3328 static void
3329 dw2_expand_all_symtabs (struct objfile *objfile)
3330 {
3331   int i;
3332
3333   dw2_setup (objfile);
3334
3335   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3336                    + dwarf2_per_objfile->n_type_units); ++i)
3337     {
3338       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3339
3340       dw2_instantiate_symtab (per_cu);
3341     }
3342 }
3343
3344 static void
3345 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3346                                   const char *fullname)
3347 {
3348   int i;
3349
3350   dw2_setup (objfile);
3351
3352   /* We don't need to consider type units here.
3353      This is only called for examining code, e.g. expand_line_sal.
3354      There can be an order of magnitude (or more) more type units
3355      than comp units, and we avoid them if we can.  */
3356
3357   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3358     {
3359       int j;
3360       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3361       struct quick_file_names *file_data;
3362
3363       /* We only need to look at symtabs not already expanded.  */
3364       if (per_cu->v.quick->symtab)
3365         continue;
3366
3367       file_data = dw2_get_file_names (per_cu);
3368       if (file_data == NULL)
3369         continue;
3370
3371       for (j = 0; j < file_data->num_file_names; ++j)
3372         {
3373           const char *this_fullname = file_data->file_names[j];
3374
3375           if (filename_cmp (this_fullname, fullname) == 0)
3376             {
3377               dw2_instantiate_symtab (per_cu);
3378               break;
3379             }
3380         }
3381     }
3382 }
3383
3384 /* A helper function for dw2_find_symbol_file that finds the primary
3385    file name for a given CU.  This is a die_reader_func.  */
3386
3387 static void
3388 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3389                                  const gdb_byte *info_ptr,
3390                                  struct die_info *comp_unit_die,
3391                                  int has_children,
3392                                  void *data)
3393 {
3394   const char **result_ptr = data;
3395   struct dwarf2_cu *cu = reader->cu;
3396   struct attribute *attr;
3397
3398   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3399   if (attr == NULL)
3400     *result_ptr = NULL;
3401   else
3402     *result_ptr = DW_STRING (attr);
3403 }
3404
3405 static const char *
3406 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3407 {
3408   struct dwarf2_per_cu_data *per_cu;
3409   offset_type *vec;
3410   const char *filename;
3411
3412   dw2_setup (objfile);
3413
3414   /* index_table is NULL if OBJF_READNOW.  */
3415   if (!dwarf2_per_objfile->index_table)
3416     {
3417       struct symtab *s;
3418
3419       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3420         {
3421           struct blockvector *bv = BLOCKVECTOR (s);
3422           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3423           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3424
3425           if (sym)
3426             {
3427               /* Only file extension of returned filename is recognized.  */
3428               return SYMBOL_SYMTAB (sym)->filename;
3429             }
3430         }
3431       return NULL;
3432     }
3433
3434   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3435                                  name, &vec))
3436     return NULL;
3437
3438   /* Note that this just looks at the very first one named NAME -- but
3439      actually we are looking for a function.  find_main_filename
3440      should be rewritten so that it doesn't require a custom hook.  It
3441      could just use the ordinary symbol tables.  */
3442   /* vec[0] is the length, which must always be >0.  */
3443   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3444
3445   if (per_cu->v.quick->symtab != NULL)
3446     {
3447       /* Only file extension of returned filename is recognized.  */
3448       return per_cu->v.quick->symtab->filename;
3449     }
3450
3451   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3452                            dw2_get_primary_filename_reader, &filename);
3453
3454   /* Only file extension of returned filename is recognized.  */
3455   return filename;
3456 }
3457
3458 static void
3459 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3460                           struct objfile *objfile, int global,
3461                           int (*callback) (struct block *,
3462                                            struct symbol *, void *),
3463                           void *data, symbol_compare_ftype *match,
3464                           symbol_compare_ftype *ordered_compare)
3465 {
3466   /* Currently unimplemented; used for Ada.  The function can be called if the
3467      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3468      does not look for non-Ada symbols this function should just return.  */
3469 }
3470
3471 static void
3472 dw2_expand_symtabs_matching
3473   (struct objfile *objfile,
3474    int (*file_matcher) (const char *, void *, int basenames),
3475    int (*name_matcher) (const char *, void *),
3476    enum search_domain kind,
3477    void *data)
3478 {
3479   int i;
3480   offset_type iter;
3481   struct mapped_index *index;
3482
3483   dw2_setup (objfile);
3484
3485   /* index_table is NULL if OBJF_READNOW.  */
3486   if (!dwarf2_per_objfile->index_table)
3487     return;
3488   index = dwarf2_per_objfile->index_table;
3489
3490   if (file_matcher != NULL)
3491     {
3492       struct cleanup *cleanup;
3493       htab_t visited_found, visited_not_found;
3494
3495       visited_found = htab_create_alloc (10,
3496                                          htab_hash_pointer, htab_eq_pointer,
3497                                          NULL, xcalloc, xfree);
3498       cleanup = make_cleanup_htab_delete (visited_found);
3499       visited_not_found = htab_create_alloc (10,
3500                                              htab_hash_pointer, htab_eq_pointer,
3501                                              NULL, xcalloc, xfree);
3502       make_cleanup_htab_delete (visited_not_found);
3503
3504       /* The rule is CUs specify all the files, including those used by
3505          any TU, so there's no need to scan TUs here.  */
3506
3507       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3508         {
3509           int j;
3510           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3511           struct quick_file_names *file_data;
3512           void **slot;
3513
3514           per_cu->v.quick->mark = 0;
3515
3516           /* We only need to look at symtabs not already expanded.  */
3517           if (per_cu->v.quick->symtab)
3518             continue;
3519
3520           file_data = dw2_get_file_names (per_cu);
3521           if (file_data == NULL)
3522             continue;
3523
3524           if (htab_find (visited_not_found, file_data) != NULL)
3525             continue;
3526           else if (htab_find (visited_found, file_data) != NULL)
3527             {
3528               per_cu->v.quick->mark = 1;
3529               continue;
3530             }
3531
3532           for (j = 0; j < file_data->num_file_names; ++j)
3533             {
3534               const char *this_real_name;
3535
3536               if (file_matcher (file_data->file_names[j], data, 0))
3537                 {
3538                   per_cu->v.quick->mark = 1;
3539                   break;
3540                 }
3541
3542               /* Before we invoke realpath, which can get expensive when many
3543                  files are involved, do a quick comparison of the basenames.  */
3544               if (!basenames_may_differ
3545                   && !file_matcher (lbasename (file_data->file_names[j]),
3546                                     data, 1))
3547                 continue;
3548
3549               this_real_name = dw2_get_real_path (objfile, file_data, j);
3550               if (file_matcher (this_real_name, data, 0))
3551                 {
3552                   per_cu->v.quick->mark = 1;
3553                   break;
3554                 }
3555             }
3556
3557           slot = htab_find_slot (per_cu->v.quick->mark
3558                                  ? visited_found
3559                                  : visited_not_found,
3560                                  file_data, INSERT);
3561           *slot = file_data;
3562         }
3563
3564       do_cleanups (cleanup);
3565     }
3566
3567   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3568     {
3569       offset_type idx = 2 * iter;
3570       const char *name;
3571       offset_type *vec, vec_len, vec_idx;
3572
3573       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3574         continue;
3575
3576       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3577
3578       if (! (*name_matcher) (name, data))
3579         continue;
3580
3581       /* The name was matched, now expand corresponding CUs that were
3582          marked.  */
3583       vec = (offset_type *) (index->constant_pool
3584                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3585       vec_len = MAYBE_SWAP (vec[0]);
3586       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3587         {
3588           struct dwarf2_per_cu_data *per_cu;
3589           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3590           gdb_index_symbol_kind symbol_kind =
3591             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3592           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3593
3594           /* Don't crash on bad data.  */
3595           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3596                            + dwarf2_per_objfile->n_type_units))
3597             continue;
3598
3599           /* Only check the symbol's kind if it has one.
3600              Indices prior to version 7 don't record it.  */
3601           if (index->version >= 7)
3602             {
3603               switch (kind)
3604                 {
3605                 case VARIABLES_DOMAIN:
3606                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3607                     continue;
3608                   break;
3609                 case FUNCTIONS_DOMAIN:
3610                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3611                     continue;
3612                   break;
3613                 case TYPES_DOMAIN:
3614                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3615                     continue;
3616                   break;
3617                 default:
3618                   break;
3619                 }
3620             }
3621
3622           per_cu = dw2_get_cu (cu_index);
3623           if (file_matcher == NULL || per_cu->v.quick->mark)
3624             dw2_instantiate_symtab (per_cu);
3625         }
3626     }
3627 }
3628
3629 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3630    symtab.  */
3631
3632 static struct symtab *
3633 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3634 {
3635   int i;
3636
3637   if (BLOCKVECTOR (symtab) != NULL
3638       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3639     return symtab;
3640
3641   if (symtab->includes == NULL)
3642     return NULL;
3643
3644   for (i = 0; symtab->includes[i]; ++i)
3645     {
3646       struct symtab *s = symtab->includes[i];
3647
3648       s = recursively_find_pc_sect_symtab (s, pc);
3649       if (s != NULL)
3650         return s;
3651     }
3652
3653   return NULL;
3654 }
3655
3656 static struct symtab *
3657 dw2_find_pc_sect_symtab (struct objfile *objfile,
3658                          struct minimal_symbol *msymbol,
3659                          CORE_ADDR pc,
3660                          struct obj_section *section,
3661                          int warn_if_readin)
3662 {
3663   struct dwarf2_per_cu_data *data;
3664   struct symtab *result;
3665
3666   dw2_setup (objfile);
3667
3668   if (!objfile->psymtabs_addrmap)
3669     return NULL;
3670
3671   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3672   if (!data)
3673     return NULL;
3674
3675   if (warn_if_readin && data->v.quick->symtab)
3676     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3677              paddress (get_objfile_arch (objfile), pc));
3678
3679   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3680   gdb_assert (result != NULL);
3681   return result;
3682 }
3683
3684 static void
3685 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3686                           void *data, int need_fullname)
3687 {
3688   int i;
3689   struct cleanup *cleanup;
3690   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3691                                       NULL, xcalloc, xfree);
3692
3693   cleanup = make_cleanup_htab_delete (visited);
3694   dw2_setup (objfile);
3695
3696   /* The rule is CUs specify all the files, including those used by
3697      any TU, so there's no need to scan TUs here.
3698      We can ignore file names coming from already-expanded CUs.  */
3699
3700   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3701     {
3702       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3703
3704       if (per_cu->v.quick->symtab)
3705         {
3706           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3707                                         INSERT);
3708
3709           *slot = per_cu->v.quick->file_names;
3710         }
3711     }
3712
3713   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3714     {
3715       int j;
3716       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3717       struct quick_file_names *file_data;
3718       void **slot;
3719
3720       /* We only need to look at symtabs not already expanded.  */
3721       if (per_cu->v.quick->symtab)
3722         continue;
3723
3724       file_data = dw2_get_file_names (per_cu);
3725       if (file_data == NULL)
3726         continue;
3727
3728       slot = htab_find_slot (visited, file_data, INSERT);
3729       if (*slot)
3730         {
3731           /* Already visited.  */
3732           continue;
3733         }
3734       *slot = file_data;
3735
3736       for (j = 0; j < file_data->num_file_names; ++j)
3737         {
3738           const char *this_real_name;
3739
3740           if (need_fullname)
3741             this_real_name = dw2_get_real_path (objfile, file_data, j);
3742           else
3743             this_real_name = NULL;
3744           (*fun) (file_data->file_names[j], this_real_name, data);
3745         }
3746     }
3747
3748   do_cleanups (cleanup);
3749 }
3750
3751 static int
3752 dw2_has_symbols (struct objfile *objfile)
3753 {
3754   return 1;
3755 }
3756
3757 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3758 {
3759   dw2_has_symbols,
3760   dw2_find_last_source_symtab,
3761   dw2_forget_cached_source_info,
3762   dw2_map_symtabs_matching_filename,
3763   dw2_lookup_symbol,
3764   dw2_print_stats,
3765   dw2_dump,
3766   dw2_relocate,
3767   dw2_expand_symtabs_for_function,
3768   dw2_expand_all_symtabs,
3769   dw2_expand_symtabs_with_fullname,
3770   dw2_find_symbol_file,
3771   dw2_map_matching_symbols,
3772   dw2_expand_symtabs_matching,
3773   dw2_find_pc_sect_symtab,
3774   dw2_map_symbol_filenames
3775 };
3776
3777 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3778    file will use psymtabs, or 1 if using the GNU index.  */
3779
3780 int
3781 dwarf2_initialize_objfile (struct objfile *objfile)
3782 {
3783   /* If we're about to read full symbols, don't bother with the
3784      indices.  In this case we also don't care if some other debug
3785      format is making psymtabs, because they are all about to be
3786      expanded anyway.  */
3787   if ((objfile->flags & OBJF_READNOW))
3788     {
3789       int i;
3790
3791       dwarf2_per_objfile->using_index = 1;
3792       create_all_comp_units (objfile);
3793       create_all_type_units (objfile);
3794       dwarf2_per_objfile->quick_file_names_table =
3795         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3796
3797       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3798                        + dwarf2_per_objfile->n_type_units); ++i)
3799         {
3800           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3801
3802           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3803                                             struct dwarf2_per_cu_quick_data);
3804         }
3805
3806       /* Return 1 so that gdb sees the "quick" functions.  However,
3807          these functions will be no-ops because we will have expanded
3808          all symtabs.  */
3809       return 1;
3810     }
3811
3812   if (dwarf2_read_index (objfile))
3813     return 1;
3814
3815   return 0;
3816 }
3817
3818 \f
3819
3820 /* Build a partial symbol table.  */
3821
3822 void
3823 dwarf2_build_psymtabs (struct objfile *objfile)
3824 {
3825   volatile struct gdb_exception except;
3826
3827   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3828     {
3829       init_psymbol_list (objfile, 1024);
3830     }
3831
3832   TRY_CATCH (except, RETURN_MASK_ERROR)
3833     {
3834       /* This isn't really ideal: all the data we allocate on the
3835          objfile's obstack is still uselessly kept around.  However,
3836          freeing it seems unsafe.  */
3837       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3838
3839       dwarf2_build_psymtabs_hard (objfile);
3840       discard_cleanups (cleanups);
3841     }
3842   if (except.reason < 0)
3843     exception_print (gdb_stderr, except);
3844 }
3845
3846 /* Return the total length of the CU described by HEADER.  */
3847
3848 static unsigned int
3849 get_cu_length (const struct comp_unit_head *header)
3850 {
3851   return header->initial_length_size + header->length;
3852 }
3853
3854 /* Return TRUE if OFFSET is within CU_HEADER.  */
3855
3856 static inline int
3857 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3858 {
3859   sect_offset bottom = { cu_header->offset.sect_off };
3860   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3861
3862   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3863 }
3864
3865 /* Find the base address of the compilation unit for range lists and
3866    location lists.  It will normally be specified by DW_AT_low_pc.
3867    In DWARF-3 draft 4, the base address could be overridden by
3868    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3869    compilation units with discontinuous ranges.  */
3870
3871 static void
3872 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3873 {
3874   struct attribute *attr;
3875
3876   cu->base_known = 0;
3877   cu->base_address = 0;
3878
3879   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3880   if (attr)
3881     {
3882       cu->base_address = DW_ADDR (attr);
3883       cu->base_known = 1;
3884     }
3885   else
3886     {
3887       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3888       if (attr)
3889         {
3890           cu->base_address = DW_ADDR (attr);
3891           cu->base_known = 1;
3892         }
3893     }
3894 }
3895
3896 /* Read in the comp unit header information from the debug_info at info_ptr.
3897    NOTE: This leaves members offset, first_die_offset to be filled in
3898    by the caller.  */
3899
3900 static const gdb_byte *
3901 read_comp_unit_head (struct comp_unit_head *cu_header,
3902                      const gdb_byte *info_ptr, bfd *abfd)
3903 {
3904   int signed_addr;
3905   unsigned int bytes_read;
3906
3907   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3908   cu_header->initial_length_size = bytes_read;
3909   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3910   info_ptr += bytes_read;
3911   cu_header->version = read_2_bytes (abfd, info_ptr);
3912   info_ptr += 2;
3913   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3914                                              &bytes_read);
3915   info_ptr += bytes_read;
3916   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3917   info_ptr += 1;
3918   signed_addr = bfd_get_sign_extend_vma (abfd);
3919   if (signed_addr < 0)
3920     internal_error (__FILE__, __LINE__,
3921                     _("read_comp_unit_head: dwarf from non elf file"));
3922   cu_header->signed_addr_p = signed_addr;
3923
3924   return info_ptr;
3925 }
3926
3927 /* Helper function that returns the proper abbrev section for
3928    THIS_CU.  */
3929
3930 static struct dwarf2_section_info *
3931 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3932 {
3933   struct dwarf2_section_info *abbrev;
3934
3935   if (this_cu->is_dwz)
3936     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3937   else
3938     abbrev = &dwarf2_per_objfile->abbrev;
3939
3940   return abbrev;
3941 }
3942
3943 /* Subroutine of read_and_check_comp_unit_head and
3944    read_and_check_type_unit_head to simplify them.
3945    Perform various error checking on the header.  */
3946
3947 static void
3948 error_check_comp_unit_head (struct comp_unit_head *header,
3949                             struct dwarf2_section_info *section,
3950                             struct dwarf2_section_info *abbrev_section)
3951 {
3952   bfd *abfd = section->asection->owner;
3953   const char *filename = bfd_get_filename (abfd);
3954
3955   if (header->version != 2 && header->version != 3 && header->version != 4)
3956     error (_("Dwarf Error: wrong version in compilation unit header "
3957            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3958            filename);
3959
3960   if (header->abbrev_offset.sect_off
3961       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3962     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3963            "(offset 0x%lx + 6) [in module %s]"),
3964            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3965            filename);
3966
3967   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3968      avoid potential 32-bit overflow.  */
3969   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3970       > section->size)
3971     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3972            "(offset 0x%lx + 0) [in module %s]"),
3973            (long) header->length, (long) header->offset.sect_off,
3974            filename);
3975 }
3976
3977 /* Read in a CU/TU header and perform some basic error checking.
3978    The contents of the header are stored in HEADER.
3979    The result is a pointer to the start of the first DIE.  */
3980
3981 static const gdb_byte *
3982 read_and_check_comp_unit_head (struct comp_unit_head *header,
3983                                struct dwarf2_section_info *section,
3984                                struct dwarf2_section_info *abbrev_section,
3985                                const gdb_byte *info_ptr,
3986                                int is_debug_types_section)
3987 {
3988   const gdb_byte *beg_of_comp_unit = info_ptr;
3989   bfd *abfd = section->asection->owner;
3990
3991   header->offset.sect_off = beg_of_comp_unit - section->buffer;
3992
3993   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
3994
3995   /* If we're reading a type unit, skip over the signature and
3996      type_offset fields.  */
3997   if (is_debug_types_section)
3998     info_ptr += 8 /*signature*/ + header->offset_size;
3999
4000   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4001
4002   error_check_comp_unit_head (header, section, abbrev_section);
4003
4004   return info_ptr;
4005 }
4006
4007 /* Read in the types comp unit header information from .debug_types entry at
4008    types_ptr.  The result is a pointer to one past the end of the header.  */
4009
4010 static const gdb_byte *
4011 read_and_check_type_unit_head (struct comp_unit_head *header,
4012                                struct dwarf2_section_info *section,
4013                                struct dwarf2_section_info *abbrev_section,
4014                                const gdb_byte *info_ptr,
4015                                ULONGEST *signature,
4016                                cu_offset *type_offset_in_tu)
4017 {
4018   const gdb_byte *beg_of_comp_unit = info_ptr;
4019   bfd *abfd = section->asection->owner;
4020
4021   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4022
4023   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4024
4025   /* If we're reading a type unit, skip over the signature and
4026      type_offset fields.  */
4027   if (signature != NULL)
4028     *signature = read_8_bytes (abfd, info_ptr);
4029   info_ptr += 8;
4030   if (type_offset_in_tu != NULL)
4031     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4032                                                header->offset_size);
4033   info_ptr += header->offset_size;
4034
4035   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4036
4037   error_check_comp_unit_head (header, section, abbrev_section);
4038
4039   return info_ptr;
4040 }
4041
4042 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4043
4044 static sect_offset
4045 read_abbrev_offset (struct dwarf2_section_info *section,
4046                     sect_offset offset)
4047 {
4048   bfd *abfd = section->asection->owner;
4049   const gdb_byte *info_ptr;
4050   unsigned int length, initial_length_size, offset_size;
4051   sect_offset abbrev_offset;
4052
4053   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4054   info_ptr = section->buffer + offset.sect_off;
4055   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4056   offset_size = initial_length_size == 4 ? 4 : 8;
4057   info_ptr += initial_length_size + 2 /*version*/;
4058   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4059   return abbrev_offset;
4060 }
4061
4062 /* Allocate a new partial symtab for file named NAME and mark this new
4063    partial symtab as being an include of PST.  */
4064
4065 static void
4066 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4067                                struct objfile *objfile)
4068 {
4069   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4070
4071   if (!IS_ABSOLUTE_PATH (subpst->filename))
4072     {
4073       /* It shares objfile->objfile_obstack.  */
4074       subpst->dirname = pst->dirname;
4075     }
4076
4077   subpst->section_offsets = pst->section_offsets;
4078   subpst->textlow = 0;
4079   subpst->texthigh = 0;
4080
4081   subpst->dependencies = (struct partial_symtab **)
4082     obstack_alloc (&objfile->objfile_obstack,
4083                    sizeof (struct partial_symtab *));
4084   subpst->dependencies[0] = pst;
4085   subpst->number_of_dependencies = 1;
4086
4087   subpst->globals_offset = 0;
4088   subpst->n_global_syms = 0;
4089   subpst->statics_offset = 0;
4090   subpst->n_static_syms = 0;
4091   subpst->symtab = NULL;
4092   subpst->read_symtab = pst->read_symtab;
4093   subpst->readin = 0;
4094
4095   /* No private part is necessary for include psymtabs.  This property
4096      can be used to differentiate between such include psymtabs and
4097      the regular ones.  */
4098   subpst->read_symtab_private = NULL;
4099 }
4100
4101 /* Read the Line Number Program data and extract the list of files
4102    included by the source file represented by PST.  Build an include
4103    partial symtab for each of these included files.  */
4104
4105 static void
4106 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4107                                struct die_info *die,
4108                                struct partial_symtab *pst)
4109 {
4110   struct line_header *lh = NULL;
4111   struct attribute *attr;
4112
4113   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4114   if (attr)
4115     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4116   if (lh == NULL)
4117     return;  /* No linetable, so no includes.  */
4118
4119   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4120   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4121
4122   free_line_header (lh);
4123 }
4124
4125 static hashval_t
4126 hash_signatured_type (const void *item)
4127 {
4128   const struct signatured_type *sig_type = item;
4129
4130   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4131   return sig_type->signature;
4132 }
4133
4134 static int
4135 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4136 {
4137   const struct signatured_type *lhs = item_lhs;
4138   const struct signatured_type *rhs = item_rhs;
4139
4140   return lhs->signature == rhs->signature;
4141 }
4142
4143 /* Allocate a hash table for signatured types.  */
4144
4145 static htab_t
4146 allocate_signatured_type_table (struct objfile *objfile)
4147 {
4148   return htab_create_alloc_ex (41,
4149                                hash_signatured_type,
4150                                eq_signatured_type,
4151                                NULL,
4152                                &objfile->objfile_obstack,
4153                                hashtab_obstack_allocate,
4154                                dummy_obstack_deallocate);
4155 }
4156
4157 /* A helper function to add a signatured type CU to a table.  */
4158
4159 static int
4160 add_signatured_type_cu_to_table (void **slot, void *datum)
4161 {
4162   struct signatured_type *sigt = *slot;
4163   struct signatured_type ***datap = datum;
4164
4165   **datap = sigt;
4166   ++*datap;
4167
4168   return 1;
4169 }
4170
4171 /* Create the hash table of all entries in the .debug_types
4172    (or .debug_types.dwo) section(s).
4173    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4174    otherwise it is NULL.
4175
4176    The result is a pointer to the hash table or NULL if there are no types.
4177
4178    Note: This function processes DWO files only, not DWP files.  */
4179
4180 static htab_t
4181 create_debug_types_hash_table (struct dwo_file *dwo_file,
4182                                VEC (dwarf2_section_info_def) *types)
4183 {
4184   struct objfile *objfile = dwarf2_per_objfile->objfile;
4185   htab_t types_htab = NULL;
4186   int ix;
4187   struct dwarf2_section_info *section;
4188   struct dwarf2_section_info *abbrev_section;
4189
4190   if (VEC_empty (dwarf2_section_info_def, types))
4191     return NULL;
4192
4193   abbrev_section = (dwo_file != NULL
4194                     ? &dwo_file->sections.abbrev
4195                     : &dwarf2_per_objfile->abbrev);
4196
4197   if (dwarf2_read_debug)
4198     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4199                         dwo_file ? ".dwo" : "",
4200                         bfd_get_filename (abbrev_section->asection->owner));
4201
4202   for (ix = 0;
4203        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4204        ++ix)
4205     {
4206       bfd *abfd;
4207       const gdb_byte *info_ptr, *end_ptr;
4208       struct dwarf2_section_info *abbrev_section;
4209
4210       dwarf2_read_section (objfile, section);
4211       info_ptr = section->buffer;
4212
4213       if (info_ptr == NULL)
4214         continue;
4215
4216       /* We can't set abfd until now because the section may be empty or
4217          not present, in which case section->asection will be NULL.  */
4218       abfd = section->asection->owner;
4219
4220       if (dwo_file)
4221         abbrev_section = &dwo_file->sections.abbrev;
4222       else
4223         abbrev_section = &dwarf2_per_objfile->abbrev;
4224
4225       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4226          because we don't need to read any dies: the signature is in the
4227          header.  */
4228
4229       end_ptr = info_ptr + section->size;
4230       while (info_ptr < end_ptr)
4231         {
4232           sect_offset offset;
4233           cu_offset type_offset_in_tu;
4234           ULONGEST signature;
4235           struct signatured_type *sig_type;
4236           struct dwo_unit *dwo_tu;
4237           void **slot;
4238           const gdb_byte *ptr = info_ptr;
4239           struct comp_unit_head header;
4240           unsigned int length;
4241
4242           offset.sect_off = ptr - section->buffer;
4243
4244           /* We need to read the type's signature in order to build the hash
4245              table, but we don't need anything else just yet.  */
4246
4247           ptr = read_and_check_type_unit_head (&header, section,
4248                                                abbrev_section, ptr,
4249                                                &signature, &type_offset_in_tu);
4250
4251           length = get_cu_length (&header);
4252
4253           /* Skip dummy type units.  */
4254           if (ptr >= info_ptr + length
4255               || peek_abbrev_code (abfd, ptr) == 0)
4256             {
4257               info_ptr += length;
4258               continue;
4259             }
4260
4261           if (types_htab == NULL)
4262             {
4263               if (dwo_file)
4264                 types_htab = allocate_dwo_unit_table (objfile);
4265               else
4266                 types_htab = allocate_signatured_type_table (objfile);
4267             }
4268
4269           if (dwo_file)
4270             {
4271               sig_type = NULL;
4272               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4273                                        struct dwo_unit);
4274               dwo_tu->dwo_file = dwo_file;
4275               dwo_tu->signature = signature;
4276               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4277               dwo_tu->section = section;
4278               dwo_tu->offset = offset;
4279               dwo_tu->length = length;
4280             }
4281           else
4282             {
4283               /* N.B.: type_offset is not usable if this type uses a DWO file.
4284                  The real type_offset is in the DWO file.  */
4285               dwo_tu = NULL;
4286               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4287                                          struct signatured_type);
4288               sig_type->signature = signature;
4289               sig_type->type_offset_in_tu = type_offset_in_tu;
4290               sig_type->per_cu.objfile = objfile;
4291               sig_type->per_cu.is_debug_types = 1;
4292               sig_type->per_cu.section = section;
4293               sig_type->per_cu.offset = offset;
4294               sig_type->per_cu.length = length;
4295             }
4296
4297           slot = htab_find_slot (types_htab,
4298                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4299                                  INSERT);
4300           gdb_assert (slot != NULL);
4301           if (*slot != NULL)
4302             {
4303               sect_offset dup_offset;
4304
4305               if (dwo_file)
4306                 {
4307                   const struct dwo_unit *dup_tu = *slot;
4308
4309                   dup_offset = dup_tu->offset;
4310                 }
4311               else
4312                 {
4313                   const struct signatured_type *dup_tu = *slot;
4314
4315                   dup_offset = dup_tu->per_cu.offset;
4316                 }
4317
4318               complaint (&symfile_complaints,
4319                          _("debug type entry at offset 0x%x is duplicate to"
4320                            " the entry at offset 0x%x, signature 0x%s"),
4321                          offset.sect_off, dup_offset.sect_off,
4322                          phex (signature, sizeof (signature)));
4323             }
4324           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4325
4326           if (dwarf2_read_debug)
4327             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4328                                 offset.sect_off,
4329                                 phex (signature, sizeof (signature)));
4330
4331           info_ptr += length;
4332         }
4333     }
4334
4335   return types_htab;
4336 }
4337
4338 /* Create the hash table of all entries in the .debug_types section,
4339    and initialize all_type_units.
4340    The result is zero if there is an error (e.g. missing .debug_types section),
4341    otherwise non-zero.  */
4342
4343 static int
4344 create_all_type_units (struct objfile *objfile)
4345 {
4346   htab_t types_htab;
4347   struct signatured_type **iter;
4348
4349   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4350   if (types_htab == NULL)
4351     {
4352       dwarf2_per_objfile->signatured_types = NULL;
4353       return 0;
4354     }
4355
4356   dwarf2_per_objfile->signatured_types = types_htab;
4357
4358   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4359   dwarf2_per_objfile->all_type_units
4360     = obstack_alloc (&objfile->objfile_obstack,
4361                      dwarf2_per_objfile->n_type_units
4362                      * sizeof (struct signatured_type *));
4363   iter = &dwarf2_per_objfile->all_type_units[0];
4364   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4365   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4366               == dwarf2_per_objfile->n_type_units);
4367
4368   return 1;
4369 }
4370
4371 /* Lookup a signature based type for DW_FORM_ref_sig8.
4372    Returns NULL if signature SIG is not present in the table.
4373    It is up to the caller to complain about this.  */
4374
4375 static struct signatured_type *
4376 lookup_signatured_type (ULONGEST sig)
4377 {
4378   struct signatured_type find_entry, *entry;
4379
4380   if (dwarf2_per_objfile->signatured_types == NULL)
4381     return NULL;
4382   find_entry.signature = sig;
4383   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4384   return entry;
4385 }
4386 \f
4387 /* Low level DIE reading support.  */
4388
4389 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4390
4391 static void
4392 init_cu_die_reader (struct die_reader_specs *reader,
4393                     struct dwarf2_cu *cu,
4394                     struct dwarf2_section_info *section,
4395                     struct dwo_file *dwo_file)
4396 {
4397   gdb_assert (section->readin && section->buffer != NULL);
4398   reader->abfd = section->asection->owner;
4399   reader->cu = cu;
4400   reader->dwo_file = dwo_file;
4401   reader->die_section = section;
4402   reader->buffer = section->buffer;
4403   reader->buffer_end = section->buffer + section->size;
4404 }
4405
4406 /* Subroutine of init_cutu_and_read_dies to simplify it.
4407    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4408    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4409    already.
4410
4411    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4412    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4413    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4414    are filled in with the info of the DIE from the DWO file.
4415    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4416    provided an abbrev table to use.
4417    The result is non-zero if a valid (non-dummy) DIE was found.  */
4418
4419 static int
4420 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4421                         struct dwo_unit *dwo_unit,
4422                         int abbrev_table_provided,
4423                         struct die_info *stub_comp_unit_die,
4424                         struct die_reader_specs *result_reader,
4425                         const gdb_byte **result_info_ptr,
4426                         struct die_info **result_comp_unit_die,
4427                         int *result_has_children)
4428 {
4429   struct objfile *objfile = dwarf2_per_objfile->objfile;
4430   struct dwarf2_cu *cu = this_cu->cu;
4431   struct dwarf2_section_info *section;
4432   bfd *abfd;
4433   const gdb_byte *begin_info_ptr, *info_ptr;
4434   const char *comp_dir_string;
4435   ULONGEST signature; /* Or dwo_id.  */
4436   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4437   int i,num_extra_attrs;
4438   struct dwarf2_section_info *dwo_abbrev_section;
4439   struct attribute *attr;
4440   struct die_info *comp_unit_die;
4441
4442   /* These attributes aren't processed until later:
4443      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4444      However, the attribute is found in the stub which we won't have later.
4445      In order to not impose this complication on the rest of the code,
4446      we read them here and copy them to the DWO CU/TU die.  */
4447
4448   stmt_list = NULL;
4449   low_pc = NULL;
4450   high_pc = NULL;
4451   ranges = NULL;
4452   comp_dir = NULL;
4453
4454   if (stub_comp_unit_die != NULL)
4455     {
4456       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4457          DWO file.  */
4458       if (! this_cu->is_debug_types)
4459         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4460       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4461       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4462       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4463       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4464
4465       /* There should be a DW_AT_addr_base attribute here (if needed).
4466          We need the value before we can process DW_FORM_GNU_addr_index.  */
4467       cu->addr_base = 0;
4468       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4469       if (attr)
4470         cu->addr_base = DW_UNSND (attr);
4471
4472       /* There should be a DW_AT_ranges_base attribute here (if needed).
4473          We need the value before we can process DW_AT_ranges.  */
4474       cu->ranges_base = 0;
4475       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4476       if (attr)
4477         cu->ranges_base = DW_UNSND (attr);
4478     }
4479
4480   /* Set up for reading the DWO CU/TU.  */
4481   cu->dwo_unit = dwo_unit;
4482   section = dwo_unit->section;
4483   dwarf2_read_section (objfile, section);
4484   abfd = section->asection->owner;
4485   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4486   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4487   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4488
4489   if (this_cu->is_debug_types)
4490     {
4491       ULONGEST header_signature;
4492       cu_offset type_offset_in_tu;
4493       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4494
4495       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4496                                                 dwo_abbrev_section,
4497                                                 info_ptr,
4498                                                 &header_signature,
4499                                                 &type_offset_in_tu);
4500       gdb_assert (sig_type->signature == header_signature);
4501       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4502       /* For DWOs coming from DWP files, we don't know the CU length
4503          nor the type's offset in the TU until now.  */
4504       dwo_unit->length = get_cu_length (&cu->header);
4505       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4506
4507       /* Establish the type offset that can be used to lookup the type.
4508          For DWO files, we don't know it until now.  */
4509       sig_type->type_offset_in_section.sect_off =
4510         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4511     }
4512   else
4513     {
4514       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4515                                                 dwo_abbrev_section,
4516                                                 info_ptr, 0);
4517       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4518       /* For DWOs coming from DWP files, we don't know the CU length
4519          until now.  */
4520       dwo_unit->length = get_cu_length (&cu->header);
4521     }
4522
4523   /* Replace the CU's original abbrev table with the DWO's.
4524      Reminder: We can't read the abbrev table until we've read the header.  */
4525   if (abbrev_table_provided)
4526     {
4527       /* Don't free the provided abbrev table, the caller of
4528          init_cutu_and_read_dies owns it.  */
4529       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4530       /* Ensure the DWO abbrev table gets freed.  */
4531       make_cleanup (dwarf2_free_abbrev_table, cu);
4532     }
4533   else
4534     {
4535       dwarf2_free_abbrev_table (cu);
4536       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4537       /* Leave any existing abbrev table cleanup as is.  */
4538     }
4539
4540   /* Read in the die, but leave space to copy over the attributes
4541      from the stub.  This has the benefit of simplifying the rest of
4542      the code - all the work to maintain the illusion of a single
4543      DW_TAG_{compile,type}_unit DIE is done here.  */
4544   num_extra_attrs = ((stmt_list != NULL)
4545                      + (low_pc != NULL)
4546                      + (high_pc != NULL)
4547                      + (ranges != NULL)
4548                      + (comp_dir != NULL));
4549   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
4550                               result_has_children, num_extra_attrs);
4551
4552   /* Copy over the attributes from the stub to the DIE we just read in.  */
4553   comp_unit_die = *result_comp_unit_die;
4554   i = comp_unit_die->num_attrs;
4555   if (stmt_list != NULL)
4556     comp_unit_die->attrs[i++] = *stmt_list;
4557   if (low_pc != NULL)
4558     comp_unit_die->attrs[i++] = *low_pc;
4559   if (high_pc != NULL)
4560     comp_unit_die->attrs[i++] = *high_pc;
4561   if (ranges != NULL)
4562     comp_unit_die->attrs[i++] = *ranges;
4563   if (comp_dir != NULL)
4564     comp_unit_die->attrs[i++] = *comp_dir;
4565   comp_unit_die->num_attrs += num_extra_attrs;
4566
4567   if (dwarf2_die_debug)
4568     {
4569       fprintf_unfiltered (gdb_stdlog,
4570                           "Read die from %s@0x%x of %s:\n",
4571                           bfd_section_name (abfd, section->asection),
4572                           (unsigned) (begin_info_ptr - section->buffer),
4573                           bfd_get_filename (abfd));
4574       dump_die (comp_unit_die, dwarf2_die_debug);
4575     }
4576
4577   /* Skip dummy compilation units.  */
4578   if (info_ptr >= begin_info_ptr + dwo_unit->length
4579       || peek_abbrev_code (abfd, info_ptr) == 0)
4580     return 0;
4581
4582   *result_info_ptr = info_ptr;
4583   return 1;
4584 }
4585
4586 /* Subroutine of init_cutu_and_read_dies to simplify it.
4587    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
4588    If the specified DWO unit cannot be found an error is thrown.  */
4589
4590 static struct dwo_unit *
4591 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
4592                  struct die_info *comp_unit_die)
4593 {
4594   struct dwarf2_cu *cu = this_cu->cu;
4595   struct attribute *attr;
4596   ULONGEST signature;
4597   struct dwo_unit *dwo_unit;
4598   const char *comp_dir, *dwo_name;
4599
4600   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
4601   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4602   gdb_assert (attr != NULL);
4603   dwo_name = DW_STRING (attr);
4604   comp_dir = NULL;
4605   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4606   if (attr)
4607     comp_dir = DW_STRING (attr);
4608
4609   if (this_cu->is_debug_types)
4610     {
4611       struct signatured_type *sig_type;
4612
4613       /* Since this_cu is the first member of struct signatured_type,
4614          we can go from a pointer to one to a pointer to the other.  */
4615       sig_type = (struct signatured_type *) this_cu;
4616       signature = sig_type->signature;
4617       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
4618     }
4619   else
4620     {
4621       struct attribute *attr;
4622
4623       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4624       if (! attr)
4625         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
4626                  " [in module %s]"),
4627                dwo_name, this_cu->objfile->name);
4628       signature = DW_UNSND (attr);
4629       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
4630                                        signature);
4631     }
4632
4633   if (dwo_unit == NULL)
4634     {
4635       error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4636                " with ID %s [in module %s]"),
4637              this_cu->offset.sect_off,
4638              phex (signature, sizeof (signature)),
4639              this_cu->objfile->name);
4640     }
4641
4642   return dwo_unit;
4643 }
4644
4645 /* Initialize a CU (or TU) and read its DIEs.
4646    If the CU defers to a DWO file, read the DWO file as well.
4647
4648    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4649    Otherwise the table specified in the comp unit header is read in and used.
4650    This is an optimization for when we already have the abbrev table.
4651
4652    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4653    Otherwise, a new CU is allocated with xmalloc.
4654
4655    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4656    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4657
4658    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4659    linker) then DIE_READER_FUNC will not get called.  */
4660
4661 static void
4662 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4663                          struct abbrev_table *abbrev_table,
4664                          int use_existing_cu, int keep,
4665                          die_reader_func_ftype *die_reader_func,
4666                          void *data)
4667 {
4668   struct objfile *objfile = dwarf2_per_objfile->objfile;
4669   struct dwarf2_section_info *section = this_cu->section;
4670   bfd *abfd = section->asection->owner;
4671   struct dwarf2_cu *cu;
4672   const gdb_byte *begin_info_ptr, *info_ptr;
4673   struct die_reader_specs reader;
4674   struct die_info *comp_unit_die;
4675   int has_children;
4676   struct attribute *attr;
4677   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4678   struct signatured_type *sig_type = NULL;
4679   struct dwarf2_section_info *abbrev_section;
4680   /* Non-zero if CU currently points to a DWO file and we need to
4681      reread it.  When this happens we need to reread the skeleton die
4682      before we can reread the DWO file.  */
4683   int rereading_dwo_cu = 0;
4684
4685   if (dwarf2_die_debug)
4686     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4687                         this_cu->is_debug_types ? "type" : "comp",
4688                         this_cu->offset.sect_off);
4689
4690   if (use_existing_cu)
4691     gdb_assert (keep);
4692
4693   cleanups = make_cleanup (null_cleanup, NULL);
4694
4695   /* This is cheap if the section is already read in.  */
4696   dwarf2_read_section (objfile, section);
4697
4698   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4699
4700   abbrev_section = get_abbrev_section_for_cu (this_cu);
4701
4702   if (use_existing_cu && this_cu->cu != NULL)
4703     {
4704       cu = this_cu->cu;
4705
4706       /* If this CU is from a DWO file we need to start over, we need to
4707          refetch the attributes from the skeleton CU.
4708          This could be optimized by retrieving those attributes from when we
4709          were here the first time: the previous comp_unit_die was stored in
4710          comp_unit_obstack.  But there's no data yet that we need this
4711          optimization.  */
4712       if (cu->dwo_unit != NULL)
4713         rereading_dwo_cu = 1;
4714     }
4715   else
4716     {
4717       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4718       gdb_assert (this_cu->cu == NULL);
4719
4720       cu = xmalloc (sizeof (*cu));
4721       init_one_comp_unit (cu, this_cu);
4722
4723       /* If an error occurs while loading, release our storage.  */
4724       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4725     }
4726
4727   /* Get the header.  */
4728   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4729     {
4730       /* We already have the header, there's no need to read it in again.  */
4731       info_ptr += cu->header.first_die_offset.cu_off;
4732     }
4733   else
4734     {
4735       if (this_cu->is_debug_types)
4736         {
4737           ULONGEST signature;
4738           cu_offset type_offset_in_tu;
4739
4740           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4741                                                     abbrev_section, info_ptr,
4742                                                     &signature,
4743                                                     &type_offset_in_tu);
4744
4745           /* Since per_cu is the first member of struct signatured_type,
4746              we can go from a pointer to one to a pointer to the other.  */
4747           sig_type = (struct signatured_type *) this_cu;
4748           gdb_assert (sig_type->signature == signature);
4749           gdb_assert (sig_type->type_offset_in_tu.cu_off
4750                       == type_offset_in_tu.cu_off);
4751           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4752
4753           /* LENGTH has not been set yet for type units if we're
4754              using .gdb_index.  */
4755           this_cu->length = get_cu_length (&cu->header);
4756
4757           /* Establish the type offset that can be used to lookup the type.  */
4758           sig_type->type_offset_in_section.sect_off =
4759             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4760         }
4761       else
4762         {
4763           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4764                                                     abbrev_section,
4765                                                     info_ptr, 0);
4766
4767           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4768           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4769         }
4770     }
4771
4772   /* Skip dummy compilation units.  */
4773   if (info_ptr >= begin_info_ptr + this_cu->length
4774       || peek_abbrev_code (abfd, info_ptr) == 0)
4775     {
4776       do_cleanups (cleanups);
4777       return;
4778     }
4779
4780   /* If we don't have them yet, read the abbrevs for this compilation unit.
4781      And if we need to read them now, make sure they're freed when we're
4782      done.  Note that it's important that if the CU had an abbrev table
4783      on entry we don't free it when we're done: Somewhere up the call stack
4784      it may be in use.  */
4785   if (abbrev_table != NULL)
4786     {
4787       gdb_assert (cu->abbrev_table == NULL);
4788       gdb_assert (cu->header.abbrev_offset.sect_off
4789                   == abbrev_table->offset.sect_off);
4790       cu->abbrev_table = abbrev_table;
4791     }
4792   else if (cu->abbrev_table == NULL)
4793     {
4794       dwarf2_read_abbrevs (cu, abbrev_section);
4795       make_cleanup (dwarf2_free_abbrev_table, cu);
4796     }
4797   else if (rereading_dwo_cu)
4798     {
4799       dwarf2_free_abbrev_table (cu);
4800       dwarf2_read_abbrevs (cu, abbrev_section);
4801     }
4802
4803   /* Read the top level CU/TU die.  */
4804   init_cu_die_reader (&reader, cu, section, NULL);
4805   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4806
4807   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
4808      from the DWO file.
4809      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
4810      DWO CU, that this test will fail (the attribute will not be present).  */
4811   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4812   if (attr)
4813     {
4814       struct dwo_unit *dwo_unit;
4815       struct die_info *dwo_comp_unit_die;
4816
4817       if (has_children)
4818         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4819                  " has children (offset 0x%x) [in module %s]"),
4820                this_cu->offset.sect_off, bfd_get_filename (abfd));
4821       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
4822       if (read_cutu_die_from_dwo (this_cu, dwo_unit,
4823                                   abbrev_table != NULL,
4824                                   comp_unit_die,
4825                                   &reader, &info_ptr,
4826                                   &dwo_comp_unit_die, &has_children) == 0)
4827         {
4828           /* Dummy die.  */
4829           do_cleanups (cleanups);
4830           return;
4831         }
4832       comp_unit_die = dwo_comp_unit_die;
4833     }
4834
4835   /* All of the above is setup for this call.  Yikes.  */
4836   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4837
4838   /* Done, clean up.  */
4839   if (free_cu_cleanup != NULL)
4840     {
4841       if (keep)
4842         {
4843           /* We've successfully allocated this compilation unit.  Let our
4844              caller clean it up when finished with it.  */
4845           discard_cleanups (free_cu_cleanup);
4846
4847           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4848              So we have to manually free the abbrev table.  */
4849           dwarf2_free_abbrev_table (cu);
4850
4851           /* Link this CU into read_in_chain.  */
4852           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4853           dwarf2_per_objfile->read_in_chain = this_cu;
4854         }
4855       else
4856         do_cleanups (free_cu_cleanup);
4857     }
4858
4859   do_cleanups (cleanups);
4860 }
4861
4862 /* Read CU/TU THIS_CU in section SECTION,
4863    but do not follow DW_AT_GNU_dwo_name if present.
4864    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4865    to have already done the lookup to find the DWO/DWP file).
4866
4867    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4868    THIS_CU->is_debug_types, but nothing else.
4869
4870    We fill in THIS_CU->length.
4871
4872    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4873    linker) then DIE_READER_FUNC will not get called.
4874
4875    THIS_CU->cu is always freed when done.
4876    This is done in order to not leave THIS_CU->cu in a state where we have
4877    to care whether it refers to the "main" CU or the DWO CU.  */
4878
4879 static void
4880 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4881                                    struct dwarf2_section_info *abbrev_section,
4882                                    struct dwo_file *dwo_file,
4883                                    die_reader_func_ftype *die_reader_func,
4884                                    void *data)
4885 {
4886   struct objfile *objfile = dwarf2_per_objfile->objfile;
4887   struct dwarf2_section_info *section = this_cu->section;
4888   bfd *abfd = section->asection->owner;
4889   struct dwarf2_cu cu;
4890   const gdb_byte *begin_info_ptr, *info_ptr;
4891   struct die_reader_specs reader;
4892   struct cleanup *cleanups;
4893   struct die_info *comp_unit_die;
4894   int has_children;
4895
4896   if (dwarf2_die_debug)
4897     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4898                         this_cu->is_debug_types ? "type" : "comp",
4899                         this_cu->offset.sect_off);
4900
4901   gdb_assert (this_cu->cu == NULL);
4902
4903   /* This is cheap if the section is already read in.  */
4904   dwarf2_read_section (objfile, section);
4905
4906   init_one_comp_unit (&cu, this_cu);
4907
4908   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4909
4910   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4911   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4912                                             abbrev_section, info_ptr,
4913                                             this_cu->is_debug_types);
4914
4915   this_cu->length = get_cu_length (&cu.header);
4916
4917   /* Skip dummy compilation units.  */
4918   if (info_ptr >= begin_info_ptr + this_cu->length
4919       || peek_abbrev_code (abfd, info_ptr) == 0)
4920     {
4921       do_cleanups (cleanups);
4922       return;
4923     }
4924
4925   dwarf2_read_abbrevs (&cu, abbrev_section);
4926   make_cleanup (dwarf2_free_abbrev_table, &cu);
4927
4928   init_cu_die_reader (&reader, &cu, section, dwo_file);
4929   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4930
4931   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4932
4933   do_cleanups (cleanups);
4934 }
4935
4936 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4937    does not lookup the specified DWO file.
4938    This cannot be used to read DWO files.
4939
4940    THIS_CU->cu is always freed when done.
4941    This is done in order to not leave THIS_CU->cu in a state where we have
4942    to care whether it refers to the "main" CU or the DWO CU.
4943    We can revisit this if the data shows there's a performance issue.  */
4944
4945 static void
4946 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4947                                 die_reader_func_ftype *die_reader_func,
4948                                 void *data)
4949 {
4950   init_cutu_and_read_dies_no_follow (this_cu,
4951                                      get_abbrev_section_for_cu (this_cu),
4952                                      NULL,
4953                                      die_reader_func, data);
4954 }
4955 \f
4956 /* Type Unit Groups.
4957
4958    Type Unit Groups are a way to collapse the set of all TUs (type units) into
4959    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
4960    so that all types coming from the same compilation (.o file) are grouped
4961    together.  A future step could be to put the types in the same symtab as
4962    the CU the types ultimately came from.  */
4963
4964 static hashval_t
4965 hash_type_unit_group (const void *item)
4966 {
4967   const struct type_unit_group *tu_group = item;
4968
4969   return hash_stmt_list_entry (&tu_group->hash);
4970 }
4971
4972 static int
4973 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
4974 {
4975   const struct type_unit_group *lhs = item_lhs;
4976   const struct type_unit_group *rhs = item_rhs;
4977
4978   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
4979 }
4980
4981 /* Allocate a hash table for type unit groups.  */
4982
4983 static htab_t
4984 allocate_type_unit_groups_table (void)
4985 {
4986   return htab_create_alloc_ex (3,
4987                                hash_type_unit_group,
4988                                eq_type_unit_group,
4989                                NULL,
4990                                &dwarf2_per_objfile->objfile->objfile_obstack,
4991                                hashtab_obstack_allocate,
4992                                dummy_obstack_deallocate);
4993 }
4994
4995 /* Type units that don't have DW_AT_stmt_list are grouped into their own
4996    partial symtabs.  We combine several TUs per psymtab to not let the size
4997    of any one psymtab grow too big.  */
4998 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
4999 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5000
5001 /* Helper routine for get_type_unit_group.
5002    Create the type_unit_group object used to hold one or more TUs.  */
5003
5004 static struct type_unit_group *
5005 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5006 {
5007   struct objfile *objfile = dwarf2_per_objfile->objfile;
5008   struct dwarf2_per_cu_data *per_cu;
5009   struct type_unit_group *tu_group;
5010
5011   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5012                              struct type_unit_group);
5013   per_cu = &tu_group->per_cu;
5014   per_cu->objfile = objfile;
5015
5016   if (dwarf2_per_objfile->using_index)
5017     {
5018       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5019                                         struct dwarf2_per_cu_quick_data);
5020     }
5021   else
5022     {
5023       unsigned int line_offset = line_offset_struct.sect_off;
5024       struct partial_symtab *pst;
5025       char *name;
5026
5027       /* Give the symtab a useful name for debug purposes.  */
5028       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5029         name = xstrprintf ("<type_units_%d>",
5030                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5031       else
5032         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5033
5034       pst = create_partial_symtab (per_cu, name);
5035       pst->anonymous = 1;
5036
5037       xfree (name);
5038     }
5039
5040   tu_group->hash.dwo_unit = cu->dwo_unit;
5041   tu_group->hash.line_offset = line_offset_struct;
5042
5043   return tu_group;
5044 }
5045
5046 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5047    STMT_LIST is a DW_AT_stmt_list attribute.  */
5048
5049 static struct type_unit_group *
5050 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5051 {
5052   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5053   struct type_unit_group *tu_group;
5054   void **slot;
5055   unsigned int line_offset;
5056   struct type_unit_group type_unit_group_for_lookup;
5057
5058   if (dwarf2_per_objfile->type_unit_groups == NULL)
5059     {
5060       dwarf2_per_objfile->type_unit_groups =
5061         allocate_type_unit_groups_table ();
5062     }
5063
5064   /* Do we need to create a new group, or can we use an existing one?  */
5065
5066   if (stmt_list)
5067     {
5068       line_offset = DW_UNSND (stmt_list);
5069       ++tu_stats->nr_symtab_sharers;
5070     }
5071   else
5072     {
5073       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5074          We can do various things here like create one group per TU or
5075          spread them over multiple groups to split up the expansion work.
5076          To avoid worst case scenarios (too many groups or too large groups)
5077          we, umm, group them in bunches.  */
5078       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5079                      | (tu_stats->nr_stmt_less_type_units
5080                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5081       ++tu_stats->nr_stmt_less_type_units;
5082     }
5083
5084   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5085   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5086   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5087                          &type_unit_group_for_lookup, INSERT);
5088   if (*slot != NULL)
5089     {
5090       tu_group = *slot;
5091       gdb_assert (tu_group != NULL);
5092     }
5093   else
5094     {
5095       sect_offset line_offset_struct;
5096
5097       line_offset_struct.sect_off = line_offset;
5098       tu_group = create_type_unit_group (cu, line_offset_struct);
5099       *slot = tu_group;
5100       ++tu_stats->nr_symtabs;
5101     }
5102
5103   return tu_group;
5104 }
5105
5106 /* Struct used to sort TUs by their abbreviation table offset.  */
5107
5108 struct tu_abbrev_offset
5109 {
5110   struct signatured_type *sig_type;
5111   sect_offset abbrev_offset;
5112 };
5113
5114 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5115
5116 static int
5117 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5118 {
5119   const struct tu_abbrev_offset * const *a = ap;
5120   const struct tu_abbrev_offset * const *b = bp;
5121   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5122   unsigned int boff = (*b)->abbrev_offset.sect_off;
5123
5124   return (aoff > boff) - (aoff < boff);
5125 }
5126
5127 /* A helper function to add a type_unit_group to a table.  */
5128
5129 static int
5130 add_type_unit_group_to_table (void **slot, void *datum)
5131 {
5132   struct type_unit_group *tu_group = *slot;
5133   struct type_unit_group ***datap = datum;
5134
5135   **datap = tu_group;
5136   ++*datap;
5137
5138   return 1;
5139 }
5140
5141 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5142    each one passing FUNC,DATA.
5143
5144    The efficiency is because we sort TUs by the abbrev table they use and
5145    only read each abbrev table once.  In one program there are 200K TUs
5146    sharing 8K abbrev tables.
5147
5148    The main purpose of this function is to support building the
5149    dwarf2_per_objfile->type_unit_groups table.
5150    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5151    can collapse the search space by grouping them by stmt_list.
5152    The savings can be significant, in the same program from above the 200K TUs
5153    share 8K stmt_list tables.
5154
5155    FUNC is expected to call get_type_unit_group, which will create the
5156    struct type_unit_group if necessary and add it to
5157    dwarf2_per_objfile->type_unit_groups.  */
5158
5159 static void
5160 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5161 {
5162   struct objfile *objfile = dwarf2_per_objfile->objfile;
5163   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5164   struct cleanup *cleanups;
5165   struct abbrev_table *abbrev_table;
5166   sect_offset abbrev_offset;
5167   struct tu_abbrev_offset *sorted_by_abbrev;
5168   struct type_unit_group **iter;
5169   int i;
5170
5171   /* It's up to the caller to not call us multiple times.  */
5172   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5173
5174   if (dwarf2_per_objfile->n_type_units == 0)
5175     return;
5176
5177   /* TUs typically share abbrev tables, and there can be way more TUs than
5178      abbrev tables.  Sort by abbrev table to reduce the number of times we
5179      read each abbrev table in.
5180      Alternatives are to punt or to maintain a cache of abbrev tables.
5181      This is simpler and efficient enough for now.
5182
5183      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5184      symtab to use).  Typically TUs with the same abbrev offset have the same
5185      stmt_list value too so in practice this should work well.
5186
5187      The basic algorithm here is:
5188
5189       sort TUs by abbrev table
5190       for each TU with same abbrev table:
5191         read abbrev table if first user
5192         read TU top level DIE
5193           [IWBN if DWO skeletons had DW_AT_stmt_list]
5194         call FUNC  */
5195
5196   if (dwarf2_read_debug)
5197     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5198
5199   /* Sort in a separate table to maintain the order of all_type_units
5200      for .gdb_index: TU indices directly index all_type_units.  */
5201   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5202                               dwarf2_per_objfile->n_type_units);
5203   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5204     {
5205       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5206
5207       sorted_by_abbrev[i].sig_type = sig_type;
5208       sorted_by_abbrev[i].abbrev_offset =
5209         read_abbrev_offset (sig_type->per_cu.section,
5210                             sig_type->per_cu.offset);
5211     }
5212   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5213   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5214          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5215
5216   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5217      called any number of times, so we don't reset tu_stats here.  */
5218
5219   abbrev_offset.sect_off = ~(unsigned) 0;
5220   abbrev_table = NULL;
5221   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5222
5223   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5224     {
5225       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5226
5227       /* Switch to the next abbrev table if necessary.  */
5228       if (abbrev_table == NULL
5229           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5230         {
5231           if (abbrev_table != NULL)
5232             {
5233               abbrev_table_free (abbrev_table);
5234               /* Reset to NULL in case abbrev_table_read_table throws
5235                  an error: abbrev_table_free_cleanup will get called.  */
5236               abbrev_table = NULL;
5237             }
5238           abbrev_offset = tu->abbrev_offset;
5239           abbrev_table =
5240             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5241                                      abbrev_offset);
5242           ++tu_stats->nr_uniq_abbrev_tables;
5243         }
5244
5245       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5246                                func, data);
5247     }
5248
5249   /* Create a vector of pointers to primary type units to make it easy to
5250      iterate over them and CUs.  See dw2_get_primary_cu.  */
5251   dwarf2_per_objfile->n_type_unit_groups =
5252     htab_elements (dwarf2_per_objfile->type_unit_groups);
5253   dwarf2_per_objfile->all_type_unit_groups =
5254     obstack_alloc (&objfile->objfile_obstack,
5255                    dwarf2_per_objfile->n_type_unit_groups
5256                    * sizeof (struct type_unit_group *));
5257   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5258   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5259                           add_type_unit_group_to_table, &iter);
5260   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5261               == dwarf2_per_objfile->n_type_unit_groups);
5262
5263   do_cleanups (cleanups);
5264
5265   if (dwarf2_read_debug)
5266     {
5267       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5268       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5269                           dwarf2_per_objfile->n_type_units);
5270       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5271                           tu_stats->nr_uniq_abbrev_tables);
5272       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5273                           tu_stats->nr_symtabs);
5274       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5275                           tu_stats->nr_symtab_sharers);
5276       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5277                           tu_stats->nr_stmt_less_type_units);
5278     }
5279 }
5280 \f
5281 /* Partial symbol tables.  */
5282
5283 /* Create a psymtab named NAME and assign it to PER_CU.
5284
5285    The caller must fill in the following details:
5286    dirname, textlow, texthigh.  */
5287
5288 static struct partial_symtab *
5289 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5290 {
5291   struct objfile *objfile = per_cu->objfile;
5292   struct partial_symtab *pst;
5293
5294   pst = start_psymtab_common (objfile, objfile->section_offsets,
5295                               name, 0,
5296                               objfile->global_psymbols.next,
5297                               objfile->static_psymbols.next);
5298
5299   pst->psymtabs_addrmap_supported = 1;
5300
5301   /* This is the glue that links PST into GDB's symbol API.  */
5302   pst->read_symtab_private = per_cu;
5303   pst->read_symtab = dwarf2_read_symtab;
5304   per_cu->v.psymtab = pst;
5305
5306   return pst;
5307 }
5308
5309 /* die_reader_func for process_psymtab_comp_unit.  */
5310
5311 static void
5312 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5313                                   const gdb_byte *info_ptr,
5314                                   struct die_info *comp_unit_die,
5315                                   int has_children,
5316                                   void *data)
5317 {
5318   struct dwarf2_cu *cu = reader->cu;
5319   struct objfile *objfile = cu->objfile;
5320   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5321   struct attribute *attr;
5322   CORE_ADDR baseaddr;
5323   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5324   struct partial_symtab *pst;
5325   int has_pc_info;
5326   const char *filename;
5327   int *want_partial_unit_ptr = data;
5328
5329   if (comp_unit_die->tag == DW_TAG_partial_unit
5330       && (want_partial_unit_ptr == NULL
5331           || !*want_partial_unit_ptr))
5332     return;
5333
5334   gdb_assert (! per_cu->is_debug_types);
5335
5336   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5337
5338   cu->list_in_scope = &file_symbols;
5339
5340   /* Allocate a new partial symbol table structure.  */
5341   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5342   if (attr == NULL || !DW_STRING (attr))
5343     filename = "";
5344   else
5345     filename = DW_STRING (attr);
5346
5347   pst = create_partial_symtab (per_cu, filename);
5348
5349   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5350   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5351   if (attr != NULL)
5352     pst->dirname = DW_STRING (attr);
5353
5354   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5355
5356   dwarf2_find_base_address (comp_unit_die, cu);
5357
5358   /* Possibly set the default values of LOWPC and HIGHPC from
5359      `DW_AT_ranges'.  */
5360   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5361                                       &best_highpc, cu, pst);
5362   if (has_pc_info == 1 && best_lowpc < best_highpc)
5363     /* Store the contiguous range if it is not empty; it can be empty for
5364        CUs with no code.  */
5365     addrmap_set_empty (objfile->psymtabs_addrmap,
5366                        best_lowpc + baseaddr,
5367                        best_highpc + baseaddr - 1, pst);
5368
5369   /* Check if comp unit has_children.
5370      If so, read the rest of the partial symbols from this comp unit.
5371      If not, there's no more debug_info for this comp unit.  */
5372   if (has_children)
5373     {
5374       struct partial_die_info *first_die;
5375       CORE_ADDR lowpc, highpc;
5376
5377       lowpc = ((CORE_ADDR) -1);
5378       highpc = ((CORE_ADDR) 0);
5379
5380       first_die = load_partial_dies (reader, info_ptr, 1);
5381
5382       scan_partial_symbols (first_die, &lowpc, &highpc,
5383                             ! has_pc_info, cu);
5384
5385       /* If we didn't find a lowpc, set it to highpc to avoid
5386          complaints from `maint check'.  */
5387       if (lowpc == ((CORE_ADDR) -1))
5388         lowpc = highpc;
5389
5390       /* If the compilation unit didn't have an explicit address range,
5391          then use the information extracted from its child dies.  */
5392       if (! has_pc_info)
5393         {
5394           best_lowpc = lowpc;
5395           best_highpc = highpc;
5396         }
5397     }
5398   pst->textlow = best_lowpc + baseaddr;
5399   pst->texthigh = best_highpc + baseaddr;
5400
5401   pst->n_global_syms = objfile->global_psymbols.next -
5402     (objfile->global_psymbols.list + pst->globals_offset);
5403   pst->n_static_syms = objfile->static_psymbols.next -
5404     (objfile->static_psymbols.list + pst->statics_offset);
5405   sort_pst_symbols (objfile, pst);
5406
5407   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5408     {
5409       int i;
5410       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5411       struct dwarf2_per_cu_data *iter;
5412
5413       /* Fill in 'dependencies' here; we fill in 'users' in a
5414          post-pass.  */
5415       pst->number_of_dependencies = len;
5416       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5417                                          len * sizeof (struct symtab *));
5418       for (i = 0;
5419            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5420                         i, iter);
5421            ++i)
5422         pst->dependencies[i] = iter->v.psymtab;
5423
5424       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5425     }
5426
5427   /* Get the list of files included in the current compilation unit,
5428      and build a psymtab for each of them.  */
5429   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5430
5431   if (dwarf2_read_debug)
5432     {
5433       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5434
5435       fprintf_unfiltered (gdb_stdlog,
5436                           "Psymtab for %s unit @0x%x: %s - %s"
5437                           ", %d global, %d static syms\n",
5438                           per_cu->is_debug_types ? "type" : "comp",
5439                           per_cu->offset.sect_off,
5440                           paddress (gdbarch, pst->textlow),
5441                           paddress (gdbarch, pst->texthigh),
5442                           pst->n_global_syms, pst->n_static_syms);
5443     }
5444 }
5445
5446 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5447    Process compilation unit THIS_CU for a psymtab.  */
5448
5449 static void
5450 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5451                            int want_partial_unit)
5452 {
5453   /* If this compilation unit was already read in, free the
5454      cached copy in order to read it in again.  This is
5455      necessary because we skipped some symbols when we first
5456      read in the compilation unit (see load_partial_dies).
5457      This problem could be avoided, but the benefit is unclear.  */
5458   if (this_cu->cu != NULL)
5459     free_one_cached_comp_unit (this_cu);
5460
5461   gdb_assert (! this_cu->is_debug_types);
5462   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5463                            process_psymtab_comp_unit_reader,
5464                            &want_partial_unit);
5465
5466   /* Age out any secondary CUs.  */
5467   age_cached_comp_units ();
5468 }
5469
5470 /* Reader function for build_type_psymtabs.  */
5471
5472 static void
5473 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5474                             const gdb_byte *info_ptr,
5475                             struct die_info *type_unit_die,
5476                             int has_children,
5477                             void *data)
5478 {
5479   struct objfile *objfile = dwarf2_per_objfile->objfile;
5480   struct dwarf2_cu *cu = reader->cu;
5481   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5482   struct signatured_type *sig_type;
5483   struct type_unit_group *tu_group;
5484   struct attribute *attr;
5485   struct partial_die_info *first_die;
5486   CORE_ADDR lowpc, highpc;
5487   struct partial_symtab *pst;
5488
5489   gdb_assert (data == NULL);
5490   gdb_assert (per_cu->is_debug_types);
5491   sig_type = (struct signatured_type *) per_cu;
5492
5493   if (! has_children)
5494     return;
5495
5496   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5497   tu_group = get_type_unit_group (cu, attr);
5498
5499   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5500
5501   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5502   cu->list_in_scope = &file_symbols;
5503   pst = create_partial_symtab (per_cu, "");
5504   pst->anonymous = 1;
5505
5506   first_die = load_partial_dies (reader, info_ptr, 1);
5507
5508   lowpc = (CORE_ADDR) -1;
5509   highpc = (CORE_ADDR) 0;
5510   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5511
5512   pst->n_global_syms = objfile->global_psymbols.next -
5513     (objfile->global_psymbols.list + pst->globals_offset);
5514   pst->n_static_syms = objfile->static_psymbols.next -
5515     (objfile->static_psymbols.list + pst->statics_offset);
5516   sort_pst_symbols (objfile, pst);
5517 }
5518
5519 /* Traversal function for build_type_psymtabs.  */
5520
5521 static int
5522 build_type_psymtab_dependencies (void **slot, void *info)
5523 {
5524   struct objfile *objfile = dwarf2_per_objfile->objfile;
5525   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5526   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5527   struct partial_symtab *pst = per_cu->v.psymtab;
5528   int len = VEC_length (sig_type_ptr, tu_group->tus);
5529   struct signatured_type *iter;
5530   int i;
5531
5532   gdb_assert (len > 0);
5533   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5534
5535   pst->number_of_dependencies = len;
5536   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5537                                      len * sizeof (struct psymtab *));
5538   for (i = 0;
5539        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5540        ++i)
5541     {
5542       gdb_assert (iter->per_cu.is_debug_types);
5543       pst->dependencies[i] = iter->per_cu.v.psymtab;
5544       iter->type_unit_group = tu_group;
5545     }
5546
5547   VEC_free (sig_type_ptr, tu_group->tus);
5548
5549   return 1;
5550 }
5551
5552 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5553    Build partial symbol tables for the .debug_types comp-units.  */
5554
5555 static void
5556 build_type_psymtabs (struct objfile *objfile)
5557 {
5558   if (! create_all_type_units (objfile))
5559     return;
5560
5561   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5562
5563   /* Now that all TUs have been processed we can fill in the dependencies.  */
5564   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5565                           build_type_psymtab_dependencies, NULL);
5566 }
5567
5568 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5569
5570 static void
5571 psymtabs_addrmap_cleanup (void *o)
5572 {
5573   struct objfile *objfile = o;
5574
5575   objfile->psymtabs_addrmap = NULL;
5576 }
5577
5578 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5579
5580 static void
5581 set_partial_user (struct objfile *objfile)
5582 {
5583   int i;
5584
5585   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5586     {
5587       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5588       struct partial_symtab *pst = per_cu->v.psymtab;
5589       int j;
5590
5591       if (pst == NULL)
5592         continue;
5593
5594       for (j = 0; j < pst->number_of_dependencies; ++j)
5595         {
5596           /* Set the 'user' field only if it is not already set.  */
5597           if (pst->dependencies[j]->user == NULL)
5598             pst->dependencies[j]->user = pst;
5599         }
5600     }
5601 }
5602
5603 /* Build the partial symbol table by doing a quick pass through the
5604    .debug_info and .debug_abbrev sections.  */
5605
5606 static void
5607 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5608 {
5609   struct cleanup *back_to, *addrmap_cleanup;
5610   struct obstack temp_obstack;
5611   int i;
5612
5613   if (dwarf2_read_debug)
5614     {
5615       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5616                           objfile->name);
5617     }
5618
5619   dwarf2_per_objfile->reading_partial_symbols = 1;
5620
5621   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5622
5623   /* Any cached compilation units will be linked by the per-objfile
5624      read_in_chain.  Make sure to free them when we're done.  */
5625   back_to = make_cleanup (free_cached_comp_units, NULL);
5626
5627   build_type_psymtabs (objfile);
5628
5629   create_all_comp_units (objfile);
5630
5631   /* Create a temporary address map on a temporary obstack.  We later
5632      copy this to the final obstack.  */
5633   obstack_init (&temp_obstack);
5634   make_cleanup_obstack_free (&temp_obstack);
5635   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5636   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5637
5638   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5639     {
5640       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5641
5642       process_psymtab_comp_unit (per_cu, 0);
5643     }
5644
5645   set_partial_user (objfile);
5646
5647   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5648                                                     &objfile->objfile_obstack);
5649   discard_cleanups (addrmap_cleanup);
5650
5651   do_cleanups (back_to);
5652
5653   if (dwarf2_read_debug)
5654     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5655                         objfile->name);
5656 }
5657
5658 /* die_reader_func for load_partial_comp_unit.  */
5659
5660 static void
5661 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5662                                const gdb_byte *info_ptr,
5663                                struct die_info *comp_unit_die,
5664                                int has_children,
5665                                void *data)
5666 {
5667   struct dwarf2_cu *cu = reader->cu;
5668
5669   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5670
5671   /* Check if comp unit has_children.
5672      If so, read the rest of the partial symbols from this comp unit.
5673      If not, there's no more debug_info for this comp unit.  */
5674   if (has_children)
5675     load_partial_dies (reader, info_ptr, 0);
5676 }
5677
5678 /* Load the partial DIEs for a secondary CU into memory.
5679    This is also used when rereading a primary CU with load_all_dies.  */
5680
5681 static void
5682 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5683 {
5684   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5685                            load_partial_comp_unit_reader, NULL);
5686 }
5687
5688 static void
5689 read_comp_units_from_section (struct objfile *objfile,
5690                               struct dwarf2_section_info *section,
5691                               unsigned int is_dwz,
5692                               int *n_allocated,
5693                               int *n_comp_units,
5694                               struct dwarf2_per_cu_data ***all_comp_units)
5695 {
5696   const gdb_byte *info_ptr;
5697   bfd *abfd = section->asection->owner;
5698
5699   if (dwarf2_read_debug)
5700     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
5701                         section->asection->name, bfd_get_filename (abfd));
5702
5703   dwarf2_read_section (objfile, section);
5704
5705   info_ptr = section->buffer;
5706
5707   while (info_ptr < section->buffer + section->size)
5708     {
5709       unsigned int length, initial_length_size;
5710       struct dwarf2_per_cu_data *this_cu;
5711       sect_offset offset;
5712
5713       offset.sect_off = info_ptr - section->buffer;
5714
5715       /* Read just enough information to find out where the next
5716          compilation unit is.  */
5717       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5718
5719       /* Save the compilation unit for later lookup.  */
5720       this_cu = obstack_alloc (&objfile->objfile_obstack,
5721                                sizeof (struct dwarf2_per_cu_data));
5722       memset (this_cu, 0, sizeof (*this_cu));
5723       this_cu->offset = offset;
5724       this_cu->length = length + initial_length_size;
5725       this_cu->is_dwz = is_dwz;
5726       this_cu->objfile = objfile;
5727       this_cu->section = section;
5728
5729       if (*n_comp_units == *n_allocated)
5730         {
5731           *n_allocated *= 2;
5732           *all_comp_units = xrealloc (*all_comp_units,
5733                                       *n_allocated
5734                                       * sizeof (struct dwarf2_per_cu_data *));
5735         }
5736       (*all_comp_units)[*n_comp_units] = this_cu;
5737       ++*n_comp_units;
5738
5739       info_ptr = info_ptr + this_cu->length;
5740     }
5741 }
5742
5743 /* Create a list of all compilation units in OBJFILE.
5744    This is only done for -readnow and building partial symtabs.  */
5745
5746 static void
5747 create_all_comp_units (struct objfile *objfile)
5748 {
5749   int n_allocated;
5750   int n_comp_units;
5751   struct dwarf2_per_cu_data **all_comp_units;
5752
5753   n_comp_units = 0;
5754   n_allocated = 10;
5755   all_comp_units = xmalloc (n_allocated
5756                             * sizeof (struct dwarf2_per_cu_data *));
5757
5758   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5759                                 &n_allocated, &n_comp_units, &all_comp_units);
5760
5761   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5762     {
5763       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5764
5765       read_comp_units_from_section (objfile, &dwz->info, 1,
5766                                     &n_allocated, &n_comp_units,
5767                                     &all_comp_units);
5768     }
5769
5770   dwarf2_per_objfile->all_comp_units
5771     = obstack_alloc (&objfile->objfile_obstack,
5772                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5773   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5774           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5775   xfree (all_comp_units);
5776   dwarf2_per_objfile->n_comp_units = n_comp_units;
5777 }
5778
5779 /* Process all loaded DIEs for compilation unit CU, starting at
5780    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5781    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5782    DW_AT_ranges).  If NEED_PC is set, then this function will set
5783    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5784    and record the covered ranges in the addrmap.  */
5785
5786 static void
5787 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5788                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5789 {
5790   struct partial_die_info *pdi;
5791
5792   /* Now, march along the PDI's, descending into ones which have
5793      interesting children but skipping the children of the other ones,
5794      until we reach the end of the compilation unit.  */
5795
5796   pdi = first_die;
5797
5798   while (pdi != NULL)
5799     {
5800       fixup_partial_die (pdi, cu);
5801
5802       /* Anonymous namespaces or modules have no name but have interesting
5803          children, so we need to look at them.  Ditto for anonymous
5804          enums.  */
5805
5806       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5807           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5808           || pdi->tag == DW_TAG_imported_unit)
5809         {
5810           switch (pdi->tag)
5811             {
5812             case DW_TAG_subprogram:
5813               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5814               break;
5815             case DW_TAG_constant:
5816             case DW_TAG_variable:
5817             case DW_TAG_typedef:
5818             case DW_TAG_union_type:
5819               if (!pdi->is_declaration)
5820                 {
5821                   add_partial_symbol (pdi, cu);
5822                 }
5823               break;
5824             case DW_TAG_class_type:
5825             case DW_TAG_interface_type:
5826             case DW_TAG_structure_type:
5827               if (!pdi->is_declaration)
5828                 {
5829                   add_partial_symbol (pdi, cu);
5830                 }
5831               break;
5832             case DW_TAG_enumeration_type:
5833               if (!pdi->is_declaration)
5834                 add_partial_enumeration (pdi, cu);
5835               break;
5836             case DW_TAG_base_type:
5837             case DW_TAG_subrange_type:
5838               /* File scope base type definitions are added to the partial
5839                  symbol table.  */
5840               add_partial_symbol (pdi, cu);
5841               break;
5842             case DW_TAG_namespace:
5843               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5844               break;
5845             case DW_TAG_module:
5846               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5847               break;
5848             case DW_TAG_imported_unit:
5849               {
5850                 struct dwarf2_per_cu_data *per_cu;
5851
5852                 /* For now we don't handle imported units in type units.  */
5853                 if (cu->per_cu->is_debug_types)
5854                   {
5855                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5856                              " supported in type units [in module %s]"),
5857                            cu->objfile->name);
5858                   }
5859
5860                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5861                                                            pdi->is_dwz,
5862                                                            cu->objfile);
5863
5864                 /* Go read the partial unit, if needed.  */
5865                 if (per_cu->v.psymtab == NULL)
5866                   process_psymtab_comp_unit (per_cu, 1);
5867
5868                 VEC_safe_push (dwarf2_per_cu_ptr,
5869                                cu->per_cu->imported_symtabs, per_cu);
5870               }
5871               break;
5872             default:
5873               break;
5874             }
5875         }
5876
5877       /* If the die has a sibling, skip to the sibling.  */
5878
5879       pdi = pdi->die_sibling;
5880     }
5881 }
5882
5883 /* Functions used to compute the fully scoped name of a partial DIE.
5884
5885    Normally, this is simple.  For C++, the parent DIE's fully scoped
5886    name is concatenated with "::" and the partial DIE's name.  For
5887    Java, the same thing occurs except that "." is used instead of "::".
5888    Enumerators are an exception; they use the scope of their parent
5889    enumeration type, i.e. the name of the enumeration type is not
5890    prepended to the enumerator.
5891
5892    There are two complexities.  One is DW_AT_specification; in this
5893    case "parent" means the parent of the target of the specification,
5894    instead of the direct parent of the DIE.  The other is compilers
5895    which do not emit DW_TAG_namespace; in this case we try to guess
5896    the fully qualified name of structure types from their members'
5897    linkage names.  This must be done using the DIE's children rather
5898    than the children of any DW_AT_specification target.  We only need
5899    to do this for structures at the top level, i.e. if the target of
5900    any DW_AT_specification (if any; otherwise the DIE itself) does not
5901    have a parent.  */
5902
5903 /* Compute the scope prefix associated with PDI's parent, in
5904    compilation unit CU.  The result will be allocated on CU's
5905    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5906    field.  NULL is returned if no prefix is necessary.  */
5907 static const char *
5908 partial_die_parent_scope (struct partial_die_info *pdi,
5909                           struct dwarf2_cu *cu)
5910 {
5911   const char *grandparent_scope;
5912   struct partial_die_info *parent, *real_pdi;
5913
5914   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5915      then this means the parent of the specification DIE.  */
5916
5917   real_pdi = pdi;
5918   while (real_pdi->has_specification)
5919     real_pdi = find_partial_die (real_pdi->spec_offset,
5920                                  real_pdi->spec_is_dwz, cu);
5921
5922   parent = real_pdi->die_parent;
5923   if (parent == NULL)
5924     return NULL;
5925
5926   if (parent->scope_set)
5927     return parent->scope;
5928
5929   fixup_partial_die (parent, cu);
5930
5931   grandparent_scope = partial_die_parent_scope (parent, cu);
5932
5933   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5934      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5935      Work around this problem here.  */
5936   if (cu->language == language_cplus
5937       && parent->tag == DW_TAG_namespace
5938       && strcmp (parent->name, "::") == 0
5939       && grandparent_scope == NULL)
5940     {
5941       parent->scope = NULL;
5942       parent->scope_set = 1;
5943       return NULL;
5944     }
5945
5946   if (pdi->tag == DW_TAG_enumerator)
5947     /* Enumerators should not get the name of the enumeration as a prefix.  */
5948     parent->scope = grandparent_scope;
5949   else if (parent->tag == DW_TAG_namespace
5950       || parent->tag == DW_TAG_module
5951       || parent->tag == DW_TAG_structure_type
5952       || parent->tag == DW_TAG_class_type
5953       || parent->tag == DW_TAG_interface_type
5954       || parent->tag == DW_TAG_union_type
5955       || parent->tag == DW_TAG_enumeration_type)
5956     {
5957       if (grandparent_scope == NULL)
5958         parent->scope = parent->name;
5959       else
5960         parent->scope = typename_concat (&cu->comp_unit_obstack,
5961                                          grandparent_scope,
5962                                          parent->name, 0, cu);
5963     }
5964   else
5965     {
5966       /* FIXME drow/2004-04-01: What should we be doing with
5967          function-local names?  For partial symbols, we should probably be
5968          ignoring them.  */
5969       complaint (&symfile_complaints,
5970                  _("unhandled containing DIE tag %d for DIE at %d"),
5971                  parent->tag, pdi->offset.sect_off);
5972       parent->scope = grandparent_scope;
5973     }
5974
5975   parent->scope_set = 1;
5976   return parent->scope;
5977 }
5978
5979 /* Return the fully scoped name associated with PDI, from compilation unit
5980    CU.  The result will be allocated with malloc.  */
5981
5982 static char *
5983 partial_die_full_name (struct partial_die_info *pdi,
5984                        struct dwarf2_cu *cu)
5985 {
5986   const char *parent_scope;
5987
5988   /* If this is a template instantiation, we can not work out the
5989      template arguments from partial DIEs.  So, unfortunately, we have
5990      to go through the full DIEs.  At least any work we do building
5991      types here will be reused if full symbols are loaded later.  */
5992   if (pdi->has_template_arguments)
5993     {
5994       fixup_partial_die (pdi, cu);
5995
5996       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5997         {
5998           struct die_info *die;
5999           struct attribute attr;
6000           struct dwarf2_cu *ref_cu = cu;
6001
6002           /* DW_FORM_ref_addr is using section offset.  */
6003           attr.name = 0;
6004           attr.form = DW_FORM_ref_addr;
6005           attr.u.unsnd = pdi->offset.sect_off;
6006           die = follow_die_ref (NULL, &attr, &ref_cu);
6007
6008           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6009         }
6010     }
6011
6012   parent_scope = partial_die_parent_scope (pdi, cu);
6013   if (parent_scope == NULL)
6014     return NULL;
6015   else
6016     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6017 }
6018
6019 static void
6020 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6021 {
6022   struct objfile *objfile = cu->objfile;
6023   CORE_ADDR addr = 0;
6024   const char *actual_name = NULL;
6025   CORE_ADDR baseaddr;
6026   char *built_actual_name;
6027
6028   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6029
6030   built_actual_name = partial_die_full_name (pdi, cu);
6031   if (built_actual_name != NULL)
6032     actual_name = built_actual_name;
6033
6034   if (actual_name == NULL)
6035     actual_name = pdi->name;
6036
6037   switch (pdi->tag)
6038     {
6039     case DW_TAG_subprogram:
6040       if (pdi->is_external || cu->language == language_ada)
6041         {
6042           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6043              of the global scope.  But in Ada, we want to be able to access
6044              nested procedures globally.  So all Ada subprograms are stored
6045              in the global scope.  */
6046           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6047              mst_text, objfile); */
6048           add_psymbol_to_list (actual_name, strlen (actual_name),
6049                                built_actual_name != NULL,
6050                                VAR_DOMAIN, LOC_BLOCK,
6051                                &objfile->global_psymbols,
6052                                0, pdi->lowpc + baseaddr,
6053                                cu->language, objfile);
6054         }
6055       else
6056         {
6057           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6058              mst_file_text, objfile); */
6059           add_psymbol_to_list (actual_name, strlen (actual_name),
6060                                built_actual_name != NULL,
6061                                VAR_DOMAIN, LOC_BLOCK,
6062                                &objfile->static_psymbols,
6063                                0, pdi->lowpc + baseaddr,
6064                                cu->language, objfile);
6065         }
6066       break;
6067     case DW_TAG_constant:
6068       {
6069         struct psymbol_allocation_list *list;
6070
6071         if (pdi->is_external)
6072           list = &objfile->global_psymbols;
6073         else
6074           list = &objfile->static_psymbols;
6075         add_psymbol_to_list (actual_name, strlen (actual_name),
6076                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6077                              list, 0, 0, cu->language, objfile);
6078       }
6079       break;
6080     case DW_TAG_variable:
6081       if (pdi->d.locdesc)
6082         addr = decode_locdesc (pdi->d.locdesc, cu);
6083
6084       if (pdi->d.locdesc
6085           && addr == 0
6086           && !dwarf2_per_objfile->has_section_at_zero)
6087         {
6088           /* A global or static variable may also have been stripped
6089              out by the linker if unused, in which case its address
6090              will be nullified; do not add such variables into partial
6091              symbol table then.  */
6092         }
6093       else if (pdi->is_external)
6094         {
6095           /* Global Variable.
6096              Don't enter into the minimal symbol tables as there is
6097              a minimal symbol table entry from the ELF symbols already.
6098              Enter into partial symbol table if it has a location
6099              descriptor or a type.
6100              If the location descriptor is missing, new_symbol will create
6101              a LOC_UNRESOLVED symbol, the address of the variable will then
6102              be determined from the minimal symbol table whenever the variable
6103              is referenced.
6104              The address for the partial symbol table entry is not
6105              used by GDB, but it comes in handy for debugging partial symbol
6106              table building.  */
6107
6108           if (pdi->d.locdesc || pdi->has_type)
6109             add_psymbol_to_list (actual_name, strlen (actual_name),
6110                                  built_actual_name != NULL,
6111                                  VAR_DOMAIN, LOC_STATIC,
6112                                  &objfile->global_psymbols,
6113                                  0, addr + baseaddr,
6114                                  cu->language, objfile);
6115         }
6116       else
6117         {
6118           /* Static Variable.  Skip symbols without location descriptors.  */
6119           if (pdi->d.locdesc == NULL)
6120             {
6121               xfree (built_actual_name);
6122               return;
6123             }
6124           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6125              mst_file_data, objfile); */
6126           add_psymbol_to_list (actual_name, strlen (actual_name),
6127                                built_actual_name != NULL,
6128                                VAR_DOMAIN, LOC_STATIC,
6129                                &objfile->static_psymbols,
6130                                0, addr + baseaddr,
6131                                cu->language, objfile);
6132         }
6133       break;
6134     case DW_TAG_typedef:
6135     case DW_TAG_base_type:
6136     case DW_TAG_subrange_type:
6137       add_psymbol_to_list (actual_name, strlen (actual_name),
6138                            built_actual_name != NULL,
6139                            VAR_DOMAIN, LOC_TYPEDEF,
6140                            &objfile->static_psymbols,
6141                            0, (CORE_ADDR) 0, cu->language, objfile);
6142       break;
6143     case DW_TAG_namespace:
6144       add_psymbol_to_list (actual_name, strlen (actual_name),
6145                            built_actual_name != NULL,
6146                            VAR_DOMAIN, LOC_TYPEDEF,
6147                            &objfile->global_psymbols,
6148                            0, (CORE_ADDR) 0, cu->language, objfile);
6149       break;
6150     case DW_TAG_class_type:
6151     case DW_TAG_interface_type:
6152     case DW_TAG_structure_type:
6153     case DW_TAG_union_type:
6154     case DW_TAG_enumeration_type:
6155       /* Skip external references.  The DWARF standard says in the section
6156          about "Structure, Union, and Class Type Entries": "An incomplete
6157          structure, union or class type is represented by a structure,
6158          union or class entry that does not have a byte size attribute
6159          and that has a DW_AT_declaration attribute."  */
6160       if (!pdi->has_byte_size && pdi->is_declaration)
6161         {
6162           xfree (built_actual_name);
6163           return;
6164         }
6165
6166       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6167          static vs. global.  */
6168       add_psymbol_to_list (actual_name, strlen (actual_name),
6169                            built_actual_name != NULL,
6170                            STRUCT_DOMAIN, LOC_TYPEDEF,
6171                            (cu->language == language_cplus
6172                             || cu->language == language_java)
6173                            ? &objfile->global_psymbols
6174                            : &objfile->static_psymbols,
6175                            0, (CORE_ADDR) 0, cu->language, objfile);
6176
6177       break;
6178     case DW_TAG_enumerator:
6179       add_psymbol_to_list (actual_name, strlen (actual_name),
6180                            built_actual_name != NULL,
6181                            VAR_DOMAIN, LOC_CONST,
6182                            (cu->language == language_cplus
6183                             || cu->language == language_java)
6184                            ? &objfile->global_psymbols
6185                            : &objfile->static_psymbols,
6186                            0, (CORE_ADDR) 0, cu->language, objfile);
6187       break;
6188     default:
6189       break;
6190     }
6191
6192   xfree (built_actual_name);
6193 }
6194
6195 /* Read a partial die corresponding to a namespace; also, add a symbol
6196    corresponding to that namespace to the symbol table.  NAMESPACE is
6197    the name of the enclosing namespace.  */
6198
6199 static void
6200 add_partial_namespace (struct partial_die_info *pdi,
6201                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6202                        int need_pc, struct dwarf2_cu *cu)
6203 {
6204   /* Add a symbol for the namespace.  */
6205
6206   add_partial_symbol (pdi, cu);
6207
6208   /* Now scan partial symbols in that namespace.  */
6209
6210   if (pdi->has_children)
6211     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6212 }
6213
6214 /* Read a partial die corresponding to a Fortran module.  */
6215
6216 static void
6217 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6218                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6219 {
6220   /* Now scan partial symbols in that module.  */
6221
6222   if (pdi->has_children)
6223     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6224 }
6225
6226 /* Read a partial die corresponding to a subprogram and create a partial
6227    symbol for that subprogram.  When the CU language allows it, this
6228    routine also defines a partial symbol for each nested subprogram
6229    that this subprogram contains.
6230
6231    DIE my also be a lexical block, in which case we simply search
6232    recursively for suprograms defined inside that lexical block.
6233    Again, this is only performed when the CU language allows this
6234    type of definitions.  */
6235
6236 static void
6237 add_partial_subprogram (struct partial_die_info *pdi,
6238                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6239                         int need_pc, struct dwarf2_cu *cu)
6240 {
6241   if (pdi->tag == DW_TAG_subprogram)
6242     {
6243       if (pdi->has_pc_info)
6244         {
6245           if (pdi->lowpc < *lowpc)
6246             *lowpc = pdi->lowpc;
6247           if (pdi->highpc > *highpc)
6248             *highpc = pdi->highpc;
6249           if (need_pc)
6250             {
6251               CORE_ADDR baseaddr;
6252               struct objfile *objfile = cu->objfile;
6253
6254               baseaddr = ANOFFSET (objfile->section_offsets,
6255                                    SECT_OFF_TEXT (objfile));
6256               addrmap_set_empty (objfile->psymtabs_addrmap,
6257                                  pdi->lowpc + baseaddr,
6258                                  pdi->highpc - 1 + baseaddr,
6259                                  cu->per_cu->v.psymtab);
6260             }
6261         }
6262
6263       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6264         {
6265           if (!pdi->is_declaration)
6266             /* Ignore subprogram DIEs that do not have a name, they are
6267                illegal.  Do not emit a complaint at this point, we will
6268                do so when we convert this psymtab into a symtab.  */
6269             if (pdi->name)
6270               add_partial_symbol (pdi, cu);
6271         }
6272     }
6273
6274   if (! pdi->has_children)
6275     return;
6276
6277   if (cu->language == language_ada)
6278     {
6279       pdi = pdi->die_child;
6280       while (pdi != NULL)
6281         {
6282           fixup_partial_die (pdi, cu);
6283           if (pdi->tag == DW_TAG_subprogram
6284               || pdi->tag == DW_TAG_lexical_block)
6285             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6286           pdi = pdi->die_sibling;
6287         }
6288     }
6289 }
6290
6291 /* Read a partial die corresponding to an enumeration type.  */
6292
6293 static void
6294 add_partial_enumeration (struct partial_die_info *enum_pdi,
6295                          struct dwarf2_cu *cu)
6296 {
6297   struct partial_die_info *pdi;
6298
6299   if (enum_pdi->name != NULL)
6300     add_partial_symbol (enum_pdi, cu);
6301
6302   pdi = enum_pdi->die_child;
6303   while (pdi)
6304     {
6305       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6306         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6307       else
6308         add_partial_symbol (pdi, cu);
6309       pdi = pdi->die_sibling;
6310     }
6311 }
6312
6313 /* Return the initial uleb128 in the die at INFO_PTR.  */
6314
6315 static unsigned int
6316 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6317 {
6318   unsigned int bytes_read;
6319
6320   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6321 }
6322
6323 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6324    Return the corresponding abbrev, or NULL if the number is zero (indicating
6325    an empty DIE).  In either case *BYTES_READ will be set to the length of
6326    the initial number.  */
6327
6328 static struct abbrev_info *
6329 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6330                  struct dwarf2_cu *cu)
6331 {
6332   bfd *abfd = cu->objfile->obfd;
6333   unsigned int abbrev_number;
6334   struct abbrev_info *abbrev;
6335
6336   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6337
6338   if (abbrev_number == 0)
6339     return NULL;
6340
6341   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6342   if (!abbrev)
6343     {
6344       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6345              abbrev_number, bfd_get_filename (abfd));
6346     }
6347
6348   return abbrev;
6349 }
6350
6351 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6352    Returns a pointer to the end of a series of DIEs, terminated by an empty
6353    DIE.  Any children of the skipped DIEs will also be skipped.  */
6354
6355 static const gdb_byte *
6356 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6357 {
6358   struct dwarf2_cu *cu = reader->cu;
6359   struct abbrev_info *abbrev;
6360   unsigned int bytes_read;
6361
6362   while (1)
6363     {
6364       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6365       if (abbrev == NULL)
6366         return info_ptr + bytes_read;
6367       else
6368         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6369     }
6370 }
6371
6372 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6373    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6374    abbrev corresponding to that skipped uleb128 should be passed in
6375    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6376    children.  */
6377
6378 static const gdb_byte *
6379 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6380               struct abbrev_info *abbrev)
6381 {
6382   unsigned int bytes_read;
6383   struct attribute attr;
6384   bfd *abfd = reader->abfd;
6385   struct dwarf2_cu *cu = reader->cu;
6386   const gdb_byte *buffer = reader->buffer;
6387   const gdb_byte *buffer_end = reader->buffer_end;
6388   const gdb_byte *start_info_ptr = info_ptr;
6389   unsigned int form, i;
6390
6391   for (i = 0; i < abbrev->num_attrs; i++)
6392     {
6393       /* The only abbrev we care about is DW_AT_sibling.  */
6394       if (abbrev->attrs[i].name == DW_AT_sibling)
6395         {
6396           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6397           if (attr.form == DW_FORM_ref_addr)
6398             complaint (&symfile_complaints,
6399                        _("ignoring absolute DW_AT_sibling"));
6400           else
6401             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6402         }
6403
6404       /* If it isn't DW_AT_sibling, skip this attribute.  */
6405       form = abbrev->attrs[i].form;
6406     skip_attribute:
6407       switch (form)
6408         {
6409         case DW_FORM_ref_addr:
6410           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6411              and later it is offset sized.  */
6412           if (cu->header.version == 2)
6413             info_ptr += cu->header.addr_size;
6414           else
6415             info_ptr += cu->header.offset_size;
6416           break;
6417         case DW_FORM_GNU_ref_alt:
6418           info_ptr += cu->header.offset_size;
6419           break;
6420         case DW_FORM_addr:
6421           info_ptr += cu->header.addr_size;
6422           break;
6423         case DW_FORM_data1:
6424         case DW_FORM_ref1:
6425         case DW_FORM_flag:
6426           info_ptr += 1;
6427           break;
6428         case DW_FORM_flag_present:
6429           break;
6430         case DW_FORM_data2:
6431         case DW_FORM_ref2:
6432           info_ptr += 2;
6433           break;
6434         case DW_FORM_data4:
6435         case DW_FORM_ref4:
6436           info_ptr += 4;
6437           break;
6438         case DW_FORM_data8:
6439         case DW_FORM_ref8:
6440         case DW_FORM_ref_sig8:
6441           info_ptr += 8;
6442           break;
6443         case DW_FORM_string:
6444           read_direct_string (abfd, info_ptr, &bytes_read);
6445           info_ptr += bytes_read;
6446           break;
6447         case DW_FORM_sec_offset:
6448         case DW_FORM_strp:
6449         case DW_FORM_GNU_strp_alt:
6450           info_ptr += cu->header.offset_size;
6451           break;
6452         case DW_FORM_exprloc:
6453         case DW_FORM_block:
6454           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6455           info_ptr += bytes_read;
6456           break;
6457         case DW_FORM_block1:
6458           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6459           break;
6460         case DW_FORM_block2:
6461           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6462           break;
6463         case DW_FORM_block4:
6464           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6465           break;
6466         case DW_FORM_sdata:
6467         case DW_FORM_udata:
6468         case DW_FORM_ref_udata:
6469         case DW_FORM_GNU_addr_index:
6470         case DW_FORM_GNU_str_index:
6471           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6472           break;
6473         case DW_FORM_indirect:
6474           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6475           info_ptr += bytes_read;
6476           /* We need to continue parsing from here, so just go back to
6477              the top.  */
6478           goto skip_attribute;
6479
6480         default:
6481           error (_("Dwarf Error: Cannot handle %s "
6482                    "in DWARF reader [in module %s]"),
6483                  dwarf_form_name (form),
6484                  bfd_get_filename (abfd));
6485         }
6486     }
6487
6488   if (abbrev->has_children)
6489     return skip_children (reader, info_ptr);
6490   else
6491     return info_ptr;
6492 }
6493
6494 /* Locate ORIG_PDI's sibling.
6495    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6496
6497 static const gdb_byte *
6498 locate_pdi_sibling (const struct die_reader_specs *reader,
6499                     struct partial_die_info *orig_pdi,
6500                     const gdb_byte *info_ptr)
6501 {
6502   /* Do we know the sibling already?  */
6503
6504   if (orig_pdi->sibling)
6505     return orig_pdi->sibling;
6506
6507   /* Are there any children to deal with?  */
6508
6509   if (!orig_pdi->has_children)
6510     return info_ptr;
6511
6512   /* Skip the children the long way.  */
6513
6514   return skip_children (reader, info_ptr);
6515 }
6516
6517 /* Expand this partial symbol table into a full symbol table.  SELF is
6518    not NULL.  */
6519
6520 static void
6521 dwarf2_read_symtab (struct partial_symtab *self,
6522                     struct objfile *objfile)
6523 {
6524   if (self->readin)
6525     {
6526       warning (_("bug: psymtab for %s is already read in."),
6527                self->filename);
6528     }
6529   else
6530     {
6531       if (info_verbose)
6532         {
6533           printf_filtered (_("Reading in symbols for %s..."),
6534                            self->filename);
6535           gdb_flush (gdb_stdout);
6536         }
6537
6538       /* Restore our global data.  */
6539       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6540
6541       /* If this psymtab is constructed from a debug-only objfile, the
6542          has_section_at_zero flag will not necessarily be correct.  We
6543          can get the correct value for this flag by looking at the data
6544          associated with the (presumably stripped) associated objfile.  */
6545       if (objfile->separate_debug_objfile_backlink)
6546         {
6547           struct dwarf2_per_objfile *dpo_backlink
6548             = objfile_data (objfile->separate_debug_objfile_backlink,
6549                             dwarf2_objfile_data_key);
6550
6551           dwarf2_per_objfile->has_section_at_zero
6552             = dpo_backlink->has_section_at_zero;
6553         }
6554
6555       dwarf2_per_objfile->reading_partial_symbols = 0;
6556
6557       psymtab_to_symtab_1 (self);
6558
6559       /* Finish up the debug error message.  */
6560       if (info_verbose)
6561         printf_filtered (_("done.\n"));
6562     }
6563
6564   process_cu_includes ();
6565 }
6566 \f
6567 /* Reading in full CUs.  */
6568
6569 /* Add PER_CU to the queue.  */
6570
6571 static void
6572 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6573                  enum language pretend_language)
6574 {
6575   struct dwarf2_queue_item *item;
6576
6577   per_cu->queued = 1;
6578   item = xmalloc (sizeof (*item));
6579   item->per_cu = per_cu;
6580   item->pretend_language = pretend_language;
6581   item->next = NULL;
6582
6583   if (dwarf2_queue == NULL)
6584     dwarf2_queue = item;
6585   else
6586     dwarf2_queue_tail->next = item;
6587
6588   dwarf2_queue_tail = item;
6589 }
6590
6591 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6592    unit and add it to our queue.
6593    The result is non-zero if PER_CU was queued, otherwise the result is zero
6594    meaning either PER_CU is already queued or it is already loaded.  */
6595
6596 static int
6597 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6598                        struct dwarf2_per_cu_data *per_cu,
6599                        enum language pretend_language)
6600 {
6601   /* We may arrive here during partial symbol reading, if we need full
6602      DIEs to process an unusual case (e.g. template arguments).  Do
6603      not queue PER_CU, just tell our caller to load its DIEs.  */
6604   if (dwarf2_per_objfile->reading_partial_symbols)
6605     {
6606       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6607         return 1;
6608       return 0;
6609     }
6610
6611   /* Mark the dependence relation so that we don't flush PER_CU
6612      too early.  */
6613   dwarf2_add_dependence (this_cu, per_cu);
6614
6615   /* If it's already on the queue, we have nothing to do.  */
6616   if (per_cu->queued)
6617     return 0;
6618
6619   /* If the compilation unit is already loaded, just mark it as
6620      used.  */
6621   if (per_cu->cu != NULL)
6622     {
6623       per_cu->cu->last_used = 0;
6624       return 0;
6625     }
6626
6627   /* Add it to the queue.  */
6628   queue_comp_unit (per_cu, pretend_language);
6629
6630   return 1;
6631 }
6632
6633 /* Process the queue.  */
6634
6635 static void
6636 process_queue (void)
6637 {
6638   struct dwarf2_queue_item *item, *next_item;
6639
6640   if (dwarf2_read_debug)
6641     {
6642       fprintf_unfiltered (gdb_stdlog,
6643                           "Expanding one or more symtabs of objfile %s ...\n",
6644                           dwarf2_per_objfile->objfile->name);
6645     }
6646
6647   /* The queue starts out with one item, but following a DIE reference
6648      may load a new CU, adding it to the end of the queue.  */
6649   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6650     {
6651       if (dwarf2_per_objfile->using_index
6652           ? !item->per_cu->v.quick->symtab
6653           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6654         {
6655           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6656
6657           if (dwarf2_read_debug)
6658             {
6659               fprintf_unfiltered (gdb_stdlog,
6660                                   "Expanding symtab of %s at offset 0x%x\n",
6661                                   per_cu->is_debug_types ? "TU" : "CU",
6662                                   per_cu->offset.sect_off);
6663             }
6664
6665           if (per_cu->is_debug_types)
6666             process_full_type_unit (per_cu, item->pretend_language);
6667           else
6668             process_full_comp_unit (per_cu, item->pretend_language);
6669
6670           if (dwarf2_read_debug)
6671             {
6672               fprintf_unfiltered (gdb_stdlog,
6673                                   "Done expanding %s at offset 0x%x\n",
6674                                   per_cu->is_debug_types ? "TU" : "CU",
6675                                   per_cu->offset.sect_off);
6676             }
6677         }
6678
6679       item->per_cu->queued = 0;
6680       next_item = item->next;
6681       xfree (item);
6682     }
6683
6684   dwarf2_queue_tail = NULL;
6685
6686   if (dwarf2_read_debug)
6687     {
6688       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6689                           dwarf2_per_objfile->objfile->name);
6690     }
6691 }
6692
6693 /* Free all allocated queue entries.  This function only releases anything if
6694    an error was thrown; if the queue was processed then it would have been
6695    freed as we went along.  */
6696
6697 static void
6698 dwarf2_release_queue (void *dummy)
6699 {
6700   struct dwarf2_queue_item *item, *last;
6701
6702   item = dwarf2_queue;
6703   while (item)
6704     {
6705       /* Anything still marked queued is likely to be in an
6706          inconsistent state, so discard it.  */
6707       if (item->per_cu->queued)
6708         {
6709           if (item->per_cu->cu != NULL)
6710             free_one_cached_comp_unit (item->per_cu);
6711           item->per_cu->queued = 0;
6712         }
6713
6714       last = item;
6715       item = item->next;
6716       xfree (last);
6717     }
6718
6719   dwarf2_queue = dwarf2_queue_tail = NULL;
6720 }
6721
6722 /* Read in full symbols for PST, and anything it depends on.  */
6723
6724 static void
6725 psymtab_to_symtab_1 (struct partial_symtab *pst)
6726 {
6727   struct dwarf2_per_cu_data *per_cu;
6728   int i;
6729
6730   if (pst->readin)
6731     return;
6732
6733   for (i = 0; i < pst->number_of_dependencies; i++)
6734     if (!pst->dependencies[i]->readin
6735         && pst->dependencies[i]->user == NULL)
6736       {
6737         /* Inform about additional files that need to be read in.  */
6738         if (info_verbose)
6739           {
6740             /* FIXME: i18n: Need to make this a single string.  */
6741             fputs_filtered (" ", gdb_stdout);
6742             wrap_here ("");
6743             fputs_filtered ("and ", gdb_stdout);
6744             wrap_here ("");
6745             printf_filtered ("%s...", pst->dependencies[i]->filename);
6746             wrap_here ("");     /* Flush output.  */
6747             gdb_flush (gdb_stdout);
6748           }
6749         psymtab_to_symtab_1 (pst->dependencies[i]);
6750       }
6751
6752   per_cu = pst->read_symtab_private;
6753
6754   if (per_cu == NULL)
6755     {
6756       /* It's an include file, no symbols to read for it.
6757          Everything is in the parent symtab.  */
6758       pst->readin = 1;
6759       return;
6760     }
6761
6762   dw2_do_instantiate_symtab (per_cu);
6763 }
6764
6765 /* Trivial hash function for die_info: the hash value of a DIE
6766    is its offset in .debug_info for this objfile.  */
6767
6768 static hashval_t
6769 die_hash (const void *item)
6770 {
6771   const struct die_info *die = item;
6772
6773   return die->offset.sect_off;
6774 }
6775
6776 /* Trivial comparison function for die_info structures: two DIEs
6777    are equal if they have the same offset.  */
6778
6779 static int
6780 die_eq (const void *item_lhs, const void *item_rhs)
6781 {
6782   const struct die_info *die_lhs = item_lhs;
6783   const struct die_info *die_rhs = item_rhs;
6784
6785   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6786 }
6787
6788 /* die_reader_func for load_full_comp_unit.
6789    This is identical to read_signatured_type_reader,
6790    but is kept separate for now.  */
6791
6792 static void
6793 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6794                             const gdb_byte *info_ptr,
6795                             struct die_info *comp_unit_die,
6796                             int has_children,
6797                             void *data)
6798 {
6799   struct dwarf2_cu *cu = reader->cu;
6800   enum language *language_ptr = data;
6801
6802   gdb_assert (cu->die_hash == NULL);
6803   cu->die_hash =
6804     htab_create_alloc_ex (cu->header.length / 12,
6805                           die_hash,
6806                           die_eq,
6807                           NULL,
6808                           &cu->comp_unit_obstack,
6809                           hashtab_obstack_allocate,
6810                           dummy_obstack_deallocate);
6811
6812   if (has_children)
6813     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6814                                                   &info_ptr, comp_unit_die);
6815   cu->dies = comp_unit_die;
6816   /* comp_unit_die is not stored in die_hash, no need.  */
6817
6818   /* We try not to read any attributes in this function, because not
6819      all CUs needed for references have been loaded yet, and symbol
6820      table processing isn't initialized.  But we have to set the CU language,
6821      or we won't be able to build types correctly.
6822      Similarly, if we do not read the producer, we can not apply
6823      producer-specific interpretation.  */
6824   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6825 }
6826
6827 /* Load the DIEs associated with PER_CU into memory.  */
6828
6829 static void
6830 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6831                      enum language pretend_language)
6832 {
6833   gdb_assert (! this_cu->is_debug_types);
6834
6835   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6836                            load_full_comp_unit_reader, &pretend_language);
6837 }
6838
6839 /* Add a DIE to the delayed physname list.  */
6840
6841 static void
6842 add_to_method_list (struct type *type, int fnfield_index, int index,
6843                     const char *name, struct die_info *die,
6844                     struct dwarf2_cu *cu)
6845 {
6846   struct delayed_method_info mi;
6847   mi.type = type;
6848   mi.fnfield_index = fnfield_index;
6849   mi.index = index;
6850   mi.name = name;
6851   mi.die = die;
6852   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6853 }
6854
6855 /* A cleanup for freeing the delayed method list.  */
6856
6857 static void
6858 free_delayed_list (void *ptr)
6859 {
6860   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6861   if (cu->method_list != NULL)
6862     {
6863       VEC_free (delayed_method_info, cu->method_list);
6864       cu->method_list = NULL;
6865     }
6866 }
6867
6868 /* Compute the physnames of any methods on the CU's method list.
6869
6870    The computation of method physnames is delayed in order to avoid the
6871    (bad) condition that one of the method's formal parameters is of an as yet
6872    incomplete type.  */
6873
6874 static void
6875 compute_delayed_physnames (struct dwarf2_cu *cu)
6876 {
6877   int i;
6878   struct delayed_method_info *mi;
6879   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6880     {
6881       const char *physname;
6882       struct fn_fieldlist *fn_flp
6883         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6884       physname = dwarf2_physname (mi->name, mi->die, cu);
6885       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6886     }
6887 }
6888
6889 /* Go objects should be embedded in a DW_TAG_module DIE,
6890    and it's not clear if/how imported objects will appear.
6891    To keep Go support simple until that's worked out,
6892    go back through what we've read and create something usable.
6893    We could do this while processing each DIE, and feels kinda cleaner,
6894    but that way is more invasive.
6895    This is to, for example, allow the user to type "p var" or "b main"
6896    without having to specify the package name, and allow lookups
6897    of module.object to work in contexts that use the expression
6898    parser.  */
6899
6900 static void
6901 fixup_go_packaging (struct dwarf2_cu *cu)
6902 {
6903   char *package_name = NULL;
6904   struct pending *list;
6905   int i;
6906
6907   for (list = global_symbols; list != NULL; list = list->next)
6908     {
6909       for (i = 0; i < list->nsyms; ++i)
6910         {
6911           struct symbol *sym = list->symbol[i];
6912
6913           if (SYMBOL_LANGUAGE (sym) == language_go
6914               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6915             {
6916               char *this_package_name = go_symbol_package_name (sym);
6917
6918               if (this_package_name == NULL)
6919                 continue;
6920               if (package_name == NULL)
6921                 package_name = this_package_name;
6922               else
6923                 {
6924                   if (strcmp (package_name, this_package_name) != 0)
6925                     complaint (&symfile_complaints,
6926                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6927                                (SYMBOL_SYMTAB (sym)
6928                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
6929                                 : cu->objfile->name),
6930                                this_package_name, package_name);
6931                   xfree (this_package_name);
6932                 }
6933             }
6934         }
6935     }
6936
6937   if (package_name != NULL)
6938     {
6939       struct objfile *objfile = cu->objfile;
6940       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6941                                                       package_name,
6942                                                       strlen (package_name));
6943       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6944                                      saved_package_name, objfile);
6945       struct symbol *sym;
6946
6947       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6948
6949       sym = allocate_symbol (objfile);
6950       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
6951       SYMBOL_SET_NAMES (sym, saved_package_name,
6952                         strlen (saved_package_name), 0, objfile);
6953       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6954          e.g., "main" finds the "main" module and not C's main().  */
6955       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6956       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
6957       SYMBOL_TYPE (sym) = type;
6958
6959       add_symbol_to_list (sym, &global_symbols);
6960
6961       xfree (package_name);
6962     }
6963 }
6964
6965 /* Return the symtab for PER_CU.  This works properly regardless of
6966    whether we're using the index or psymtabs.  */
6967
6968 static struct symtab *
6969 get_symtab (struct dwarf2_per_cu_data *per_cu)
6970 {
6971   return (dwarf2_per_objfile->using_index
6972           ? per_cu->v.quick->symtab
6973           : per_cu->v.psymtab->symtab);
6974 }
6975
6976 /* A helper function for computing the list of all symbol tables
6977    included by PER_CU.  */
6978
6979 static void
6980 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6981                                 htab_t all_children,
6982                                 struct dwarf2_per_cu_data *per_cu)
6983 {
6984   void **slot;
6985   int ix;
6986   struct dwarf2_per_cu_data *iter;
6987
6988   slot = htab_find_slot (all_children, per_cu, INSERT);
6989   if (*slot != NULL)
6990     {
6991       /* This inclusion and its children have been processed.  */
6992       return;
6993     }
6994
6995   *slot = per_cu;
6996   /* Only add a CU if it has a symbol table.  */
6997   if (get_symtab (per_cu) != NULL)
6998     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6999
7000   for (ix = 0;
7001        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7002        ++ix)
7003     recursively_compute_inclusions (result, all_children, iter);
7004 }
7005
7006 /* Compute the symtab 'includes' fields for the symtab related to
7007    PER_CU.  */
7008
7009 static void
7010 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7011 {
7012   gdb_assert (! per_cu->is_debug_types);
7013
7014   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7015     {
7016       int ix, len;
7017       struct dwarf2_per_cu_data *iter;
7018       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
7019       htab_t all_children;
7020       struct symtab *symtab = get_symtab (per_cu);
7021
7022       /* If we don't have a symtab, we can just skip this case.  */
7023       if (symtab == NULL)
7024         return;
7025
7026       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7027                                         NULL, xcalloc, xfree);
7028
7029       for (ix = 0;
7030            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7031                         ix, iter);
7032            ++ix)
7033         recursively_compute_inclusions (&result_children, all_children, iter);
7034
7035       /* Now we have a transitive closure of all the included CUs, and
7036          for .gdb_index version 7 the included TUs, so we can convert it
7037          to a list of symtabs.  */
7038       len = VEC_length (dwarf2_per_cu_ptr, result_children);
7039       symtab->includes
7040         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7041                          (len + 1) * sizeof (struct symtab *));
7042       for (ix = 0;
7043            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
7044            ++ix)
7045         symtab->includes[ix] = get_symtab (iter);
7046       symtab->includes[len] = NULL;
7047
7048       VEC_free (dwarf2_per_cu_ptr, result_children);
7049       htab_delete (all_children);
7050     }
7051 }
7052
7053 /* Compute the 'includes' field for the symtabs of all the CUs we just
7054    read.  */
7055
7056 static void
7057 process_cu_includes (void)
7058 {
7059   int ix;
7060   struct dwarf2_per_cu_data *iter;
7061
7062   for (ix = 0;
7063        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7064                     ix, iter);
7065        ++ix)
7066     {
7067       if (! iter->is_debug_types)
7068         compute_symtab_includes (iter);
7069     }
7070
7071   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7072 }
7073
7074 /* Generate full symbol information for PER_CU, whose DIEs have
7075    already been loaded into memory.  */
7076
7077 static void
7078 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7079                         enum language pretend_language)
7080 {
7081   struct dwarf2_cu *cu = per_cu->cu;
7082   struct objfile *objfile = per_cu->objfile;
7083   CORE_ADDR lowpc, highpc;
7084   struct symtab *symtab;
7085   struct cleanup *back_to, *delayed_list_cleanup;
7086   CORE_ADDR baseaddr;
7087   struct block *static_block;
7088
7089   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7090
7091   buildsym_init ();
7092   back_to = make_cleanup (really_free_pendings, NULL);
7093   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7094
7095   cu->list_in_scope = &file_symbols;
7096
7097   cu->language = pretend_language;
7098   cu->language_defn = language_def (cu->language);
7099
7100   /* Do line number decoding in read_file_scope () */
7101   process_die (cu->dies, cu);
7102
7103   /* For now fudge the Go package.  */
7104   if (cu->language == language_go)
7105     fixup_go_packaging (cu);
7106
7107   /* Now that we have processed all the DIEs in the CU, all the types 
7108      should be complete, and it should now be safe to compute all of the
7109      physnames.  */
7110   compute_delayed_physnames (cu);
7111   do_cleanups (delayed_list_cleanup);
7112
7113   /* Some compilers don't define a DW_AT_high_pc attribute for the
7114      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7115      it, by scanning the DIE's below the compilation unit.  */
7116   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7117
7118   static_block
7119     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
7120                                    per_cu->imported_symtabs != NULL);
7121
7122   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7123      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7124      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7125      addrmap to help ensure it has an accurate map of pc values belonging to
7126      this comp unit.  */
7127   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7128
7129   symtab = end_symtab_from_static_block (static_block, objfile,
7130                                          SECT_OFF_TEXT (objfile), 0);
7131
7132   if (symtab != NULL)
7133     {
7134       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7135
7136       /* Set symtab language to language from DW_AT_language.  If the
7137          compilation is from a C file generated by language preprocessors, do
7138          not set the language if it was already deduced by start_subfile.  */
7139       if (!(cu->language == language_c && symtab->language != language_c))
7140         symtab->language = cu->language;
7141
7142       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7143          produce DW_AT_location with location lists but it can be possibly
7144          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7145          there were bugs in prologue debug info, fixed later in GCC-4.5
7146          by "unwind info for epilogues" patch (which is not directly related).
7147
7148          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7149          needed, it would be wrong due to missing DW_AT_producer there.
7150
7151          Still one can confuse GDB by using non-standard GCC compilation
7152          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7153          */ 
7154       if (cu->has_loclist && gcc_4_minor >= 5)
7155         symtab->locations_valid = 1;
7156
7157       if (gcc_4_minor >= 5)
7158         symtab->epilogue_unwind_valid = 1;
7159
7160       symtab->call_site_htab = cu->call_site_htab;
7161     }
7162
7163   if (dwarf2_per_objfile->using_index)
7164     per_cu->v.quick->symtab = symtab;
7165   else
7166     {
7167       struct partial_symtab *pst = per_cu->v.psymtab;
7168       pst->symtab = symtab;
7169       pst->readin = 1;
7170     }
7171
7172   /* Push it for inclusion processing later.  */
7173   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7174
7175   do_cleanups (back_to);
7176 }
7177
7178 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7179    already been loaded into memory.  */
7180
7181 static void
7182 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7183                         enum language pretend_language)
7184 {
7185   struct dwarf2_cu *cu = per_cu->cu;
7186   struct objfile *objfile = per_cu->objfile;
7187   struct symtab *symtab;
7188   struct cleanup *back_to, *delayed_list_cleanup;
7189   struct signatured_type *sig_type;
7190
7191   gdb_assert (per_cu->is_debug_types);
7192   sig_type = (struct signatured_type *) per_cu;
7193
7194   buildsym_init ();
7195   back_to = make_cleanup (really_free_pendings, NULL);
7196   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7197
7198   cu->list_in_scope = &file_symbols;
7199
7200   cu->language = pretend_language;
7201   cu->language_defn = language_def (cu->language);
7202
7203   /* The symbol tables are set up in read_type_unit_scope.  */
7204   process_die (cu->dies, cu);
7205
7206   /* For now fudge the Go package.  */
7207   if (cu->language == language_go)
7208     fixup_go_packaging (cu);
7209
7210   /* Now that we have processed all the DIEs in the CU, all the types 
7211      should be complete, and it should now be safe to compute all of the
7212      physnames.  */
7213   compute_delayed_physnames (cu);
7214   do_cleanups (delayed_list_cleanup);
7215
7216   /* TUs share symbol tables.
7217      If this is the first TU to use this symtab, complete the construction
7218      of it with end_expandable_symtab.  Otherwise, complete the addition of
7219      this TU's symbols to the existing symtab.  */
7220   if (sig_type->type_unit_group->primary_symtab == NULL)
7221     {
7222       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7223       sig_type->type_unit_group->primary_symtab = symtab;
7224
7225       if (symtab != NULL)
7226         {
7227           /* Set symtab language to language from DW_AT_language.  If the
7228              compilation is from a C file generated by language preprocessors,
7229              do not set the language if it was already deduced by
7230              start_subfile.  */
7231           if (!(cu->language == language_c && symtab->language != language_c))
7232             symtab->language = cu->language;
7233         }
7234     }
7235   else
7236     {
7237       augment_type_symtab (objfile,
7238                            sig_type->type_unit_group->primary_symtab);
7239       symtab = sig_type->type_unit_group->primary_symtab;
7240     }
7241
7242   if (dwarf2_per_objfile->using_index)
7243     per_cu->v.quick->symtab = symtab;
7244   else
7245     {
7246       struct partial_symtab *pst = per_cu->v.psymtab;
7247       pst->symtab = symtab;
7248       pst->readin = 1;
7249     }
7250
7251   do_cleanups (back_to);
7252 }
7253
7254 /* Process an imported unit DIE.  */
7255
7256 static void
7257 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7258 {
7259   struct attribute *attr;
7260
7261   /* For now we don't handle imported units in type units.  */
7262   if (cu->per_cu->is_debug_types)
7263     {
7264       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7265                " supported in type units [in module %s]"),
7266              cu->objfile->name);
7267     }
7268
7269   attr = dwarf2_attr (die, DW_AT_import, cu);
7270   if (attr != NULL)
7271     {
7272       struct dwarf2_per_cu_data *per_cu;
7273       struct symtab *imported_symtab;
7274       sect_offset offset;
7275       int is_dwz;
7276
7277       offset = dwarf2_get_ref_die_offset (attr);
7278       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7279       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7280
7281       /* Queue the unit, if needed.  */
7282       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7283         load_full_comp_unit (per_cu, cu->language);
7284
7285       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7286                      per_cu);
7287     }
7288 }
7289
7290 /* Process a die and its children.  */
7291
7292 static void
7293 process_die (struct die_info *die, struct dwarf2_cu *cu)
7294 {
7295   switch (die->tag)
7296     {
7297     case DW_TAG_padding:
7298       break;
7299     case DW_TAG_compile_unit:
7300     case DW_TAG_partial_unit:
7301       read_file_scope (die, cu);
7302       break;
7303     case DW_TAG_type_unit:
7304       read_type_unit_scope (die, cu);
7305       break;
7306     case DW_TAG_subprogram:
7307     case DW_TAG_inlined_subroutine:
7308       read_func_scope (die, cu);
7309       break;
7310     case DW_TAG_lexical_block:
7311     case DW_TAG_try_block:
7312     case DW_TAG_catch_block:
7313       read_lexical_block_scope (die, cu);
7314       break;
7315     case DW_TAG_GNU_call_site:
7316       read_call_site_scope (die, cu);
7317       break;
7318     case DW_TAG_class_type:
7319     case DW_TAG_interface_type:
7320     case DW_TAG_structure_type:
7321     case DW_TAG_union_type:
7322       process_structure_scope (die, cu);
7323       break;
7324     case DW_TAG_enumeration_type:
7325       process_enumeration_scope (die, cu);
7326       break;
7327
7328     /* These dies have a type, but processing them does not create
7329        a symbol or recurse to process the children.  Therefore we can
7330        read them on-demand through read_type_die.  */
7331     case DW_TAG_subroutine_type:
7332     case DW_TAG_set_type:
7333     case DW_TAG_array_type:
7334     case DW_TAG_pointer_type:
7335     case DW_TAG_ptr_to_member_type:
7336     case DW_TAG_reference_type:
7337     case DW_TAG_string_type:
7338       break;
7339
7340     case DW_TAG_base_type:
7341     case DW_TAG_subrange_type:
7342     case DW_TAG_typedef:
7343       /* Add a typedef symbol for the type definition, if it has a
7344          DW_AT_name.  */
7345       new_symbol (die, read_type_die (die, cu), cu);
7346       break;
7347     case DW_TAG_common_block:
7348       read_common_block (die, cu);
7349       break;
7350     case DW_TAG_common_inclusion:
7351       break;
7352     case DW_TAG_namespace:
7353       cu->processing_has_namespace_info = 1;
7354       read_namespace (die, cu);
7355       break;
7356     case DW_TAG_module:
7357       cu->processing_has_namespace_info = 1;
7358       read_module (die, cu);
7359       break;
7360     case DW_TAG_imported_declaration:
7361     case DW_TAG_imported_module:
7362       cu->processing_has_namespace_info = 1;
7363       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7364                                  || cu->language != language_fortran))
7365         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7366                    dwarf_tag_name (die->tag));
7367       read_import_statement (die, cu);
7368       break;
7369
7370     case DW_TAG_imported_unit:
7371       process_imported_unit_die (die, cu);
7372       break;
7373
7374     default:
7375       new_symbol (die, NULL, cu);
7376       break;
7377     }
7378 }
7379 \f
7380 /* DWARF name computation.  */
7381
7382 /* A helper function for dwarf2_compute_name which determines whether DIE
7383    needs to have the name of the scope prepended to the name listed in the
7384    die.  */
7385
7386 static int
7387 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7388 {
7389   struct attribute *attr;
7390
7391   switch (die->tag)
7392     {
7393     case DW_TAG_namespace:
7394     case DW_TAG_typedef:
7395     case DW_TAG_class_type:
7396     case DW_TAG_interface_type:
7397     case DW_TAG_structure_type:
7398     case DW_TAG_union_type:
7399     case DW_TAG_enumeration_type:
7400     case DW_TAG_enumerator:
7401     case DW_TAG_subprogram:
7402     case DW_TAG_member:
7403       return 1;
7404
7405     case DW_TAG_variable:
7406     case DW_TAG_constant:
7407       /* We only need to prefix "globally" visible variables.  These include
7408          any variable marked with DW_AT_external or any variable that
7409          lives in a namespace.  [Variables in anonymous namespaces
7410          require prefixing, but they are not DW_AT_external.]  */
7411
7412       if (dwarf2_attr (die, DW_AT_specification, cu))
7413         {
7414           struct dwarf2_cu *spec_cu = cu;
7415
7416           return die_needs_namespace (die_specification (die, &spec_cu),
7417                                       spec_cu);
7418         }
7419
7420       attr = dwarf2_attr (die, DW_AT_external, cu);
7421       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7422           && die->parent->tag != DW_TAG_module)
7423         return 0;
7424       /* A variable in a lexical block of some kind does not need a
7425          namespace, even though in C++ such variables may be external
7426          and have a mangled name.  */
7427       if (die->parent->tag ==  DW_TAG_lexical_block
7428           || die->parent->tag ==  DW_TAG_try_block
7429           || die->parent->tag ==  DW_TAG_catch_block
7430           || die->parent->tag == DW_TAG_subprogram)
7431         return 0;
7432       return 1;
7433
7434     default:
7435       return 0;
7436     }
7437 }
7438
7439 /* Retrieve the last character from a mem_file.  */
7440
7441 static void
7442 do_ui_file_peek_last (void *object, const char *buffer, long length)
7443 {
7444   char *last_char_p = (char *) object;
7445
7446   if (length > 0)
7447     *last_char_p = buffer[length - 1];
7448 }
7449
7450 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7451    compute the physname for the object, which include a method's:
7452    - formal parameters (C++/Java),
7453    - receiver type (Go),
7454    - return type (Java).
7455
7456    The term "physname" is a bit confusing.
7457    For C++, for example, it is the demangled name.
7458    For Go, for example, it's the mangled name.
7459
7460    For Ada, return the DIE's linkage name rather than the fully qualified
7461    name.  PHYSNAME is ignored..
7462
7463    The result is allocated on the objfile_obstack and canonicalized.  */
7464
7465 static const char *
7466 dwarf2_compute_name (const char *name,
7467                      struct die_info *die, struct dwarf2_cu *cu,
7468                      int physname)
7469 {
7470   struct objfile *objfile = cu->objfile;
7471
7472   if (name == NULL)
7473     name = dwarf2_name (die, cu);
7474
7475   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7476      compute it by typename_concat inside GDB.  */
7477   if (cu->language == language_ada
7478       || (cu->language == language_fortran && physname))
7479     {
7480       /* For Ada unit, we prefer the linkage name over the name, as
7481          the former contains the exported name, which the user expects
7482          to be able to reference.  Ideally, we want the user to be able
7483          to reference this entity using either natural or linkage name,
7484          but we haven't started looking at this enhancement yet.  */
7485       struct attribute *attr;
7486
7487       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7488       if (attr == NULL)
7489         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7490       if (attr && DW_STRING (attr))
7491         return DW_STRING (attr);
7492     }
7493
7494   /* These are the only languages we know how to qualify names in.  */
7495   if (name != NULL
7496       && (cu->language == language_cplus || cu->language == language_java
7497           || cu->language == language_fortran))
7498     {
7499       if (die_needs_namespace (die, cu))
7500         {
7501           long length;
7502           const char *prefix;
7503           struct ui_file *buf;
7504
7505           prefix = determine_prefix (die, cu);
7506           buf = mem_fileopen ();
7507           if (*prefix != '\0')
7508             {
7509               char *prefixed_name = typename_concat (NULL, prefix, name,
7510                                                      physname, cu);
7511
7512               fputs_unfiltered (prefixed_name, buf);
7513               xfree (prefixed_name);
7514             }
7515           else
7516             fputs_unfiltered (name, buf);
7517
7518           /* Template parameters may be specified in the DIE's DW_AT_name, or
7519              as children with DW_TAG_template_type_param or
7520              DW_TAG_value_type_param.  If the latter, add them to the name
7521              here.  If the name already has template parameters, then
7522              skip this step; some versions of GCC emit both, and
7523              it is more efficient to use the pre-computed name.
7524
7525              Something to keep in mind about this process: it is very
7526              unlikely, or in some cases downright impossible, to produce
7527              something that will match the mangled name of a function.
7528              If the definition of the function has the same debug info,
7529              we should be able to match up with it anyway.  But fallbacks
7530              using the minimal symbol, for instance to find a method
7531              implemented in a stripped copy of libstdc++, will not work.
7532              If we do not have debug info for the definition, we will have to
7533              match them up some other way.
7534
7535              When we do name matching there is a related problem with function
7536              templates; two instantiated function templates are allowed to
7537              differ only by their return types, which we do not add here.  */
7538
7539           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7540             {
7541               struct attribute *attr;
7542               struct die_info *child;
7543               int first = 1;
7544
7545               die->building_fullname = 1;
7546
7547               for (child = die->child; child != NULL; child = child->sibling)
7548                 {
7549                   struct type *type;
7550                   LONGEST value;
7551                   const gdb_byte *bytes;
7552                   struct dwarf2_locexpr_baton *baton;
7553                   struct value *v;
7554
7555                   if (child->tag != DW_TAG_template_type_param
7556                       && child->tag != DW_TAG_template_value_param)
7557                     continue;
7558
7559                   if (first)
7560                     {
7561                       fputs_unfiltered ("<", buf);
7562                       first = 0;
7563                     }
7564                   else
7565                     fputs_unfiltered (", ", buf);
7566
7567                   attr = dwarf2_attr (child, DW_AT_type, cu);
7568                   if (attr == NULL)
7569                     {
7570                       complaint (&symfile_complaints,
7571                                  _("template parameter missing DW_AT_type"));
7572                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7573                       continue;
7574                     }
7575                   type = die_type (child, cu);
7576
7577                   if (child->tag == DW_TAG_template_type_param)
7578                     {
7579                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7580                       continue;
7581                     }
7582
7583                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7584                   if (attr == NULL)
7585                     {
7586                       complaint (&symfile_complaints,
7587                                  _("template parameter missing "
7588                                    "DW_AT_const_value"));
7589                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7590                       continue;
7591                     }
7592
7593                   dwarf2_const_value_attr (attr, type, name,
7594                                            &cu->comp_unit_obstack, cu,
7595                                            &value, &bytes, &baton);
7596
7597                   if (TYPE_NOSIGN (type))
7598                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7599                        changed, this can use value_print instead.  */
7600                     c_printchar (value, type, buf);
7601                   else
7602                     {
7603                       struct value_print_options opts;
7604
7605                       if (baton != NULL)
7606                         v = dwarf2_evaluate_loc_desc (type, NULL,
7607                                                       baton->data,
7608                                                       baton->size,
7609                                                       baton->per_cu);
7610                       else if (bytes != NULL)
7611                         {
7612                           v = allocate_value (type);
7613                           memcpy (value_contents_writeable (v), bytes,
7614                                   TYPE_LENGTH (type));
7615                         }
7616                       else
7617                         v = value_from_longest (type, value);
7618
7619                       /* Specify decimal so that we do not depend on
7620                          the radix.  */
7621                       get_formatted_print_options (&opts, 'd');
7622                       opts.raw = 1;
7623                       value_print (v, buf, &opts);
7624                       release_value (v);
7625                       value_free (v);
7626                     }
7627                 }
7628
7629               die->building_fullname = 0;
7630
7631               if (!first)
7632                 {
7633                   /* Close the argument list, with a space if necessary
7634                      (nested templates).  */
7635                   char last_char = '\0';
7636                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7637                   if (last_char == '>')
7638                     fputs_unfiltered (" >", buf);
7639                   else
7640                     fputs_unfiltered (">", buf);
7641                 }
7642             }
7643
7644           /* For Java and C++ methods, append formal parameter type
7645              information, if PHYSNAME.  */
7646
7647           if (physname && die->tag == DW_TAG_subprogram
7648               && (cu->language == language_cplus
7649                   || cu->language == language_java))
7650             {
7651               struct type *type = read_type_die (die, cu);
7652
7653               c_type_print_args (type, buf, 1, cu->language,
7654                                  &type_print_raw_options);
7655
7656               if (cu->language == language_java)
7657                 {
7658                   /* For java, we must append the return type to method
7659                      names.  */
7660                   if (die->tag == DW_TAG_subprogram)
7661                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7662                                      0, 0, &type_print_raw_options);
7663                 }
7664               else if (cu->language == language_cplus)
7665                 {
7666                   /* Assume that an artificial first parameter is
7667                      "this", but do not crash if it is not.  RealView
7668                      marks unnamed (and thus unused) parameters as
7669                      artificial; there is no way to differentiate
7670                      the two cases.  */
7671                   if (TYPE_NFIELDS (type) > 0
7672                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7673                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7674                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7675                                                                         0))))
7676                     fputs_unfiltered (" const", buf);
7677                 }
7678             }
7679
7680           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7681                                        &length);
7682           ui_file_delete (buf);
7683
7684           if (cu->language == language_cplus)
7685             {
7686               const char *cname
7687                 = dwarf2_canonicalize_name (name, cu,
7688                                             &objfile->objfile_obstack);
7689
7690               if (cname != NULL)
7691                 name = cname;
7692             }
7693         }
7694     }
7695
7696   return name;
7697 }
7698
7699 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7700    If scope qualifiers are appropriate they will be added.  The result
7701    will be allocated on the objfile_obstack, or NULL if the DIE does
7702    not have a name.  NAME may either be from a previous call to
7703    dwarf2_name or NULL.
7704
7705    The output string will be canonicalized (if C++/Java).  */
7706
7707 static const char *
7708 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7709 {
7710   return dwarf2_compute_name (name, die, cu, 0);
7711 }
7712
7713 /* Construct a physname for the given DIE in CU.  NAME may either be
7714    from a previous call to dwarf2_name or NULL.  The result will be
7715    allocated on the objfile_objstack or NULL if the DIE does not have a
7716    name.
7717
7718    The output string will be canonicalized (if C++/Java).  */
7719
7720 static const char *
7721 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7722 {
7723   struct objfile *objfile = cu->objfile;
7724   struct attribute *attr;
7725   const char *retval, *mangled = NULL, *canon = NULL;
7726   struct cleanup *back_to;
7727   int need_copy = 1;
7728
7729   /* In this case dwarf2_compute_name is just a shortcut not building anything
7730      on its own.  */
7731   if (!die_needs_namespace (die, cu))
7732     return dwarf2_compute_name (name, die, cu, 1);
7733
7734   back_to = make_cleanup (null_cleanup, NULL);
7735
7736   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7737   if (!attr)
7738     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7739
7740   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7741      has computed.  */
7742   if (attr && DW_STRING (attr))
7743     {
7744       char *demangled;
7745
7746       mangled = DW_STRING (attr);
7747
7748       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7749          type.  It is easier for GDB users to search for such functions as
7750          `name(params)' than `long name(params)'.  In such case the minimal
7751          symbol names do not match the full symbol names but for template
7752          functions there is never a need to look up their definition from their
7753          declaration so the only disadvantage remains the minimal symbol
7754          variant `long name(params)' does not have the proper inferior type.
7755          */
7756
7757       if (cu->language == language_go)
7758         {
7759           /* This is a lie, but we already lie to the caller new_symbol_full.
7760              new_symbol_full assumes we return the mangled name.
7761              This just undoes that lie until things are cleaned up.  */
7762           demangled = NULL;
7763         }
7764       else
7765         {
7766           demangled = gdb_demangle (mangled,
7767                                     (DMGL_PARAMS | DMGL_ANSI
7768                                      | (cu->language == language_java
7769                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
7770                                         : DMGL_RET_DROP)));
7771         }
7772       if (demangled)
7773         {
7774           make_cleanup (xfree, demangled);
7775           canon = demangled;
7776         }
7777       else
7778         {
7779           canon = mangled;
7780           need_copy = 0;
7781         }
7782     }
7783
7784   if (canon == NULL || check_physname)
7785     {
7786       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7787
7788       if (canon != NULL && strcmp (physname, canon) != 0)
7789         {
7790           /* It may not mean a bug in GDB.  The compiler could also
7791              compute DW_AT_linkage_name incorrectly.  But in such case
7792              GDB would need to be bug-to-bug compatible.  */
7793
7794           complaint (&symfile_complaints,
7795                      _("Computed physname <%s> does not match demangled <%s> "
7796                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7797                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7798
7799           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7800              is available here - over computed PHYSNAME.  It is safer
7801              against both buggy GDB and buggy compilers.  */
7802
7803           retval = canon;
7804         }
7805       else
7806         {
7807           retval = physname;
7808           need_copy = 0;
7809         }
7810     }
7811   else
7812     retval = canon;
7813
7814   if (need_copy)
7815     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7816
7817   do_cleanups (back_to);
7818   return retval;
7819 }
7820
7821 /* Read the import statement specified by the given die and record it.  */
7822
7823 static void
7824 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7825 {
7826   struct objfile *objfile = cu->objfile;
7827   struct attribute *import_attr;
7828   struct die_info *imported_die, *child_die;
7829   struct dwarf2_cu *imported_cu;
7830   const char *imported_name;
7831   const char *imported_name_prefix;
7832   const char *canonical_name;
7833   const char *import_alias;
7834   const char *imported_declaration = NULL;
7835   const char *import_prefix;
7836   VEC (const_char_ptr) *excludes = NULL;
7837   struct cleanup *cleanups;
7838
7839   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7840   if (import_attr == NULL)
7841     {
7842       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7843                  dwarf_tag_name (die->tag));
7844       return;
7845     }
7846
7847   imported_cu = cu;
7848   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7849   imported_name = dwarf2_name (imported_die, imported_cu);
7850   if (imported_name == NULL)
7851     {
7852       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7853
7854         The import in the following code:
7855         namespace A
7856           {
7857             typedef int B;
7858           }
7859
7860         int main ()
7861           {
7862             using A::B;
7863             B b;
7864             return b;
7865           }
7866
7867         ...
7868          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7869             <52>   DW_AT_decl_file   : 1
7870             <53>   DW_AT_decl_line   : 6
7871             <54>   DW_AT_import      : <0x75>
7872          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7873             <59>   DW_AT_name        : B
7874             <5b>   DW_AT_decl_file   : 1
7875             <5c>   DW_AT_decl_line   : 2
7876             <5d>   DW_AT_type        : <0x6e>
7877         ...
7878          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7879             <76>   DW_AT_byte_size   : 4
7880             <77>   DW_AT_encoding    : 5        (signed)
7881
7882         imports the wrong die ( 0x75 instead of 0x58 ).
7883         This case will be ignored until the gcc bug is fixed.  */
7884       return;
7885     }
7886
7887   /* Figure out the local name after import.  */
7888   import_alias = dwarf2_name (die, cu);
7889
7890   /* Figure out where the statement is being imported to.  */
7891   import_prefix = determine_prefix (die, cu);
7892
7893   /* Figure out what the scope of the imported die is and prepend it
7894      to the name of the imported die.  */
7895   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7896
7897   if (imported_die->tag != DW_TAG_namespace
7898       && imported_die->tag != DW_TAG_module)
7899     {
7900       imported_declaration = imported_name;
7901       canonical_name = imported_name_prefix;
7902     }
7903   else if (strlen (imported_name_prefix) > 0)
7904     canonical_name = obconcat (&objfile->objfile_obstack,
7905                                imported_name_prefix, "::", imported_name,
7906                                (char *) NULL);
7907   else
7908     canonical_name = imported_name;
7909
7910   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7911
7912   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7913     for (child_die = die->child; child_die && child_die->tag;
7914          child_die = sibling_die (child_die))
7915       {
7916         /* DWARF-4: A Fortran use statement with a “rename list” may be
7917            represented by an imported module entry with an import attribute
7918            referring to the module and owned entries corresponding to those
7919            entities that are renamed as part of being imported.  */
7920
7921         if (child_die->tag != DW_TAG_imported_declaration)
7922           {
7923             complaint (&symfile_complaints,
7924                        _("child DW_TAG_imported_declaration expected "
7925                          "- DIE at 0x%x [in module %s]"),
7926                        child_die->offset.sect_off, objfile->name);
7927             continue;
7928           }
7929
7930         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7931         if (import_attr == NULL)
7932           {
7933             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7934                        dwarf_tag_name (child_die->tag));
7935             continue;
7936           }
7937
7938         imported_cu = cu;
7939         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7940                                               &imported_cu);
7941         imported_name = dwarf2_name (imported_die, imported_cu);
7942         if (imported_name == NULL)
7943           {
7944             complaint (&symfile_complaints,
7945                        _("child DW_TAG_imported_declaration has unknown "
7946                          "imported name - DIE at 0x%x [in module %s]"),
7947                        child_die->offset.sect_off, objfile->name);
7948             continue;
7949           }
7950
7951         VEC_safe_push (const_char_ptr, excludes, imported_name);
7952
7953         process_die (child_die, cu);
7954       }
7955
7956   cp_add_using_directive (import_prefix,
7957                           canonical_name,
7958                           import_alias,
7959                           imported_declaration,
7960                           excludes,
7961                           0,
7962                           &objfile->objfile_obstack);
7963
7964   do_cleanups (cleanups);
7965 }
7966
7967 /* Cleanup function for handle_DW_AT_stmt_list.  */
7968
7969 static void
7970 free_cu_line_header (void *arg)
7971 {
7972   struct dwarf2_cu *cu = arg;
7973
7974   free_line_header (cu->line_header);
7975   cu->line_header = NULL;
7976 }
7977
7978 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7979    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7980    this, it was first present in GCC release 4.3.0.  */
7981
7982 static int
7983 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7984 {
7985   if (!cu->checked_producer)
7986     check_producer (cu);
7987
7988   return cu->producer_is_gcc_lt_4_3;
7989 }
7990
7991 static void
7992 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7993                          const char **name, const char **comp_dir)
7994 {
7995   struct attribute *attr;
7996
7997   *name = NULL;
7998   *comp_dir = NULL;
7999
8000   /* Find the filename.  Do not use dwarf2_name here, since the filename
8001      is not a source language identifier.  */
8002   attr = dwarf2_attr (die, DW_AT_name, cu);
8003   if (attr)
8004     {
8005       *name = DW_STRING (attr);
8006     }
8007
8008   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8009   if (attr)
8010     *comp_dir = DW_STRING (attr);
8011   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8012            && IS_ABSOLUTE_PATH (*name))
8013     {
8014       char *d = ldirname (*name);
8015
8016       *comp_dir = d;
8017       if (d != NULL)
8018         make_cleanup (xfree, d);
8019     }
8020   if (*comp_dir != NULL)
8021     {
8022       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8023          directory, get rid of it.  */
8024       char *cp = strchr (*comp_dir, ':');
8025
8026       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8027         *comp_dir = cp + 1;
8028     }
8029
8030   if (*name == NULL)
8031     *name = "<unknown>";
8032 }
8033
8034 /* Handle DW_AT_stmt_list for a compilation unit.
8035    DIE is the DW_TAG_compile_unit die for CU.
8036    COMP_DIR is the compilation directory.
8037    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8038
8039 static void
8040 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8041                         const char *comp_dir)
8042 {
8043   struct attribute *attr;
8044
8045   gdb_assert (! cu->per_cu->is_debug_types);
8046
8047   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8048   if (attr)
8049     {
8050       unsigned int line_offset = DW_UNSND (attr);
8051       struct line_header *line_header
8052         = dwarf_decode_line_header (line_offset, cu);
8053
8054       if (line_header)
8055         {
8056           cu->line_header = line_header;
8057           make_cleanup (free_cu_line_header, cu);
8058           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8059         }
8060     }
8061 }
8062
8063 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8064
8065 static void
8066 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8067 {
8068   struct objfile *objfile = dwarf2_per_objfile->objfile;
8069   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8070   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8071   CORE_ADDR highpc = ((CORE_ADDR) 0);
8072   struct attribute *attr;
8073   const char *name = NULL;
8074   const char *comp_dir = NULL;
8075   struct die_info *child_die;
8076   bfd *abfd = objfile->obfd;
8077   CORE_ADDR baseaddr;
8078
8079   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8080
8081   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8082
8083   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8084      from finish_block.  */
8085   if (lowpc == ((CORE_ADDR) -1))
8086     lowpc = highpc;
8087   lowpc += baseaddr;
8088   highpc += baseaddr;
8089
8090   find_file_and_directory (die, cu, &name, &comp_dir);
8091
8092   prepare_one_comp_unit (cu, die, cu->language);
8093
8094   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8095      standardised yet.  As a workaround for the language detection we fall
8096      back to the DW_AT_producer string.  */
8097   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8098     cu->language = language_opencl;
8099
8100   /* Similar hack for Go.  */
8101   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8102     set_cu_language (DW_LANG_Go, cu);
8103
8104   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8105
8106   /* Decode line number information if present.  We do this before
8107      processing child DIEs, so that the line header table is available
8108      for DW_AT_decl_file.  */
8109   handle_DW_AT_stmt_list (die, cu, comp_dir);
8110
8111   /* Process all dies in compilation unit.  */
8112   if (die->child != NULL)
8113     {
8114       child_die = die->child;
8115       while (child_die && child_die->tag)
8116         {
8117           process_die (child_die, cu);
8118           child_die = sibling_die (child_die);
8119         }
8120     }
8121
8122   /* Decode macro information, if present.  Dwarf 2 macro information
8123      refers to information in the line number info statement program
8124      header, so we can only read it if we've read the header
8125      successfully.  */
8126   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8127   if (attr && cu->line_header)
8128     {
8129       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8130         complaint (&symfile_complaints,
8131                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8132
8133       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8134     }
8135   else
8136     {
8137       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8138       if (attr && cu->line_header)
8139         {
8140           unsigned int macro_offset = DW_UNSND (attr);
8141
8142           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8143         }
8144     }
8145
8146   do_cleanups (back_to);
8147 }
8148
8149 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8150    Create the set of symtabs used by this TU, or if this TU is sharing
8151    symtabs with another TU and the symtabs have already been created
8152    then restore those symtabs in the line header.
8153    We don't need the pc/line-number mapping for type units.  */
8154
8155 static void
8156 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8157 {
8158   struct objfile *objfile = dwarf2_per_objfile->objfile;
8159   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8160   struct type_unit_group *tu_group;
8161   int first_time;
8162   struct line_header *lh;
8163   struct attribute *attr;
8164   unsigned int i, line_offset;
8165   struct signatured_type *sig_type;
8166
8167   gdb_assert (per_cu->is_debug_types);
8168   sig_type = (struct signatured_type *) per_cu;
8169
8170   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8171
8172   /* If we're using .gdb_index (includes -readnow) then
8173      per_cu->s.type_unit_group may not have been set up yet.  */
8174   if (sig_type->type_unit_group == NULL)
8175     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8176   tu_group = sig_type->type_unit_group;
8177
8178   /* If we've already processed this stmt_list there's no real need to
8179      do it again, we could fake it and just recreate the part we need
8180      (file name,index -> symtab mapping).  If data shows this optimization
8181      is useful we can do it then.  */
8182   first_time = tu_group->primary_symtab == NULL;
8183
8184   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8185      debug info.  */
8186   lh = NULL;
8187   if (attr != NULL)
8188     {
8189       line_offset = DW_UNSND (attr);
8190       lh = dwarf_decode_line_header (line_offset, cu);
8191     }
8192   if (lh == NULL)
8193     {
8194       if (first_time)
8195         dwarf2_start_symtab (cu, "", NULL, 0);
8196       else
8197         {
8198           gdb_assert (tu_group->symtabs == NULL);
8199           restart_symtab (0);
8200         }
8201       /* Note: The primary symtab will get allocated at the end.  */
8202       return;
8203     }
8204
8205   cu->line_header = lh;
8206   make_cleanup (free_cu_line_header, cu);
8207
8208   if (first_time)
8209     {
8210       dwarf2_start_symtab (cu, "", NULL, 0);
8211
8212       tu_group->num_symtabs = lh->num_file_names;
8213       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8214
8215       for (i = 0; i < lh->num_file_names; ++i)
8216         {
8217           const char *dir = NULL;
8218           struct file_entry *fe = &lh->file_names[i];
8219
8220           if (fe->dir_index)
8221             dir = lh->include_dirs[fe->dir_index - 1];
8222           dwarf2_start_subfile (fe->name, dir, NULL);
8223
8224           /* Note: We don't have to watch for the main subfile here, type units
8225              don't have DW_AT_name.  */
8226
8227           if (current_subfile->symtab == NULL)
8228             {
8229               /* NOTE: start_subfile will recognize when it's been passed
8230                  a file it has already seen.  So we can't assume there's a
8231                  simple mapping from lh->file_names to subfiles,
8232                  lh->file_names may contain dups.  */
8233               current_subfile->symtab = allocate_symtab (current_subfile->name,
8234                                                          objfile);
8235             }
8236
8237           fe->symtab = current_subfile->symtab;
8238           tu_group->symtabs[i] = fe->symtab;
8239         }
8240     }
8241   else
8242     {
8243       restart_symtab (0);
8244
8245       for (i = 0; i < lh->num_file_names; ++i)
8246         {
8247           struct file_entry *fe = &lh->file_names[i];
8248
8249           fe->symtab = tu_group->symtabs[i];
8250         }
8251     }
8252
8253   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8254      so they don't have a "real" (so to speak) symtab anyway.
8255      There is later code that will assign the main symtab to all symbols
8256      that don't have one.  We need to handle the case of a symbol with a
8257      missing symtab (DW_AT_decl_file) anyway.  */
8258 }
8259
8260 /* Process DW_TAG_type_unit.
8261    For TUs we want to skip the first top level sibling if it's not the
8262    actual type being defined by this TU.  In this case the first top
8263    level sibling is there to provide context only.  */
8264
8265 static void
8266 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8267 {
8268   struct die_info *child_die;
8269
8270   prepare_one_comp_unit (cu, die, language_minimal);
8271
8272   /* Initialize (or reinitialize) the machinery for building symtabs.
8273      We do this before processing child DIEs, so that the line header table
8274      is available for DW_AT_decl_file.  */
8275   setup_type_unit_groups (die, cu);
8276
8277   if (die->child != NULL)
8278     {
8279       child_die = die->child;
8280       while (child_die && child_die->tag)
8281         {
8282           process_die (child_die, cu);
8283           child_die = sibling_die (child_die);
8284         }
8285     }
8286 }
8287 \f
8288 /* DWO/DWP files.
8289
8290    http://gcc.gnu.org/wiki/DebugFission
8291    http://gcc.gnu.org/wiki/DebugFissionDWP
8292
8293    To simplify handling of both DWO files ("object" files with the DWARF info)
8294    and DWP files (a file with the DWOs packaged up into one file), we treat
8295    DWP files as having a collection of virtual DWO files.  */
8296
8297 static hashval_t
8298 hash_dwo_file (const void *item)
8299 {
8300   const struct dwo_file *dwo_file = item;
8301
8302   return (htab_hash_string (dwo_file->dwo_name)
8303           + htab_hash_string (dwo_file->comp_dir));
8304 }
8305
8306 static int
8307 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8308 {
8309   const struct dwo_file *lhs = item_lhs;
8310   const struct dwo_file *rhs = item_rhs;
8311
8312   return (strcmp (lhs->dwo_name, rhs->dwo_name) == 0
8313           && strcmp (lhs->comp_dir, rhs->comp_dir) == 0);
8314 }
8315
8316 /* Allocate a hash table for DWO files.  */
8317
8318 static htab_t
8319 allocate_dwo_file_hash_table (void)
8320 {
8321   struct objfile *objfile = dwarf2_per_objfile->objfile;
8322
8323   return htab_create_alloc_ex (41,
8324                                hash_dwo_file,
8325                                eq_dwo_file,
8326                                NULL,
8327                                &objfile->objfile_obstack,
8328                                hashtab_obstack_allocate,
8329                                dummy_obstack_deallocate);
8330 }
8331
8332 /* Lookup DWO file DWO_NAME.  */
8333
8334 static void **
8335 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8336 {
8337   struct dwo_file find_entry;
8338   void **slot;
8339
8340   if (dwarf2_per_objfile->dwo_files == NULL)
8341     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8342
8343   memset (&find_entry, 0, sizeof (find_entry));
8344   find_entry.dwo_name = dwo_name;
8345   find_entry.comp_dir = comp_dir;
8346   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8347
8348   return slot;
8349 }
8350
8351 static hashval_t
8352 hash_dwo_unit (const void *item)
8353 {
8354   const struct dwo_unit *dwo_unit = item;
8355
8356   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8357   return dwo_unit->signature;
8358 }
8359
8360 static int
8361 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8362 {
8363   const struct dwo_unit *lhs = item_lhs;
8364   const struct dwo_unit *rhs = item_rhs;
8365
8366   /* The signature is assumed to be unique within the DWO file.
8367      So while object file CU dwo_id's always have the value zero,
8368      that's OK, assuming each object file DWO file has only one CU,
8369      and that's the rule for now.  */
8370   return lhs->signature == rhs->signature;
8371 }
8372
8373 /* Allocate a hash table for DWO CUs,TUs.
8374    There is one of these tables for each of CUs,TUs for each DWO file.  */
8375
8376 static htab_t
8377 allocate_dwo_unit_table (struct objfile *objfile)
8378 {
8379   /* Start out with a pretty small number.
8380      Generally DWO files contain only one CU and maybe some TUs.  */
8381   return htab_create_alloc_ex (3,
8382                                hash_dwo_unit,
8383                                eq_dwo_unit,
8384                                NULL,
8385                                &objfile->objfile_obstack,
8386                                hashtab_obstack_allocate,
8387                                dummy_obstack_deallocate);
8388 }
8389
8390 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8391
8392 struct create_dwo_info_table_data
8393 {
8394   struct dwo_file *dwo_file;
8395   htab_t cu_htab;
8396 };
8397
8398 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8399
8400 static void
8401 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8402                                          const gdb_byte *info_ptr,
8403                                          struct die_info *comp_unit_die,
8404                                          int has_children,
8405                                          void *datap)
8406 {
8407   struct dwarf2_cu *cu = reader->cu;
8408   struct objfile *objfile = dwarf2_per_objfile->objfile;
8409   sect_offset offset = cu->per_cu->offset;
8410   struct dwarf2_section_info *section = cu->per_cu->section;
8411   struct create_dwo_info_table_data *data = datap;
8412   struct dwo_file *dwo_file = data->dwo_file;
8413   htab_t cu_htab = data->cu_htab;
8414   void **slot;
8415   struct attribute *attr;
8416   struct dwo_unit *dwo_unit;
8417
8418   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8419   if (attr == NULL)
8420     {
8421       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8422                " its dwo_id [in module %s]"),
8423              offset.sect_off, dwo_file->dwo_name);
8424       return;
8425     }
8426
8427   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8428   dwo_unit->dwo_file = dwo_file;
8429   dwo_unit->signature = DW_UNSND (attr);
8430   dwo_unit->section = section;
8431   dwo_unit->offset = offset;
8432   dwo_unit->length = cu->per_cu->length;
8433
8434   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8435   gdb_assert (slot != NULL);
8436   if (*slot != NULL)
8437     {
8438       const struct dwo_unit *dup_dwo_unit = *slot;
8439
8440       complaint (&symfile_complaints,
8441                  _("debug entry at offset 0x%x is duplicate to the entry at"
8442                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8443                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8444                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8445                  dwo_file->dwo_name);
8446     }
8447   else
8448     *slot = dwo_unit;
8449
8450   if (dwarf2_read_debug)
8451     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8452                         offset.sect_off,
8453                         phex (dwo_unit->signature,
8454                               sizeof (dwo_unit->signature)));
8455 }
8456
8457 /* Create a hash table to map DWO IDs to their CU entry in
8458    .debug_info.dwo in DWO_FILE.
8459    Note: This function processes DWO files only, not DWP files.
8460    Note: A DWO file generally contains one CU, but we don't assume this.  */
8461
8462 static htab_t
8463 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8464 {
8465   struct objfile *objfile = dwarf2_per_objfile->objfile;
8466   struct dwarf2_section_info *section = &dwo_file->sections.info;
8467   bfd *abfd;
8468   htab_t cu_htab;
8469   const gdb_byte *info_ptr, *end_ptr;
8470   struct create_dwo_info_table_data create_dwo_info_table_data;
8471
8472   dwarf2_read_section (objfile, section);
8473   info_ptr = section->buffer;
8474
8475   if (info_ptr == NULL)
8476     return NULL;
8477
8478   /* We can't set abfd until now because the section may be empty or
8479      not present, in which case section->asection will be NULL.  */
8480   abfd = section->asection->owner;
8481
8482   if (dwarf2_read_debug)
8483     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8484                         bfd_get_filename (abfd));
8485
8486   cu_htab = allocate_dwo_unit_table (objfile);
8487
8488   create_dwo_info_table_data.dwo_file = dwo_file;
8489   create_dwo_info_table_data.cu_htab = cu_htab;
8490
8491   end_ptr = info_ptr + section->size;
8492   while (info_ptr < end_ptr)
8493     {
8494       struct dwarf2_per_cu_data per_cu;
8495
8496       memset (&per_cu, 0, sizeof (per_cu));
8497       per_cu.objfile = objfile;
8498       per_cu.is_debug_types = 0;
8499       per_cu.offset.sect_off = info_ptr - section->buffer;
8500       per_cu.section = section;
8501
8502       init_cutu_and_read_dies_no_follow (&per_cu,
8503                                          &dwo_file->sections.abbrev,
8504                                          dwo_file,
8505                                          create_dwo_debug_info_hash_table_reader,
8506                                          &create_dwo_info_table_data);
8507
8508       info_ptr += per_cu.length;
8509     }
8510
8511   return cu_htab;
8512 }
8513
8514 /* DWP file .debug_{cu,tu}_index section format:
8515    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8516
8517    Both index sections have the same format, and serve to map a 64-bit
8518    signature to a set of section numbers.  Each section begins with a header,
8519    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8520    indexes, and a pool of 32-bit section numbers.  The index sections will be
8521    aligned at 8-byte boundaries in the file.
8522
8523    The index section header contains two unsigned 32-bit values (using the
8524    byte order of the application binary):
8525
8526     N, the number of compilation units or type units in the index
8527     M, the number of slots in the hash table
8528
8529   (We assume that N and M will not exceed 2^32 - 1.)
8530
8531   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8532
8533   The hash table begins at offset 8 in the section, and consists of an array
8534   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8535   order of the application binary).  Unused slots in the hash table are 0.
8536   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8537
8538   The parallel table begins immediately after the hash table
8539   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8540   array of 32-bit indexes (using the byte order of the application binary),
8541   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8542   table contains a 32-bit index into the pool of section numbers.  For unused
8543   hash table slots, the corresponding entry in the parallel table will be 0.
8544
8545   Given a 64-bit compilation unit signature or a type signature S, an entry
8546   in the hash table is located as follows:
8547
8548   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8549      the low-order k bits all set to 1.
8550
8551   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8552
8553   3) If the hash table entry at index H matches the signature, use that
8554      entry.  If the hash table entry at index H is unused (all zeroes),
8555      terminate the search: the signature is not present in the table.
8556
8557   4) Let H = (H + H') modulo M. Repeat at Step 3.
8558
8559   Because M > N and H' and M are relatively prime, the search is guaranteed
8560   to stop at an unused slot or find the match.
8561
8562   The pool of section numbers begins immediately following the hash table
8563   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8564   section numbers consists of an array of 32-bit words (using the byte order
8565   of the application binary).  Each item in the array is indexed starting
8566   from 0.  The hash table entry provides the index of the first section
8567   number in the set.  Additional section numbers in the set follow, and the
8568   set is terminated by a 0 entry (section number 0 is not used in ELF).
8569
8570   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8571   section must be the first entry in the set, and the .debug_abbrev.dwo must
8572   be the second entry. Other members of the set may follow in any order.  */
8573
8574 /* Create a hash table to map DWO IDs to their CU/TU entry in
8575    .debug_{info,types}.dwo in DWP_FILE.
8576    Returns NULL if there isn't one.
8577    Note: This function processes DWP files only, not DWO files.  */
8578
8579 static struct dwp_hash_table *
8580 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8581 {
8582   struct objfile *objfile = dwarf2_per_objfile->objfile;
8583   bfd *dbfd = dwp_file->dbfd;
8584   const char *index_ptr, *index_end;
8585   struct dwarf2_section_info *index;
8586   uint32_t version, nr_units, nr_slots;
8587   struct dwp_hash_table *htab;
8588
8589   if (is_debug_types)
8590     index = &dwp_file->sections.tu_index;
8591   else
8592     index = &dwp_file->sections.cu_index;
8593
8594   if (dwarf2_section_empty_p (index))
8595     return NULL;
8596   dwarf2_read_section (objfile, index);
8597
8598   index_ptr = index->buffer;
8599   index_end = index_ptr + index->size;
8600
8601   version = read_4_bytes (dbfd, index_ptr);
8602   index_ptr += 8; /* Skip the unused word.  */
8603   nr_units = read_4_bytes (dbfd, index_ptr);
8604   index_ptr += 4;
8605   nr_slots = read_4_bytes (dbfd, index_ptr);
8606   index_ptr += 4;
8607
8608   if (version != 1)
8609     {
8610       error (_("Dwarf Error: unsupported DWP file version (%u)"
8611                " [in module %s]"),
8612              version, dwp_file->name);
8613     }
8614   if (nr_slots != (nr_slots & -nr_slots))
8615     {
8616       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8617                " is not power of 2 [in module %s]"),
8618              nr_slots, dwp_file->name);
8619     }
8620
8621   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8622   htab->nr_units = nr_units;
8623   htab->nr_slots = nr_slots;
8624   htab->hash_table = index_ptr;
8625   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8626   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8627
8628   return htab;
8629 }
8630
8631 /* Update SECTIONS with the data from SECTP.
8632
8633    This function is like the other "locate" section routines that are
8634    passed to bfd_map_over_sections, but in this context the sections to
8635    read comes from the DWP hash table, not the full ELF section table.
8636
8637    The result is non-zero for success, or zero if an error was found.  */
8638
8639 static int
8640 locate_virtual_dwo_sections (asection *sectp,
8641                              struct virtual_dwo_sections *sections)
8642 {
8643   const struct dwop_section_names *names = &dwop_section_names;
8644
8645   if (section_is_p (sectp->name, &names->abbrev_dwo))
8646     {
8647       /* There can be only one.  */
8648       if (sections->abbrev.asection != NULL)
8649         return 0;
8650       sections->abbrev.asection = sectp;
8651       sections->abbrev.size = bfd_get_section_size (sectp);
8652     }
8653   else if (section_is_p (sectp->name, &names->info_dwo)
8654            || section_is_p (sectp->name, &names->types_dwo))
8655     {
8656       /* There can be only one.  */
8657       if (sections->info_or_types.asection != NULL)
8658         return 0;
8659       sections->info_or_types.asection = sectp;
8660       sections->info_or_types.size = bfd_get_section_size (sectp);
8661     }
8662   else if (section_is_p (sectp->name, &names->line_dwo))
8663     {
8664       /* There can be only one.  */
8665       if (sections->line.asection != NULL)
8666         return 0;
8667       sections->line.asection = sectp;
8668       sections->line.size = bfd_get_section_size (sectp);
8669     }
8670   else if (section_is_p (sectp->name, &names->loc_dwo))
8671     {
8672       /* There can be only one.  */
8673       if (sections->loc.asection != NULL)
8674         return 0;
8675       sections->loc.asection = sectp;
8676       sections->loc.size = bfd_get_section_size (sectp);
8677     }
8678   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8679     {
8680       /* There can be only one.  */
8681       if (sections->macinfo.asection != NULL)
8682         return 0;
8683       sections->macinfo.asection = sectp;
8684       sections->macinfo.size = bfd_get_section_size (sectp);
8685     }
8686   else if (section_is_p (sectp->name, &names->macro_dwo))
8687     {
8688       /* There can be only one.  */
8689       if (sections->macro.asection != NULL)
8690         return 0;
8691       sections->macro.asection = sectp;
8692       sections->macro.size = bfd_get_section_size (sectp);
8693     }
8694   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8695     {
8696       /* There can be only one.  */
8697       if (sections->str_offsets.asection != NULL)
8698         return 0;
8699       sections->str_offsets.asection = sectp;
8700       sections->str_offsets.size = bfd_get_section_size (sectp);
8701     }
8702   else
8703     {
8704       /* No other kind of section is valid.  */
8705       return 0;
8706     }
8707
8708   return 1;
8709 }
8710
8711 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8712    HTAB is the hash table from the DWP file.
8713    SECTION_INDEX is the index of the DWO in HTAB.
8714    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
8715
8716 static struct dwo_unit *
8717 create_dwo_in_dwp (struct dwp_file *dwp_file,
8718                    const struct dwp_hash_table *htab,
8719                    uint32_t section_index,
8720                    const char *comp_dir,
8721                    ULONGEST signature, int is_debug_types)
8722 {
8723   struct objfile *objfile = dwarf2_per_objfile->objfile;
8724   bfd *dbfd = dwp_file->dbfd;
8725   const char *kind = is_debug_types ? "TU" : "CU";
8726   struct dwo_file *dwo_file;
8727   struct dwo_unit *dwo_unit;
8728   struct virtual_dwo_sections sections;
8729   void **dwo_file_slot;
8730   char *virtual_dwo_name;
8731   struct dwarf2_section_info *cutu;
8732   struct cleanup *cleanups;
8733   int i;
8734
8735   if (dwarf2_read_debug)
8736     {
8737       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8738                           kind,
8739                           section_index, phex (signature, sizeof (signature)),
8740                           dwp_file->name);
8741     }
8742
8743   /* Fetch the sections of this DWO.
8744      Put a limit on the number of sections we look for so that bad data
8745      doesn't cause us to loop forever.  */
8746
8747 #define MAX_NR_DWO_SECTIONS \
8748   (1 /* .debug_info or .debug_types */ \
8749    + 1 /* .debug_abbrev */ \
8750    + 1 /* .debug_line */ \
8751    + 1 /* .debug_loc */ \
8752    + 1 /* .debug_str_offsets */ \
8753    + 1 /* .debug_macro */ \
8754    + 1 /* .debug_macinfo */ \
8755    + 1 /* trailing zero */)
8756
8757   memset (&sections, 0, sizeof (sections));
8758   cleanups = make_cleanup (null_cleanup, 0);
8759
8760   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8761     {
8762       asection *sectp;
8763       uint32_t section_nr =
8764         read_4_bytes (dbfd,
8765                       htab->section_pool
8766                       + (section_index + i) * sizeof (uint32_t));
8767
8768       if (section_nr == 0)
8769         break;
8770       if (section_nr >= dwp_file->num_sections)
8771         {
8772           error (_("Dwarf Error: bad DWP hash table, section number too large"
8773                    " [in module %s]"),
8774                  dwp_file->name);
8775         }
8776
8777       sectp = dwp_file->elf_sections[section_nr];
8778       if (! locate_virtual_dwo_sections (sectp, &sections))
8779         {
8780           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8781                    " [in module %s]"),
8782                  dwp_file->name);
8783         }
8784     }
8785
8786   if (i < 2
8787       || sections.info_or_types.asection == NULL
8788       || sections.abbrev.asection == NULL)
8789     {
8790       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8791                " [in module %s]"),
8792              dwp_file->name);
8793     }
8794   if (i == MAX_NR_DWO_SECTIONS)
8795     {
8796       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8797                " [in module %s]"),
8798              dwp_file->name);
8799     }
8800
8801   /* It's easier for the rest of the code if we fake a struct dwo_file and
8802      have dwo_unit "live" in that.  At least for now.
8803
8804      The DWP file can be made up of a random collection of CUs and TUs.
8805      However, for each CU + set of TUs that came from the same original DWO
8806      file, we want to combine them back into a virtual DWO file to save space
8807      (fewer struct dwo_file objects to allocated).  Remember that for really
8808      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8809
8810   virtual_dwo_name =
8811     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8812                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8813                 sections.line.asection ? sections.line.asection->id : 0,
8814                 sections.loc.asection ? sections.loc.asection->id : 0,
8815                 (sections.str_offsets.asection
8816                 ? sections.str_offsets.asection->id
8817                 : 0));
8818   make_cleanup (xfree, virtual_dwo_name);
8819   /* Can we use an existing virtual DWO file?  */
8820   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
8821   /* Create one if necessary.  */
8822   if (*dwo_file_slot == NULL)
8823     {
8824       if (dwarf2_read_debug)
8825         {
8826           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8827                               virtual_dwo_name);
8828         }
8829       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8830       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
8831                                           virtual_dwo_name,
8832                                           strlen (virtual_dwo_name));
8833       dwo_file->comp_dir = comp_dir;
8834       dwo_file->sections.abbrev = sections.abbrev;
8835       dwo_file->sections.line = sections.line;
8836       dwo_file->sections.loc = sections.loc;
8837       dwo_file->sections.macinfo = sections.macinfo;
8838       dwo_file->sections.macro = sections.macro;
8839       dwo_file->sections.str_offsets = sections.str_offsets;
8840       /* The "str" section is global to the entire DWP file.  */
8841       dwo_file->sections.str = dwp_file->sections.str;
8842       /* The info or types section is assigned later to dwo_unit,
8843          there's no need to record it in dwo_file.
8844          Also, we can't simply record type sections in dwo_file because
8845          we record a pointer into the vector in dwo_unit.  As we collect more
8846          types we'll grow the vector and eventually have to reallocate space
8847          for it, invalidating all the pointers into the current copy.  */
8848       *dwo_file_slot = dwo_file;
8849     }
8850   else
8851     {
8852       if (dwarf2_read_debug)
8853         {
8854           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8855                               virtual_dwo_name);
8856         }
8857       dwo_file = *dwo_file_slot;
8858     }
8859   do_cleanups (cleanups);
8860
8861   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8862   dwo_unit->dwo_file = dwo_file;
8863   dwo_unit->signature = signature;
8864   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
8865                                      sizeof (struct dwarf2_section_info));
8866   *dwo_unit->section = sections.info_or_types;
8867   /* offset, length, type_offset_in_tu are set later.  */
8868
8869   return dwo_unit;
8870 }
8871
8872 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8873
8874 static struct dwo_unit *
8875 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8876                    const struct dwp_hash_table *htab,
8877                    const char *comp_dir,
8878                    ULONGEST signature, int is_debug_types)
8879 {
8880   bfd *dbfd = dwp_file->dbfd;
8881   uint32_t mask = htab->nr_slots - 1;
8882   uint32_t hash = signature & mask;
8883   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8884   unsigned int i;
8885   void **slot;
8886   struct dwo_unit find_dwo_cu, *dwo_cu;
8887
8888   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8889   find_dwo_cu.signature = signature;
8890   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8891
8892   if (*slot != NULL)
8893     return *slot;
8894
8895   /* Use a for loop so that we don't loop forever on bad debug info.  */
8896   for (i = 0; i < htab->nr_slots; ++i)
8897     {
8898       ULONGEST signature_in_table;
8899
8900       signature_in_table =
8901         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8902       if (signature_in_table == signature)
8903         {
8904           uint32_t section_index =
8905             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8906
8907           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8908                                      comp_dir, signature, is_debug_types);
8909           return *slot;
8910         }
8911       if (signature_in_table == 0)
8912         return NULL;
8913       hash = (hash + hash2) & mask;
8914     }
8915
8916   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8917            " [in module %s]"),
8918          dwp_file->name);
8919 }
8920
8921 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
8922    Open the file specified by FILE_NAME and hand it off to BFD for
8923    preliminary analysis.  Return a newly initialized bfd *, which
8924    includes a canonicalized copy of FILE_NAME.
8925    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8926    In case of trouble, return NULL.
8927    NOTE: This function is derived from symfile_bfd_open.  */
8928
8929 static bfd *
8930 try_open_dwop_file (const char *file_name, int is_dwp)
8931 {
8932   bfd *sym_bfd;
8933   int desc, flags;
8934   char *absolute_name;
8935
8936   flags = OPF_TRY_CWD_FIRST;
8937   if (is_dwp)
8938     flags |= OPF_SEARCH_IN_PATH;
8939   desc = openp (debug_file_directory, flags, file_name,
8940                 O_RDONLY | O_BINARY, &absolute_name);
8941   if (desc < 0)
8942     return NULL;
8943
8944   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8945   if (!sym_bfd)
8946     {
8947       xfree (absolute_name);
8948       return NULL;
8949     }
8950   xfree (absolute_name);
8951   bfd_set_cacheable (sym_bfd, 1);
8952
8953   if (!bfd_check_format (sym_bfd, bfd_object))
8954     {
8955       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8956       return NULL;
8957     }
8958
8959   return sym_bfd;
8960 }
8961
8962 /* Try to open DWO file FILE_NAME.
8963    COMP_DIR is the DW_AT_comp_dir attribute.
8964    The result is the bfd handle of the file.
8965    If there is a problem finding or opening the file, return NULL.
8966    Upon success, the canonicalized path of the file is stored in the bfd,
8967    same as symfile_bfd_open.  */
8968
8969 static bfd *
8970 open_dwo_file (const char *file_name, const char *comp_dir)
8971 {
8972   bfd *abfd;
8973
8974   if (IS_ABSOLUTE_PATH (file_name))
8975     return try_open_dwop_file (file_name, 0 /*is_dwp*/);
8976
8977   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8978
8979   if (comp_dir != NULL)
8980     {
8981       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8982
8983       /* NOTE: If comp_dir is a relative path, this will also try the
8984          search path, which seems useful.  */
8985       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/);
8986       xfree (path_to_try);
8987       if (abfd != NULL)
8988         return abfd;
8989     }
8990
8991   /* That didn't work, try debug-file-directory, which, despite its name,
8992      is a list of paths.  */
8993
8994   if (*debug_file_directory == '\0')
8995     return NULL;
8996
8997   return try_open_dwop_file (file_name, 0 /*is_dwp*/);
8998 }
8999
9000 /* This function is mapped across the sections and remembers the offset and
9001    size of each of the DWO debugging sections we are interested in.  */
9002
9003 static void
9004 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9005 {
9006   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9007   const struct dwop_section_names *names = &dwop_section_names;
9008
9009   if (section_is_p (sectp->name, &names->abbrev_dwo))
9010     {
9011       dwo_sections->abbrev.asection = sectp;
9012       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9013     }
9014   else if (section_is_p (sectp->name, &names->info_dwo))
9015     {
9016       dwo_sections->info.asection = sectp;
9017       dwo_sections->info.size = bfd_get_section_size (sectp);
9018     }
9019   else if (section_is_p (sectp->name, &names->line_dwo))
9020     {
9021       dwo_sections->line.asection = sectp;
9022       dwo_sections->line.size = bfd_get_section_size (sectp);
9023     }
9024   else if (section_is_p (sectp->name, &names->loc_dwo))
9025     {
9026       dwo_sections->loc.asection = sectp;
9027       dwo_sections->loc.size = bfd_get_section_size (sectp);
9028     }
9029   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9030     {
9031       dwo_sections->macinfo.asection = sectp;
9032       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9033     }
9034   else if (section_is_p (sectp->name, &names->macro_dwo))
9035     {
9036       dwo_sections->macro.asection = sectp;
9037       dwo_sections->macro.size = bfd_get_section_size (sectp);
9038     }
9039   else if (section_is_p (sectp->name, &names->str_dwo))
9040     {
9041       dwo_sections->str.asection = sectp;
9042       dwo_sections->str.size = bfd_get_section_size (sectp);
9043     }
9044   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9045     {
9046       dwo_sections->str_offsets.asection = sectp;
9047       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9048     }
9049   else if (section_is_p (sectp->name, &names->types_dwo))
9050     {
9051       struct dwarf2_section_info type_section;
9052
9053       memset (&type_section, 0, sizeof (type_section));
9054       type_section.asection = sectp;
9055       type_section.size = bfd_get_section_size (sectp);
9056       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9057                      &type_section);
9058     }
9059 }
9060
9061 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9062    by PER_CU.
9063    The result is NULL if DWO_NAME can't be found.  */
9064
9065 static struct dwo_file *
9066 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9067                         const char *dwo_name, const char *comp_dir)
9068 {
9069   struct objfile *objfile = dwarf2_per_objfile->objfile;
9070   struct dwo_file *dwo_file;
9071   bfd *dbfd;
9072   struct cleanup *cleanups;
9073
9074   dbfd = open_dwo_file (dwo_name, comp_dir);
9075   if (dbfd == NULL)
9076     {
9077       if (dwarf2_read_debug)
9078         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9079       return NULL;
9080     }
9081   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9082   dwo_file->dwo_name = dwo_name;
9083   dwo_file->comp_dir = comp_dir;
9084   dwo_file->dbfd = dbfd;
9085
9086   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9087
9088   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9089
9090   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
9091
9092   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9093                                                  dwo_file->sections.types);
9094
9095   discard_cleanups (cleanups);
9096
9097   if (dwarf2_read_debug)
9098     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9099
9100   return dwo_file;
9101 }
9102
9103 /* This function is mapped across the sections and remembers the offset and
9104    size of each of the DWP debugging sections we are interested in.  */
9105
9106 static void
9107 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9108 {
9109   struct dwp_file *dwp_file = dwp_file_ptr;
9110   const struct dwop_section_names *names = &dwop_section_names;
9111   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9112
9113   /* Record the ELF section number for later lookup: this is what the
9114      .debug_cu_index,.debug_tu_index tables use.  */
9115   gdb_assert (elf_section_nr < dwp_file->num_sections);
9116   dwp_file->elf_sections[elf_section_nr] = sectp;
9117
9118   /* Look for specific sections that we need.  */
9119   if (section_is_p (sectp->name, &names->str_dwo))
9120     {
9121       dwp_file->sections.str.asection = sectp;
9122       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9123     }
9124   else if (section_is_p (sectp->name, &names->cu_index))
9125     {
9126       dwp_file->sections.cu_index.asection = sectp;
9127       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9128     }
9129   else if (section_is_p (sectp->name, &names->tu_index))
9130     {
9131       dwp_file->sections.tu_index.asection = sectp;
9132       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9133     }
9134 }
9135
9136 /* Hash function for dwp_file loaded CUs/TUs.  */
9137
9138 static hashval_t
9139 hash_dwp_loaded_cutus (const void *item)
9140 {
9141   const struct dwo_unit *dwo_unit = item;
9142
9143   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9144   return dwo_unit->signature;
9145 }
9146
9147 /* Equality function for dwp_file loaded CUs/TUs.  */
9148
9149 static int
9150 eq_dwp_loaded_cutus (const void *a, const void *b)
9151 {
9152   const struct dwo_unit *dua = a;
9153   const struct dwo_unit *dub = b;
9154
9155   return dua->signature == dub->signature;
9156 }
9157
9158 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9159
9160 static htab_t
9161 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9162 {
9163   return htab_create_alloc_ex (3,
9164                                hash_dwp_loaded_cutus,
9165                                eq_dwp_loaded_cutus,
9166                                NULL,
9167                                &objfile->objfile_obstack,
9168                                hashtab_obstack_allocate,
9169                                dummy_obstack_deallocate);
9170 }
9171
9172 /* Try to open DWP file FILE_NAME.
9173    The result is the bfd handle of the file.
9174    If there is a problem finding or opening the file, return NULL.
9175    Upon success, the canonicalized path of the file is stored in the bfd,
9176    same as symfile_bfd_open.  */
9177
9178 static bfd *
9179 open_dwp_file (const char *file_name)
9180 {
9181   return try_open_dwop_file (file_name, 1 /*is_dwp*/);
9182 }
9183
9184 /* Initialize the use of the DWP file for the current objfile.
9185    By convention the name of the DWP file is ${objfile}.dwp.
9186    The result is NULL if it can't be found.  */
9187
9188 static struct dwp_file *
9189 open_and_init_dwp_file (void)
9190 {
9191   struct objfile *objfile = dwarf2_per_objfile->objfile;
9192   struct dwp_file *dwp_file;
9193   char *dwp_name;
9194   bfd *dbfd;
9195   struct cleanup *cleanups;
9196
9197   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9198   cleanups = make_cleanup (xfree, dwp_name);
9199
9200   dbfd = open_dwp_file (dwp_name);
9201   if (dbfd == NULL)
9202     {
9203       if (dwarf2_read_debug)
9204         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9205       do_cleanups (cleanups);
9206       return NULL;
9207     }
9208   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9209   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9210                                   dwp_name, strlen (dwp_name));
9211   dwp_file->dbfd = dbfd;
9212   do_cleanups (cleanups);
9213
9214   /* +1: section 0 is unused */
9215   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9216   dwp_file->elf_sections =
9217     OBSTACK_CALLOC (&objfile->objfile_obstack,
9218                     dwp_file->num_sections, asection *);
9219
9220   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9221
9222   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9223
9224   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9225
9226   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9227
9228   if (dwarf2_read_debug)
9229     {
9230       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9231       fprintf_unfiltered (gdb_stdlog,
9232                           "    %u CUs, %u TUs\n",
9233                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9234                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9235     }
9236
9237   return dwp_file;
9238 }
9239
9240 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9241
9242 static struct dwp_file *
9243 get_dwp_file (void)
9244 {
9245   if (! dwarf2_per_objfile->dwp_checked)
9246     {
9247       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9248       dwarf2_per_objfile->dwp_checked = 1;
9249     }
9250   return dwarf2_per_objfile->dwp_file;
9251 }
9252
9253 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9254    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9255    or in the DWP file for the objfile, referenced by THIS_UNIT.
9256    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9257    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9258
9259    This is called, for example, when wanting to read a variable with a
9260    complex location.  Therefore we don't want to do file i/o for every call.
9261    Therefore we don't want to look for a DWO file on every call.
9262    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9263    then we check if we've already seen DWO_NAME, and only THEN do we check
9264    for a DWO file.
9265
9266    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9267    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9268
9269 static struct dwo_unit *
9270 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9271                  const char *dwo_name, const char *comp_dir,
9272                  ULONGEST signature, int is_debug_types)
9273 {
9274   struct objfile *objfile = dwarf2_per_objfile->objfile;
9275   const char *kind = is_debug_types ? "TU" : "CU";
9276   void **dwo_file_slot;
9277   struct dwo_file *dwo_file;
9278   struct dwp_file *dwp_file;
9279
9280   /* Have we already read SIGNATURE from a DWP file?  */
9281
9282   dwp_file = get_dwp_file ();
9283   if (dwp_file != NULL)
9284     {
9285       const struct dwp_hash_table *dwp_htab =
9286         is_debug_types ? dwp_file->tus : dwp_file->cus;
9287
9288       if (dwp_htab != NULL)
9289         {
9290           struct dwo_unit *dwo_cutu =
9291             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9292                                signature, is_debug_types);
9293
9294           if (dwo_cutu != NULL)
9295             {
9296               if (dwarf2_read_debug)
9297                 {
9298                   fprintf_unfiltered (gdb_stdlog,
9299                                       "Virtual DWO %s %s found: @%s\n",
9300                                       kind, hex_string (signature),
9301                                       host_address_to_string (dwo_cutu));
9302                 }
9303               return dwo_cutu;
9304             }
9305         }
9306     }
9307
9308   /* Have we already seen DWO_NAME?  */
9309
9310   dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9311   if (*dwo_file_slot == NULL)
9312     {
9313       /* Read in the file and build a table of the DWOs it contains.  */
9314       *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9315     }
9316   /* NOTE: This will be NULL if unable to open the file.  */
9317   dwo_file = *dwo_file_slot;
9318
9319   if (dwo_file != NULL)
9320     {
9321       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9322
9323       if (htab != NULL)
9324         {
9325           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9326
9327           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9328           find_dwo_cutu.signature = signature;
9329           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9330
9331           if (dwo_cutu != NULL)
9332             {
9333               if (dwarf2_read_debug)
9334                 {
9335                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9336                                       kind, dwo_name, hex_string (signature),
9337                                       host_address_to_string (dwo_cutu));
9338                 }
9339               return dwo_cutu;
9340             }
9341         }
9342     }
9343
9344   /* We didn't find it.  This could mean a dwo_id mismatch, or
9345      someone deleted the DWO/DWP file, or the search path isn't set up
9346      correctly to find the file.  */
9347
9348   if (dwarf2_read_debug)
9349     {
9350       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9351                           kind, dwo_name, hex_string (signature));
9352     }
9353
9354   complaint (&symfile_complaints,
9355              _("Could not find DWO %s referenced by CU at offset 0x%x"
9356                " [in module %s]"),
9357              kind, this_unit->offset.sect_off, objfile->name);
9358   return NULL;
9359 }
9360
9361 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9362    See lookup_dwo_cutu_unit for details.  */
9363
9364 static struct dwo_unit *
9365 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9366                       const char *dwo_name, const char *comp_dir,
9367                       ULONGEST signature)
9368 {
9369   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9370 }
9371
9372 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9373    See lookup_dwo_cutu_unit for details.  */
9374
9375 static struct dwo_unit *
9376 lookup_dwo_type_unit (struct signatured_type *this_tu,
9377                       const char *dwo_name, const char *comp_dir)
9378 {
9379   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9380 }
9381
9382 /* Free all resources associated with DWO_FILE.
9383    Close the DWO file and munmap the sections.
9384    All memory should be on the objfile obstack.  */
9385
9386 static void
9387 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9388 {
9389   int ix;
9390   struct dwarf2_section_info *section;
9391
9392   /* Note: dbfd is NULL for virtual DWO files.  */
9393   gdb_bfd_unref (dwo_file->dbfd);
9394
9395   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9396 }
9397
9398 /* Wrapper for free_dwo_file for use in cleanups.  */
9399
9400 static void
9401 free_dwo_file_cleanup (void *arg)
9402 {
9403   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9404   struct objfile *objfile = dwarf2_per_objfile->objfile;
9405
9406   free_dwo_file (dwo_file, objfile);
9407 }
9408
9409 /* Traversal function for free_dwo_files.  */
9410
9411 static int
9412 free_dwo_file_from_slot (void **slot, void *info)
9413 {
9414   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9415   struct objfile *objfile = (struct objfile *) info;
9416
9417   free_dwo_file (dwo_file, objfile);
9418
9419   return 1;
9420 }
9421
9422 /* Free all resources associated with DWO_FILES.  */
9423
9424 static void
9425 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9426 {
9427   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9428 }
9429 \f
9430 /* Read in various DIEs.  */
9431
9432 /* qsort helper for inherit_abstract_dies.  */
9433
9434 static int
9435 unsigned_int_compar (const void *ap, const void *bp)
9436 {
9437   unsigned int a = *(unsigned int *) ap;
9438   unsigned int b = *(unsigned int *) bp;
9439
9440   return (a > b) - (b > a);
9441 }
9442
9443 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9444    Inherit only the children of the DW_AT_abstract_origin DIE not being
9445    already referenced by DW_AT_abstract_origin from the children of the
9446    current DIE.  */
9447
9448 static void
9449 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9450 {
9451   struct die_info *child_die;
9452   unsigned die_children_count;
9453   /* CU offsets which were referenced by children of the current DIE.  */
9454   sect_offset *offsets;
9455   sect_offset *offsets_end, *offsetp;
9456   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9457   struct die_info *origin_die;
9458   /* Iterator of the ORIGIN_DIE children.  */
9459   struct die_info *origin_child_die;
9460   struct cleanup *cleanups;
9461   struct attribute *attr;
9462   struct dwarf2_cu *origin_cu;
9463   struct pending **origin_previous_list_in_scope;
9464
9465   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9466   if (!attr)
9467     return;
9468
9469   /* Note that following die references may follow to a die in a
9470      different cu.  */
9471
9472   origin_cu = cu;
9473   origin_die = follow_die_ref (die, attr, &origin_cu);
9474
9475   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9476      symbols in.  */
9477   origin_previous_list_in_scope = origin_cu->list_in_scope;
9478   origin_cu->list_in_scope = cu->list_in_scope;
9479
9480   if (die->tag != origin_die->tag
9481       && !(die->tag == DW_TAG_inlined_subroutine
9482            && origin_die->tag == DW_TAG_subprogram))
9483     complaint (&symfile_complaints,
9484                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9485                die->offset.sect_off, origin_die->offset.sect_off);
9486
9487   child_die = die->child;
9488   die_children_count = 0;
9489   while (child_die && child_die->tag)
9490     {
9491       child_die = sibling_die (child_die);
9492       die_children_count++;
9493     }
9494   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9495   cleanups = make_cleanup (xfree, offsets);
9496
9497   offsets_end = offsets;
9498   child_die = die->child;
9499   while (child_die && child_die->tag)
9500     {
9501       /* For each CHILD_DIE, find the corresponding child of
9502          ORIGIN_DIE.  If there is more than one layer of
9503          DW_AT_abstract_origin, follow them all; there shouldn't be,
9504          but GCC versions at least through 4.4 generate this (GCC PR
9505          40573).  */
9506       struct die_info *child_origin_die = child_die;
9507       struct dwarf2_cu *child_origin_cu = cu;
9508
9509       while (1)
9510         {
9511           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9512                               child_origin_cu);
9513           if (attr == NULL)
9514             break;
9515           child_origin_die = follow_die_ref (child_origin_die, attr,
9516                                              &child_origin_cu);
9517         }
9518
9519       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9520          counterpart may exist.  */
9521       if (child_origin_die != child_die)
9522         {
9523           if (child_die->tag != child_origin_die->tag
9524               && !(child_die->tag == DW_TAG_inlined_subroutine
9525                    && child_origin_die->tag == DW_TAG_subprogram))
9526             complaint (&symfile_complaints,
9527                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9528                          "different tags"), child_die->offset.sect_off,
9529                        child_origin_die->offset.sect_off);
9530           if (child_origin_die->parent != origin_die)
9531             complaint (&symfile_complaints,
9532                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9533                          "different parents"), child_die->offset.sect_off,
9534                        child_origin_die->offset.sect_off);
9535           else
9536             *offsets_end++ = child_origin_die->offset;
9537         }
9538       child_die = sibling_die (child_die);
9539     }
9540   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9541          unsigned_int_compar);
9542   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9543     if (offsetp[-1].sect_off == offsetp->sect_off)
9544       complaint (&symfile_complaints,
9545                  _("Multiple children of DIE 0x%x refer "
9546                    "to DIE 0x%x as their abstract origin"),
9547                  die->offset.sect_off, offsetp->sect_off);
9548
9549   offsetp = offsets;
9550   origin_child_die = origin_die->child;
9551   while (origin_child_die && origin_child_die->tag)
9552     {
9553       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9554       while (offsetp < offsets_end
9555              && offsetp->sect_off < origin_child_die->offset.sect_off)
9556         offsetp++;
9557       if (offsetp >= offsets_end
9558           || offsetp->sect_off > origin_child_die->offset.sect_off)
9559         {
9560           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9561           process_die (origin_child_die, origin_cu);
9562         }
9563       origin_child_die = sibling_die (origin_child_die);
9564     }
9565   origin_cu->list_in_scope = origin_previous_list_in_scope;
9566
9567   do_cleanups (cleanups);
9568 }
9569
9570 static void
9571 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9572 {
9573   struct objfile *objfile = cu->objfile;
9574   struct context_stack *new;
9575   CORE_ADDR lowpc;
9576   CORE_ADDR highpc;
9577   struct die_info *child_die;
9578   struct attribute *attr, *call_line, *call_file;
9579   const char *name;
9580   CORE_ADDR baseaddr;
9581   struct block *block;
9582   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9583   VEC (symbolp) *template_args = NULL;
9584   struct template_symbol *templ_func = NULL;
9585
9586   if (inlined_func)
9587     {
9588       /* If we do not have call site information, we can't show the
9589          caller of this inlined function.  That's too confusing, so
9590          only use the scope for local variables.  */
9591       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9592       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9593       if (call_line == NULL || call_file == NULL)
9594         {
9595           read_lexical_block_scope (die, cu);
9596           return;
9597         }
9598     }
9599
9600   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9601
9602   name = dwarf2_name (die, cu);
9603
9604   /* Ignore functions with missing or empty names.  These are actually
9605      illegal according to the DWARF standard.  */
9606   if (name == NULL)
9607     {
9608       complaint (&symfile_complaints,
9609                  _("missing name for subprogram DIE at %d"),
9610                  die->offset.sect_off);
9611       return;
9612     }
9613
9614   /* Ignore functions with missing or invalid low and high pc attributes.  */
9615   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9616     {
9617       attr = dwarf2_attr (die, DW_AT_external, cu);
9618       if (!attr || !DW_UNSND (attr))
9619         complaint (&symfile_complaints,
9620                    _("cannot get low and high bounds "
9621                      "for subprogram DIE at %d"),
9622                    die->offset.sect_off);
9623       return;
9624     }
9625
9626   lowpc += baseaddr;
9627   highpc += baseaddr;
9628
9629   /* If we have any template arguments, then we must allocate a
9630      different sort of symbol.  */
9631   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9632     {
9633       if (child_die->tag == DW_TAG_template_type_param
9634           || child_die->tag == DW_TAG_template_value_param)
9635         {
9636           templ_func = allocate_template_symbol (objfile);
9637           templ_func->base.is_cplus_template_function = 1;
9638           break;
9639         }
9640     }
9641
9642   new = push_context (0, lowpc);
9643   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9644                                (struct symbol *) templ_func);
9645
9646   /* If there is a location expression for DW_AT_frame_base, record
9647      it.  */
9648   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9649   if (attr)
9650     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
9651
9652   cu->list_in_scope = &local_symbols;
9653
9654   if (die->child != NULL)
9655     {
9656       child_die = die->child;
9657       while (child_die && child_die->tag)
9658         {
9659           if (child_die->tag == DW_TAG_template_type_param
9660               || child_die->tag == DW_TAG_template_value_param)
9661             {
9662               struct symbol *arg = new_symbol (child_die, NULL, cu);
9663
9664               if (arg != NULL)
9665                 VEC_safe_push (symbolp, template_args, arg);
9666             }
9667           else
9668             process_die (child_die, cu);
9669           child_die = sibling_die (child_die);
9670         }
9671     }
9672
9673   inherit_abstract_dies (die, cu);
9674
9675   /* If we have a DW_AT_specification, we might need to import using
9676      directives from the context of the specification DIE.  See the
9677      comment in determine_prefix.  */
9678   if (cu->language == language_cplus
9679       && dwarf2_attr (die, DW_AT_specification, cu))
9680     {
9681       struct dwarf2_cu *spec_cu = cu;
9682       struct die_info *spec_die = die_specification (die, &spec_cu);
9683
9684       while (spec_die)
9685         {
9686           child_die = spec_die->child;
9687           while (child_die && child_die->tag)
9688             {
9689               if (child_die->tag == DW_TAG_imported_module)
9690                 process_die (child_die, spec_cu);
9691               child_die = sibling_die (child_die);
9692             }
9693
9694           /* In some cases, GCC generates specification DIEs that
9695              themselves contain DW_AT_specification attributes.  */
9696           spec_die = die_specification (spec_die, &spec_cu);
9697         }
9698     }
9699
9700   new = pop_context ();
9701   /* Make a block for the local symbols within.  */
9702   block = finish_block (new->name, &local_symbols, new->old_blocks,
9703                         lowpc, highpc, objfile);
9704
9705   /* For C++, set the block's scope.  */
9706   if ((cu->language == language_cplus || cu->language == language_fortran)
9707       && cu->processing_has_namespace_info)
9708     block_set_scope (block, determine_prefix (die, cu),
9709                      &objfile->objfile_obstack);
9710
9711   /* If we have address ranges, record them.  */
9712   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9713
9714   /* Attach template arguments to function.  */
9715   if (! VEC_empty (symbolp, template_args))
9716     {
9717       gdb_assert (templ_func != NULL);
9718
9719       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9720       templ_func->template_arguments
9721         = obstack_alloc (&objfile->objfile_obstack,
9722                          (templ_func->n_template_arguments
9723                           * sizeof (struct symbol *)));
9724       memcpy (templ_func->template_arguments,
9725               VEC_address (symbolp, template_args),
9726               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9727       VEC_free (symbolp, template_args);
9728     }
9729
9730   /* In C++, we can have functions nested inside functions (e.g., when
9731      a function declares a class that has methods).  This means that
9732      when we finish processing a function scope, we may need to go
9733      back to building a containing block's symbol lists.  */
9734   local_symbols = new->locals;
9735   using_directives = new->using_directives;
9736
9737   /* If we've finished processing a top-level function, subsequent
9738      symbols go in the file symbol list.  */
9739   if (outermost_context_p ())
9740     cu->list_in_scope = &file_symbols;
9741 }
9742
9743 /* Process all the DIES contained within a lexical block scope.  Start
9744    a new scope, process the dies, and then close the scope.  */
9745
9746 static void
9747 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9748 {
9749   struct objfile *objfile = cu->objfile;
9750   struct context_stack *new;
9751   CORE_ADDR lowpc, highpc;
9752   struct die_info *child_die;
9753   CORE_ADDR baseaddr;
9754
9755   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9756
9757   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9758   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9759      as multiple lexical blocks?  Handling children in a sane way would
9760      be nasty.  Might be easier to properly extend generic blocks to
9761      describe ranges.  */
9762   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9763     return;
9764   lowpc += baseaddr;
9765   highpc += baseaddr;
9766
9767   push_context (0, lowpc);
9768   if (die->child != NULL)
9769     {
9770       child_die = die->child;
9771       while (child_die && child_die->tag)
9772         {
9773           process_die (child_die, cu);
9774           child_die = sibling_die (child_die);
9775         }
9776     }
9777   new = pop_context ();
9778
9779   if (local_symbols != NULL || using_directives != NULL)
9780     {
9781       struct block *block
9782         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9783                         highpc, objfile);
9784
9785       /* Note that recording ranges after traversing children, as we
9786          do here, means that recording a parent's ranges entails
9787          walking across all its children's ranges as they appear in
9788          the address map, which is quadratic behavior.
9789
9790          It would be nicer to record the parent's ranges before
9791          traversing its children, simply overriding whatever you find
9792          there.  But since we don't even decide whether to create a
9793          block until after we've traversed its children, that's hard
9794          to do.  */
9795       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9796     }
9797   local_symbols = new->locals;
9798   using_directives = new->using_directives;
9799 }
9800
9801 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9802
9803 static void
9804 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9805 {
9806   struct objfile *objfile = cu->objfile;
9807   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9808   CORE_ADDR pc, baseaddr;
9809   struct attribute *attr;
9810   struct call_site *call_site, call_site_local;
9811   void **slot;
9812   int nparams;
9813   struct die_info *child_die;
9814
9815   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9816
9817   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9818   if (!attr)
9819     {
9820       complaint (&symfile_complaints,
9821                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9822                    "DIE 0x%x [in module %s]"),
9823                  die->offset.sect_off, objfile->name);
9824       return;
9825     }
9826   pc = DW_ADDR (attr) + baseaddr;
9827
9828   if (cu->call_site_htab == NULL)
9829     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9830                                                NULL, &objfile->objfile_obstack,
9831                                                hashtab_obstack_allocate, NULL);
9832   call_site_local.pc = pc;
9833   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9834   if (*slot != NULL)
9835     {
9836       complaint (&symfile_complaints,
9837                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9838                    "DIE 0x%x [in module %s]"),
9839                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9840       return;
9841     }
9842
9843   /* Count parameters at the caller.  */
9844
9845   nparams = 0;
9846   for (child_die = die->child; child_die && child_die->tag;
9847        child_die = sibling_die (child_die))
9848     {
9849       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9850         {
9851           complaint (&symfile_complaints,
9852                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9853                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9854                      child_die->tag, child_die->offset.sect_off, objfile->name);
9855           continue;
9856         }
9857
9858       nparams++;
9859     }
9860
9861   call_site = obstack_alloc (&objfile->objfile_obstack,
9862                              (sizeof (*call_site)
9863                               + (sizeof (*call_site->parameter)
9864                                  * (nparams - 1))));
9865   *slot = call_site;
9866   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9867   call_site->pc = pc;
9868
9869   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9870     {
9871       struct die_info *func_die;
9872
9873       /* Skip also over DW_TAG_inlined_subroutine.  */
9874       for (func_die = die->parent;
9875            func_die && func_die->tag != DW_TAG_subprogram
9876            && func_die->tag != DW_TAG_subroutine_type;
9877            func_die = func_die->parent);
9878
9879       /* DW_AT_GNU_all_call_sites is a superset
9880          of DW_AT_GNU_all_tail_call_sites.  */
9881       if (func_die
9882           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9883           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9884         {
9885           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9886              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9887              both the initial caller containing the real return address PC and
9888              the final callee containing the current PC of a chain of tail
9889              calls do not need to have the tail call list complete.  But any
9890              function candidate for a virtual tail call frame searched via
9891              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9892              determined unambiguously.  */
9893         }
9894       else
9895         {
9896           struct type *func_type = NULL;
9897
9898           if (func_die)
9899             func_type = get_die_type (func_die, cu);
9900           if (func_type != NULL)
9901             {
9902               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9903
9904               /* Enlist this call site to the function.  */
9905               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9906               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9907             }
9908           else
9909             complaint (&symfile_complaints,
9910                        _("Cannot find function owning DW_TAG_GNU_call_site "
9911                          "DIE 0x%x [in module %s]"),
9912                        die->offset.sect_off, objfile->name);
9913         }
9914     }
9915
9916   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9917   if (attr == NULL)
9918     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9919   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9920   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9921     /* Keep NULL DWARF_BLOCK.  */;
9922   else if (attr_form_is_block (attr))
9923     {
9924       struct dwarf2_locexpr_baton *dlbaton;
9925
9926       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9927       dlbaton->data = DW_BLOCK (attr)->data;
9928       dlbaton->size = DW_BLOCK (attr)->size;
9929       dlbaton->per_cu = cu->per_cu;
9930
9931       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9932     }
9933   else if (is_ref_attr (attr))
9934     {
9935       struct dwarf2_cu *target_cu = cu;
9936       struct die_info *target_die;
9937
9938       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9939       gdb_assert (target_cu->objfile == objfile);
9940       if (die_is_declaration (target_die, target_cu))
9941         {
9942           const char *target_physname = NULL;
9943           struct attribute *target_attr;
9944
9945           /* Prefer the mangled name; otherwise compute the demangled one.  */
9946           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
9947           if (target_attr == NULL)
9948             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
9949                                        target_cu);
9950           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
9951             target_physname = DW_STRING (target_attr);
9952           else
9953             target_physname = dwarf2_physname (NULL, target_die, target_cu);
9954           if (target_physname == NULL)
9955             complaint (&symfile_complaints,
9956                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9957                          "physname, for referencing DIE 0x%x [in module %s]"),
9958                        die->offset.sect_off, objfile->name);
9959           else
9960             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9961         }
9962       else
9963         {
9964           CORE_ADDR lowpc;
9965
9966           /* DW_AT_entry_pc should be preferred.  */
9967           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9968             complaint (&symfile_complaints,
9969                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9970                          "low pc, for referencing DIE 0x%x [in module %s]"),
9971                        die->offset.sect_off, objfile->name);
9972           else
9973             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9974         }
9975     }
9976   else
9977     complaint (&symfile_complaints,
9978                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9979                  "block nor reference, for DIE 0x%x [in module %s]"),
9980                die->offset.sect_off, objfile->name);
9981
9982   call_site->per_cu = cu->per_cu;
9983
9984   for (child_die = die->child;
9985        child_die && child_die->tag;
9986        child_die = sibling_die (child_die))
9987     {
9988       struct call_site_parameter *parameter;
9989       struct attribute *loc, *origin;
9990
9991       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9992         {
9993           /* Already printed the complaint above.  */
9994           continue;
9995         }
9996
9997       gdb_assert (call_site->parameter_count < nparams);
9998       parameter = &call_site->parameter[call_site->parameter_count];
9999
10000       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
10001          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
10002          register is contained in DW_AT_GNU_call_site_value.  */
10003
10004       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10005       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10006       if (loc == NULL && origin != NULL && is_ref_attr (origin))
10007         {
10008           sect_offset offset;
10009
10010           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10011           offset = dwarf2_get_ref_die_offset (origin);
10012           if (!offset_in_cu_p (&cu->header, offset))
10013             {
10014               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10015                  binding can be done only inside one CU.  Such referenced DIE
10016                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10017               complaint (&symfile_complaints,
10018                          _("DW_AT_abstract_origin offset is not in CU for "
10019                            "DW_TAG_GNU_call_site child DIE 0x%x "
10020                            "[in module %s]"),
10021                          child_die->offset.sect_off, objfile->name);
10022               continue;
10023             }
10024           parameter->u.param_offset.cu_off = (offset.sect_off
10025                                               - cu->header.offset.sect_off);
10026         }
10027       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10028         {
10029           complaint (&symfile_complaints,
10030                      _("No DW_FORM_block* DW_AT_location for "
10031                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10032                      child_die->offset.sect_off, objfile->name);
10033           continue;
10034         }
10035       else
10036         {
10037           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10038             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10039           if (parameter->u.dwarf_reg != -1)
10040             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10041           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10042                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10043                                              &parameter->u.fb_offset))
10044             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10045           else
10046             {
10047               complaint (&symfile_complaints,
10048                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10049                            "for DW_FORM_block* DW_AT_location is supported for "
10050                            "DW_TAG_GNU_call_site child DIE 0x%x "
10051                            "[in module %s]"),
10052                          child_die->offset.sect_off, objfile->name);
10053               continue;
10054             }
10055         }
10056
10057       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10058       if (!attr_form_is_block (attr))
10059         {
10060           complaint (&symfile_complaints,
10061                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10062                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10063                      child_die->offset.sect_off, objfile->name);
10064           continue;
10065         }
10066       parameter->value = DW_BLOCK (attr)->data;
10067       parameter->value_size = DW_BLOCK (attr)->size;
10068
10069       /* Parameters are not pre-cleared by memset above.  */
10070       parameter->data_value = NULL;
10071       parameter->data_value_size = 0;
10072       call_site->parameter_count++;
10073
10074       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10075       if (attr)
10076         {
10077           if (!attr_form_is_block (attr))
10078             complaint (&symfile_complaints,
10079                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10080                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10081                        child_die->offset.sect_off, objfile->name);
10082           else
10083             {
10084               parameter->data_value = DW_BLOCK (attr)->data;
10085               parameter->data_value_size = DW_BLOCK (attr)->size;
10086             }
10087         }
10088     }
10089 }
10090
10091 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10092    Return 1 if the attributes are present and valid, otherwise, return 0.
10093    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10094
10095 static int
10096 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10097                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10098                     struct partial_symtab *ranges_pst)
10099 {
10100   struct objfile *objfile = cu->objfile;
10101   struct comp_unit_head *cu_header = &cu->header;
10102   bfd *obfd = objfile->obfd;
10103   unsigned int addr_size = cu_header->addr_size;
10104   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10105   /* Base address selection entry.  */
10106   CORE_ADDR base;
10107   int found_base;
10108   unsigned int dummy;
10109   const gdb_byte *buffer;
10110   CORE_ADDR marker;
10111   int low_set;
10112   CORE_ADDR low = 0;
10113   CORE_ADDR high = 0;
10114   CORE_ADDR baseaddr;
10115
10116   found_base = cu->base_known;
10117   base = cu->base_address;
10118
10119   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10120   if (offset >= dwarf2_per_objfile->ranges.size)
10121     {
10122       complaint (&symfile_complaints,
10123                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10124                  offset);
10125       return 0;
10126     }
10127   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10128
10129   /* Read in the largest possible address.  */
10130   marker = read_address (obfd, buffer, cu, &dummy);
10131   if ((marker & mask) == mask)
10132     {
10133       /* If we found the largest possible address, then
10134          read the base address.  */
10135       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10136       buffer += 2 * addr_size;
10137       offset += 2 * addr_size;
10138       found_base = 1;
10139     }
10140
10141   low_set = 0;
10142
10143   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10144
10145   while (1)
10146     {
10147       CORE_ADDR range_beginning, range_end;
10148
10149       range_beginning = read_address (obfd, buffer, cu, &dummy);
10150       buffer += addr_size;
10151       range_end = read_address (obfd, buffer, cu, &dummy);
10152       buffer += addr_size;
10153       offset += 2 * addr_size;
10154
10155       /* An end of list marker is a pair of zero addresses.  */
10156       if (range_beginning == 0 && range_end == 0)
10157         /* Found the end of list entry.  */
10158         break;
10159
10160       /* Each base address selection entry is a pair of 2 values.
10161          The first is the largest possible address, the second is
10162          the base address.  Check for a base address here.  */
10163       if ((range_beginning & mask) == mask)
10164         {
10165           /* If we found the largest possible address, then
10166              read the base address.  */
10167           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10168           found_base = 1;
10169           continue;
10170         }
10171
10172       if (!found_base)
10173         {
10174           /* We have no valid base address for the ranges
10175              data.  */
10176           complaint (&symfile_complaints,
10177                      _("Invalid .debug_ranges data (no base address)"));
10178           return 0;
10179         }
10180
10181       if (range_beginning > range_end)
10182         {
10183           /* Inverted range entries are invalid.  */
10184           complaint (&symfile_complaints,
10185                      _("Invalid .debug_ranges data (inverted range)"));
10186           return 0;
10187         }
10188
10189       /* Empty range entries have no effect.  */
10190       if (range_beginning == range_end)
10191         continue;
10192
10193       range_beginning += base;
10194       range_end += base;
10195
10196       /* A not-uncommon case of bad debug info.
10197          Don't pollute the addrmap with bad data.  */
10198       if (range_beginning + baseaddr == 0
10199           && !dwarf2_per_objfile->has_section_at_zero)
10200         {
10201           complaint (&symfile_complaints,
10202                      _(".debug_ranges entry has start address of zero"
10203                        " [in module %s]"), objfile->name);
10204           continue;
10205         }
10206
10207       if (ranges_pst != NULL)
10208         addrmap_set_empty (objfile->psymtabs_addrmap,
10209                            range_beginning + baseaddr,
10210                            range_end - 1 + baseaddr,
10211                            ranges_pst);
10212
10213       /* FIXME: This is recording everything as a low-high
10214          segment of consecutive addresses.  We should have a
10215          data structure for discontiguous block ranges
10216          instead.  */
10217       if (! low_set)
10218         {
10219           low = range_beginning;
10220           high = range_end;
10221           low_set = 1;
10222         }
10223       else
10224         {
10225           if (range_beginning < low)
10226             low = range_beginning;
10227           if (range_end > high)
10228             high = range_end;
10229         }
10230     }
10231
10232   if (! low_set)
10233     /* If the first entry is an end-of-list marker, the range
10234        describes an empty scope, i.e. no instructions.  */
10235     return 0;
10236
10237   if (low_return)
10238     *low_return = low;
10239   if (high_return)
10240     *high_return = high;
10241   return 1;
10242 }
10243
10244 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10245    are present and valid, otherwise, return 0.  Return -1 if the range is
10246    discontinuous, i.e. derived from DW_AT_ranges information.  */
10247
10248 static int
10249 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10250                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10251                       struct partial_symtab *pst)
10252 {
10253   struct attribute *attr;
10254   struct attribute *attr_high;
10255   CORE_ADDR low = 0;
10256   CORE_ADDR high = 0;
10257   int ret = 0;
10258
10259   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10260   if (attr_high)
10261     {
10262       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10263       if (attr)
10264         {
10265           low = DW_ADDR (attr);
10266           if (attr_high->form == DW_FORM_addr
10267               || attr_high->form == DW_FORM_GNU_addr_index)
10268             high = DW_ADDR (attr_high);
10269           else
10270             high = low + DW_UNSND (attr_high);
10271         }
10272       else
10273         /* Found high w/o low attribute.  */
10274         return 0;
10275
10276       /* Found consecutive range of addresses.  */
10277       ret = 1;
10278     }
10279   else
10280     {
10281       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10282       if (attr != NULL)
10283         {
10284           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10285              We take advantage of the fact that DW_AT_ranges does not appear
10286              in DW_TAG_compile_unit of DWO files.  */
10287           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10288           unsigned int ranges_offset = (DW_UNSND (attr)
10289                                         + (need_ranges_base
10290                                            ? cu->ranges_base
10291                                            : 0));
10292
10293           /* Value of the DW_AT_ranges attribute is the offset in the
10294              .debug_ranges section.  */
10295           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10296             return 0;
10297           /* Found discontinuous range of addresses.  */
10298           ret = -1;
10299         }
10300     }
10301
10302   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10303   if (high <= low)
10304     return 0;
10305
10306   /* When using the GNU linker, .gnu.linkonce. sections are used to
10307      eliminate duplicate copies of functions and vtables and such.
10308      The linker will arbitrarily choose one and discard the others.
10309      The AT_*_pc values for such functions refer to local labels in
10310      these sections.  If the section from that file was discarded, the
10311      labels are not in the output, so the relocs get a value of 0.
10312      If this is a discarded function, mark the pc bounds as invalid,
10313      so that GDB will ignore it.  */
10314   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10315     return 0;
10316
10317   *lowpc = low;
10318   if (highpc)
10319     *highpc = high;
10320   return ret;
10321 }
10322
10323 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10324    its low and high PC addresses.  Do nothing if these addresses could not
10325    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10326    and HIGHPC to the high address if greater than HIGHPC.  */
10327
10328 static void
10329 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10330                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10331                                  struct dwarf2_cu *cu)
10332 {
10333   CORE_ADDR low, high;
10334   struct die_info *child = die->child;
10335
10336   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10337     {
10338       *lowpc = min (*lowpc, low);
10339       *highpc = max (*highpc, high);
10340     }
10341
10342   /* If the language does not allow nested subprograms (either inside
10343      subprograms or lexical blocks), we're done.  */
10344   if (cu->language != language_ada)
10345     return;
10346
10347   /* Check all the children of the given DIE.  If it contains nested
10348      subprograms, then check their pc bounds.  Likewise, we need to
10349      check lexical blocks as well, as they may also contain subprogram
10350      definitions.  */
10351   while (child && child->tag)
10352     {
10353       if (child->tag == DW_TAG_subprogram
10354           || child->tag == DW_TAG_lexical_block)
10355         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10356       child = sibling_die (child);
10357     }
10358 }
10359
10360 /* Get the low and high pc's represented by the scope DIE, and store
10361    them in *LOWPC and *HIGHPC.  If the correct values can't be
10362    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10363
10364 static void
10365 get_scope_pc_bounds (struct die_info *die,
10366                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10367                      struct dwarf2_cu *cu)
10368 {
10369   CORE_ADDR best_low = (CORE_ADDR) -1;
10370   CORE_ADDR best_high = (CORE_ADDR) 0;
10371   CORE_ADDR current_low, current_high;
10372
10373   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10374     {
10375       best_low = current_low;
10376       best_high = current_high;
10377     }
10378   else
10379     {
10380       struct die_info *child = die->child;
10381
10382       while (child && child->tag)
10383         {
10384           switch (child->tag) {
10385           case DW_TAG_subprogram:
10386             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10387             break;
10388           case DW_TAG_namespace:
10389           case DW_TAG_module:
10390             /* FIXME: carlton/2004-01-16: Should we do this for
10391                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10392                that current GCC's always emit the DIEs corresponding
10393                to definitions of methods of classes as children of a
10394                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10395                the DIEs giving the declarations, which could be
10396                anywhere).  But I don't see any reason why the
10397                standards says that they have to be there.  */
10398             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10399
10400             if (current_low != ((CORE_ADDR) -1))
10401               {
10402                 best_low = min (best_low, current_low);
10403                 best_high = max (best_high, current_high);
10404               }
10405             break;
10406           default:
10407             /* Ignore.  */
10408             break;
10409           }
10410
10411           child = sibling_die (child);
10412         }
10413     }
10414
10415   *lowpc = best_low;
10416   *highpc = best_high;
10417 }
10418
10419 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10420    in DIE.  */
10421
10422 static void
10423 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10424                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10425 {
10426   struct objfile *objfile = cu->objfile;
10427   struct attribute *attr;
10428   struct attribute *attr_high;
10429
10430   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10431   if (attr_high)
10432     {
10433       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10434       if (attr)
10435         {
10436           CORE_ADDR low = DW_ADDR (attr);
10437           CORE_ADDR high;
10438           if (attr_high->form == DW_FORM_addr
10439               || attr_high->form == DW_FORM_GNU_addr_index)
10440             high = DW_ADDR (attr_high);
10441           else
10442             high = low + DW_UNSND (attr_high);
10443
10444           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10445         }
10446     }
10447
10448   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10449   if (attr)
10450     {
10451       bfd *obfd = objfile->obfd;
10452       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10453          We take advantage of the fact that DW_AT_ranges does not appear
10454          in DW_TAG_compile_unit of DWO files.  */
10455       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10456
10457       /* The value of the DW_AT_ranges attribute is the offset of the
10458          address range list in the .debug_ranges section.  */
10459       unsigned long offset = (DW_UNSND (attr)
10460                               + (need_ranges_base ? cu->ranges_base : 0));
10461       const gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10462
10463       /* For some target architectures, but not others, the
10464          read_address function sign-extends the addresses it returns.
10465          To recognize base address selection entries, we need a
10466          mask.  */
10467       unsigned int addr_size = cu->header.addr_size;
10468       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10469
10470       /* The base address, to which the next pair is relative.  Note
10471          that this 'base' is a DWARF concept: most entries in a range
10472          list are relative, to reduce the number of relocs against the
10473          debugging information.  This is separate from this function's
10474          'baseaddr' argument, which GDB uses to relocate debugging
10475          information from a shared library based on the address at
10476          which the library was loaded.  */
10477       CORE_ADDR base = cu->base_address;
10478       int base_known = cu->base_known;
10479
10480       gdb_assert (dwarf2_per_objfile->ranges.readin);
10481       if (offset >= dwarf2_per_objfile->ranges.size)
10482         {
10483           complaint (&symfile_complaints,
10484                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10485                      offset);
10486           return;
10487         }
10488
10489       for (;;)
10490         {
10491           unsigned int bytes_read;
10492           CORE_ADDR start, end;
10493
10494           start = read_address (obfd, buffer, cu, &bytes_read);
10495           buffer += bytes_read;
10496           end = read_address (obfd, buffer, cu, &bytes_read);
10497           buffer += bytes_read;
10498
10499           /* Did we find the end of the range list?  */
10500           if (start == 0 && end == 0)
10501             break;
10502
10503           /* Did we find a base address selection entry?  */
10504           else if ((start & base_select_mask) == base_select_mask)
10505             {
10506               base = end;
10507               base_known = 1;
10508             }
10509
10510           /* We found an ordinary address range.  */
10511           else
10512             {
10513               if (!base_known)
10514                 {
10515                   complaint (&symfile_complaints,
10516                              _("Invalid .debug_ranges data "
10517                                "(no base address)"));
10518                   return;
10519                 }
10520
10521               if (start > end)
10522                 {
10523                   /* Inverted range entries are invalid.  */
10524                   complaint (&symfile_complaints,
10525                              _("Invalid .debug_ranges data "
10526                                "(inverted range)"));
10527                   return;
10528                 }
10529
10530               /* Empty range entries have no effect.  */
10531               if (start == end)
10532                 continue;
10533
10534               start += base + baseaddr;
10535               end += base + baseaddr;
10536
10537               /* A not-uncommon case of bad debug info.
10538                  Don't pollute the addrmap with bad data.  */
10539               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10540                 {
10541                   complaint (&symfile_complaints,
10542                              _(".debug_ranges entry has start address of zero"
10543                                " [in module %s]"), objfile->name);
10544                   continue;
10545                 }
10546
10547               record_block_range (block, start, end - 1);
10548             }
10549         }
10550     }
10551 }
10552
10553 /* Check whether the producer field indicates either of GCC < 4.6, or the
10554    Intel C/C++ compiler, and cache the result in CU.  */
10555
10556 static void
10557 check_producer (struct dwarf2_cu *cu)
10558 {
10559   const char *cs;
10560   int major, minor, release;
10561
10562   if (cu->producer == NULL)
10563     {
10564       /* For unknown compilers expect their behavior is DWARF version
10565          compliant.
10566
10567          GCC started to support .debug_types sections by -gdwarf-4 since
10568          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10569          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10570          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10571          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10572     }
10573   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10574     {
10575       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10576
10577       cs = &cu->producer[strlen ("GNU ")];
10578       while (*cs && !isdigit (*cs))
10579         cs++;
10580       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10581         {
10582           /* Not recognized as GCC.  */
10583         }
10584       else
10585         {
10586           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10587           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10588         }
10589     }
10590   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10591     cu->producer_is_icc = 1;
10592   else
10593     {
10594       /* For other non-GCC compilers, expect their behavior is DWARF version
10595          compliant.  */
10596     }
10597
10598   cu->checked_producer = 1;
10599 }
10600
10601 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10602    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10603    during 4.6.0 experimental.  */
10604
10605 static int
10606 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10607 {
10608   if (!cu->checked_producer)
10609     check_producer (cu);
10610
10611   return cu->producer_is_gxx_lt_4_6;
10612 }
10613
10614 /* Return the default accessibility type if it is not overriden by
10615    DW_AT_accessibility.  */
10616
10617 static enum dwarf_access_attribute
10618 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10619 {
10620   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10621     {
10622       /* The default DWARF 2 accessibility for members is public, the default
10623          accessibility for inheritance is private.  */
10624
10625       if (die->tag != DW_TAG_inheritance)
10626         return DW_ACCESS_public;
10627       else
10628         return DW_ACCESS_private;
10629     }
10630   else
10631     {
10632       /* DWARF 3+ defines the default accessibility a different way.  The same
10633          rules apply now for DW_TAG_inheritance as for the members and it only
10634          depends on the container kind.  */
10635
10636       if (die->parent->tag == DW_TAG_class_type)
10637         return DW_ACCESS_private;
10638       else
10639         return DW_ACCESS_public;
10640     }
10641 }
10642
10643 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10644    offset.  If the attribute was not found return 0, otherwise return
10645    1.  If it was found but could not properly be handled, set *OFFSET
10646    to 0.  */
10647
10648 static int
10649 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10650                              LONGEST *offset)
10651 {
10652   struct attribute *attr;
10653
10654   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10655   if (attr != NULL)
10656     {
10657       *offset = 0;
10658
10659       /* Note that we do not check for a section offset first here.
10660          This is because DW_AT_data_member_location is new in DWARF 4,
10661          so if we see it, we can assume that a constant form is really
10662          a constant and not a section offset.  */
10663       if (attr_form_is_constant (attr))
10664         *offset = dwarf2_get_attr_constant_value (attr, 0);
10665       else if (attr_form_is_section_offset (attr))
10666         dwarf2_complex_location_expr_complaint ();
10667       else if (attr_form_is_block (attr))
10668         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10669       else
10670         dwarf2_complex_location_expr_complaint ();
10671
10672       return 1;
10673     }
10674
10675   return 0;
10676 }
10677
10678 /* Add an aggregate field to the field list.  */
10679
10680 static void
10681 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10682                   struct dwarf2_cu *cu)
10683 {
10684   struct objfile *objfile = cu->objfile;
10685   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10686   struct nextfield *new_field;
10687   struct attribute *attr;
10688   struct field *fp;
10689   const char *fieldname = "";
10690
10691   /* Allocate a new field list entry and link it in.  */
10692   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10693   make_cleanup (xfree, new_field);
10694   memset (new_field, 0, sizeof (struct nextfield));
10695
10696   if (die->tag == DW_TAG_inheritance)
10697     {
10698       new_field->next = fip->baseclasses;
10699       fip->baseclasses = new_field;
10700     }
10701   else
10702     {
10703       new_field->next = fip->fields;
10704       fip->fields = new_field;
10705     }
10706   fip->nfields++;
10707
10708   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10709   if (attr)
10710     new_field->accessibility = DW_UNSND (attr);
10711   else
10712     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10713   if (new_field->accessibility != DW_ACCESS_public)
10714     fip->non_public_fields = 1;
10715
10716   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10717   if (attr)
10718     new_field->virtuality = DW_UNSND (attr);
10719   else
10720     new_field->virtuality = DW_VIRTUALITY_none;
10721
10722   fp = &new_field->field;
10723
10724   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10725     {
10726       LONGEST offset;
10727
10728       /* Data member other than a C++ static data member.  */
10729
10730       /* Get type of field.  */
10731       fp->type = die_type (die, cu);
10732
10733       SET_FIELD_BITPOS (*fp, 0);
10734
10735       /* Get bit size of field (zero if none).  */
10736       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10737       if (attr)
10738         {
10739           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10740         }
10741       else
10742         {
10743           FIELD_BITSIZE (*fp) = 0;
10744         }
10745
10746       /* Get bit offset of field.  */
10747       if (handle_data_member_location (die, cu, &offset))
10748         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10749       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10750       if (attr)
10751         {
10752           if (gdbarch_bits_big_endian (gdbarch))
10753             {
10754               /* For big endian bits, the DW_AT_bit_offset gives the
10755                  additional bit offset from the MSB of the containing
10756                  anonymous object to the MSB of the field.  We don't
10757                  have to do anything special since we don't need to
10758                  know the size of the anonymous object.  */
10759               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10760             }
10761           else
10762             {
10763               /* For little endian bits, compute the bit offset to the
10764                  MSB of the anonymous object, subtract off the number of
10765                  bits from the MSB of the field to the MSB of the
10766                  object, and then subtract off the number of bits of
10767                  the field itself.  The result is the bit offset of
10768                  the LSB of the field.  */
10769               int anonymous_size;
10770               int bit_offset = DW_UNSND (attr);
10771
10772               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10773               if (attr)
10774                 {
10775                   /* The size of the anonymous object containing
10776                      the bit field is explicit, so use the
10777                      indicated size (in bytes).  */
10778                   anonymous_size = DW_UNSND (attr);
10779                 }
10780               else
10781                 {
10782                   /* The size of the anonymous object containing
10783                      the bit field must be inferred from the type
10784                      attribute of the data member containing the
10785                      bit field.  */
10786                   anonymous_size = TYPE_LENGTH (fp->type);
10787                 }
10788               SET_FIELD_BITPOS (*fp,
10789                                 (FIELD_BITPOS (*fp)
10790                                  + anonymous_size * bits_per_byte
10791                                  - bit_offset - FIELD_BITSIZE (*fp)));
10792             }
10793         }
10794
10795       /* Get name of field.  */
10796       fieldname = dwarf2_name (die, cu);
10797       if (fieldname == NULL)
10798         fieldname = "";
10799
10800       /* The name is already allocated along with this objfile, so we don't
10801          need to duplicate it for the type.  */
10802       fp->name = fieldname;
10803
10804       /* Change accessibility for artificial fields (e.g. virtual table
10805          pointer or virtual base class pointer) to private.  */
10806       if (dwarf2_attr (die, DW_AT_artificial, cu))
10807         {
10808           FIELD_ARTIFICIAL (*fp) = 1;
10809           new_field->accessibility = DW_ACCESS_private;
10810           fip->non_public_fields = 1;
10811         }
10812     }
10813   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10814     {
10815       /* C++ static member.  */
10816
10817       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10818          is a declaration, but all versions of G++ as of this writing
10819          (so through at least 3.2.1) incorrectly generate
10820          DW_TAG_variable tags.  */
10821
10822       const char *physname;
10823
10824       /* Get name of field.  */
10825       fieldname = dwarf2_name (die, cu);
10826       if (fieldname == NULL)
10827         return;
10828
10829       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10830       if (attr
10831           /* Only create a symbol if this is an external value.
10832              new_symbol checks this and puts the value in the global symbol
10833              table, which we want.  If it is not external, new_symbol
10834              will try to put the value in cu->list_in_scope which is wrong.  */
10835           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10836         {
10837           /* A static const member, not much different than an enum as far as
10838              we're concerned, except that we can support more types.  */
10839           new_symbol (die, NULL, cu);
10840         }
10841
10842       /* Get physical name.  */
10843       physname = dwarf2_physname (fieldname, die, cu);
10844
10845       /* The name is already allocated along with this objfile, so we don't
10846          need to duplicate it for the type.  */
10847       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10848       FIELD_TYPE (*fp) = die_type (die, cu);
10849       FIELD_NAME (*fp) = fieldname;
10850     }
10851   else if (die->tag == DW_TAG_inheritance)
10852     {
10853       LONGEST offset;
10854
10855       /* C++ base class field.  */
10856       if (handle_data_member_location (die, cu, &offset))
10857         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10858       FIELD_BITSIZE (*fp) = 0;
10859       FIELD_TYPE (*fp) = die_type (die, cu);
10860       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10861       fip->nbaseclasses++;
10862     }
10863 }
10864
10865 /* Add a typedef defined in the scope of the FIP's class.  */
10866
10867 static void
10868 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10869                     struct dwarf2_cu *cu)
10870 {
10871   struct objfile *objfile = cu->objfile;
10872   struct typedef_field_list *new_field;
10873   struct attribute *attr;
10874   struct typedef_field *fp;
10875   char *fieldname = "";
10876
10877   /* Allocate a new field list entry and link it in.  */
10878   new_field = xzalloc (sizeof (*new_field));
10879   make_cleanup (xfree, new_field);
10880
10881   gdb_assert (die->tag == DW_TAG_typedef);
10882
10883   fp = &new_field->field;
10884
10885   /* Get name of field.  */
10886   fp->name = dwarf2_name (die, cu);
10887   if (fp->name == NULL)
10888     return;
10889
10890   fp->type = read_type_die (die, cu);
10891
10892   new_field->next = fip->typedef_field_list;
10893   fip->typedef_field_list = new_field;
10894   fip->typedef_field_list_count++;
10895 }
10896
10897 /* Create the vector of fields, and attach it to the type.  */
10898
10899 static void
10900 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10901                               struct dwarf2_cu *cu)
10902 {
10903   int nfields = fip->nfields;
10904
10905   /* Record the field count, allocate space for the array of fields,
10906      and create blank accessibility bitfields if necessary.  */
10907   TYPE_NFIELDS (type) = nfields;
10908   TYPE_FIELDS (type) = (struct field *)
10909     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10910   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10911
10912   if (fip->non_public_fields && cu->language != language_ada)
10913     {
10914       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10915
10916       TYPE_FIELD_PRIVATE_BITS (type) =
10917         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10918       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10919
10920       TYPE_FIELD_PROTECTED_BITS (type) =
10921         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10922       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10923
10924       TYPE_FIELD_IGNORE_BITS (type) =
10925         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10926       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10927     }
10928
10929   /* If the type has baseclasses, allocate and clear a bit vector for
10930      TYPE_FIELD_VIRTUAL_BITS.  */
10931   if (fip->nbaseclasses && cu->language != language_ada)
10932     {
10933       int num_bytes = B_BYTES (fip->nbaseclasses);
10934       unsigned char *pointer;
10935
10936       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10937       pointer = TYPE_ALLOC (type, num_bytes);
10938       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10939       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10940       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10941     }
10942
10943   /* Copy the saved-up fields into the field vector.  Start from the head of
10944      the list, adding to the tail of the field array, so that they end up in
10945      the same order in the array in which they were added to the list.  */
10946   while (nfields-- > 0)
10947     {
10948       struct nextfield *fieldp;
10949
10950       if (fip->fields)
10951         {
10952           fieldp = fip->fields;
10953           fip->fields = fieldp->next;
10954         }
10955       else
10956         {
10957           fieldp = fip->baseclasses;
10958           fip->baseclasses = fieldp->next;
10959         }
10960
10961       TYPE_FIELD (type, nfields) = fieldp->field;
10962       switch (fieldp->accessibility)
10963         {
10964         case DW_ACCESS_private:
10965           if (cu->language != language_ada)
10966             SET_TYPE_FIELD_PRIVATE (type, nfields);
10967           break;
10968
10969         case DW_ACCESS_protected:
10970           if (cu->language != language_ada)
10971             SET_TYPE_FIELD_PROTECTED (type, nfields);
10972           break;
10973
10974         case DW_ACCESS_public:
10975           break;
10976
10977         default:
10978           /* Unknown accessibility.  Complain and treat it as public.  */
10979           {
10980             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10981                        fieldp->accessibility);
10982           }
10983           break;
10984         }
10985       if (nfields < fip->nbaseclasses)
10986         {
10987           switch (fieldp->virtuality)
10988             {
10989             case DW_VIRTUALITY_virtual:
10990             case DW_VIRTUALITY_pure_virtual:
10991               if (cu->language == language_ada)
10992                 error (_("unexpected virtuality in component of Ada type"));
10993               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10994               break;
10995             }
10996         }
10997     }
10998 }
10999
11000 /* Return true if this member function is a constructor, false
11001    otherwise.  */
11002
11003 static int
11004 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11005 {
11006   const char *fieldname;
11007   const char *typename;
11008   int len;
11009
11010   if (die->parent == NULL)
11011     return 0;
11012
11013   if (die->parent->tag != DW_TAG_structure_type
11014       && die->parent->tag != DW_TAG_union_type
11015       && die->parent->tag != DW_TAG_class_type)
11016     return 0;
11017
11018   fieldname = dwarf2_name (die, cu);
11019   typename = dwarf2_name (die->parent, cu);
11020   if (fieldname == NULL || typename == NULL)
11021     return 0;
11022
11023   len = strlen (fieldname);
11024   return (strncmp (fieldname, typename, len) == 0
11025           && (typename[len] == '\0' || typename[len] == '<'));
11026 }
11027
11028 /* Add a member function to the proper fieldlist.  */
11029
11030 static void
11031 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11032                       struct type *type, struct dwarf2_cu *cu)
11033 {
11034   struct objfile *objfile = cu->objfile;
11035   struct attribute *attr;
11036   struct fnfieldlist *flp;
11037   int i;
11038   struct fn_field *fnp;
11039   const char *fieldname;
11040   struct nextfnfield *new_fnfield;
11041   struct type *this_type;
11042   enum dwarf_access_attribute accessibility;
11043
11044   if (cu->language == language_ada)
11045     error (_("unexpected member function in Ada type"));
11046
11047   /* Get name of member function.  */
11048   fieldname = dwarf2_name (die, cu);
11049   if (fieldname == NULL)
11050     return;
11051
11052   /* Look up member function name in fieldlist.  */
11053   for (i = 0; i < fip->nfnfields; i++)
11054     {
11055       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11056         break;
11057     }
11058
11059   /* Create new list element if necessary.  */
11060   if (i < fip->nfnfields)
11061     flp = &fip->fnfieldlists[i];
11062   else
11063     {
11064       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11065         {
11066           fip->fnfieldlists = (struct fnfieldlist *)
11067             xrealloc (fip->fnfieldlists,
11068                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11069                       * sizeof (struct fnfieldlist));
11070           if (fip->nfnfields == 0)
11071             make_cleanup (free_current_contents, &fip->fnfieldlists);
11072         }
11073       flp = &fip->fnfieldlists[fip->nfnfields];
11074       flp->name = fieldname;
11075       flp->length = 0;
11076       flp->head = NULL;
11077       i = fip->nfnfields++;
11078     }
11079
11080   /* Create a new member function field and chain it to the field list
11081      entry.  */
11082   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11083   make_cleanup (xfree, new_fnfield);
11084   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11085   new_fnfield->next = flp->head;
11086   flp->head = new_fnfield;
11087   flp->length++;
11088
11089   /* Fill in the member function field info.  */
11090   fnp = &new_fnfield->fnfield;
11091
11092   /* Delay processing of the physname until later.  */
11093   if (cu->language == language_cplus || cu->language == language_java)
11094     {
11095       add_to_method_list (type, i, flp->length - 1, fieldname,
11096                           die, cu);
11097     }
11098   else
11099     {
11100       const char *physname = dwarf2_physname (fieldname, die, cu);
11101       fnp->physname = physname ? physname : "";
11102     }
11103
11104   fnp->type = alloc_type (objfile);
11105   this_type = read_type_die (die, cu);
11106   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11107     {
11108       int nparams = TYPE_NFIELDS (this_type);
11109
11110       /* TYPE is the domain of this method, and THIS_TYPE is the type
11111            of the method itself (TYPE_CODE_METHOD).  */
11112       smash_to_method_type (fnp->type, type,
11113                             TYPE_TARGET_TYPE (this_type),
11114                             TYPE_FIELDS (this_type),
11115                             TYPE_NFIELDS (this_type),
11116                             TYPE_VARARGS (this_type));
11117
11118       /* Handle static member functions.
11119          Dwarf2 has no clean way to discern C++ static and non-static
11120          member functions.  G++ helps GDB by marking the first
11121          parameter for non-static member functions (which is the this
11122          pointer) as artificial.  We obtain this information from
11123          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11124       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11125         fnp->voffset = VOFFSET_STATIC;
11126     }
11127   else
11128     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11129                dwarf2_full_name (fieldname, die, cu));
11130
11131   /* Get fcontext from DW_AT_containing_type if present.  */
11132   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11133     fnp->fcontext = die_containing_type (die, cu);
11134
11135   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11136      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11137
11138   /* Get accessibility.  */
11139   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11140   if (attr)
11141     accessibility = DW_UNSND (attr);
11142   else
11143     accessibility = dwarf2_default_access_attribute (die, cu);
11144   switch (accessibility)
11145     {
11146     case DW_ACCESS_private:
11147       fnp->is_private = 1;
11148       break;
11149     case DW_ACCESS_protected:
11150       fnp->is_protected = 1;
11151       break;
11152     }
11153
11154   /* Check for artificial methods.  */
11155   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11156   if (attr && DW_UNSND (attr) != 0)
11157     fnp->is_artificial = 1;
11158
11159   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11160
11161   /* Get index in virtual function table if it is a virtual member
11162      function.  For older versions of GCC, this is an offset in the
11163      appropriate virtual table, as specified by DW_AT_containing_type.
11164      For everyone else, it is an expression to be evaluated relative
11165      to the object address.  */
11166
11167   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11168   if (attr)
11169     {
11170       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11171         {
11172           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11173             {
11174               /* Old-style GCC.  */
11175               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11176             }
11177           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11178                    || (DW_BLOCK (attr)->size > 1
11179                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11180                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11181             {
11182               struct dwarf_block blk;
11183               int offset;
11184
11185               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11186                         ? 1 : 2);
11187               blk.size = DW_BLOCK (attr)->size - offset;
11188               blk.data = DW_BLOCK (attr)->data + offset;
11189               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11190               if ((fnp->voffset % cu->header.addr_size) != 0)
11191                 dwarf2_complex_location_expr_complaint ();
11192               else
11193                 fnp->voffset /= cu->header.addr_size;
11194               fnp->voffset += 2;
11195             }
11196           else
11197             dwarf2_complex_location_expr_complaint ();
11198
11199           if (!fnp->fcontext)
11200             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11201         }
11202       else if (attr_form_is_section_offset (attr))
11203         {
11204           dwarf2_complex_location_expr_complaint ();
11205         }
11206       else
11207         {
11208           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11209                                                  fieldname);
11210         }
11211     }
11212   else
11213     {
11214       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11215       if (attr && DW_UNSND (attr))
11216         {
11217           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11218           complaint (&symfile_complaints,
11219                      _("Member function \"%s\" (offset %d) is virtual "
11220                        "but the vtable offset is not specified"),
11221                      fieldname, die->offset.sect_off);
11222           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11223           TYPE_CPLUS_DYNAMIC (type) = 1;
11224         }
11225     }
11226 }
11227
11228 /* Create the vector of member function fields, and attach it to the type.  */
11229
11230 static void
11231 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11232                                  struct dwarf2_cu *cu)
11233 {
11234   struct fnfieldlist *flp;
11235   int i;
11236
11237   if (cu->language == language_ada)
11238     error (_("unexpected member functions in Ada type"));
11239
11240   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11241   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11242     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11243
11244   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11245     {
11246       struct nextfnfield *nfp = flp->head;
11247       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11248       int k;
11249
11250       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11251       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11252       fn_flp->fn_fields = (struct fn_field *)
11253         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11254       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11255         fn_flp->fn_fields[k] = nfp->fnfield;
11256     }
11257
11258   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11259 }
11260
11261 /* Returns non-zero if NAME is the name of a vtable member in CU's
11262    language, zero otherwise.  */
11263 static int
11264 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11265 {
11266   static const char vptr[] = "_vptr";
11267   static const char vtable[] = "vtable";
11268
11269   /* Look for the C++ and Java forms of the vtable.  */
11270   if ((cu->language == language_java
11271        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11272        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11273        && is_cplus_marker (name[sizeof (vptr) - 1])))
11274     return 1;
11275
11276   return 0;
11277 }
11278
11279 /* GCC outputs unnamed structures that are really pointers to member
11280    functions, with the ABI-specified layout.  If TYPE describes
11281    such a structure, smash it into a member function type.
11282
11283    GCC shouldn't do this; it should just output pointer to member DIEs.
11284    This is GCC PR debug/28767.  */
11285
11286 static void
11287 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11288 {
11289   struct type *pfn_type, *domain_type, *new_type;
11290
11291   /* Check for a structure with no name and two children.  */
11292   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11293     return;
11294
11295   /* Check for __pfn and __delta members.  */
11296   if (TYPE_FIELD_NAME (type, 0) == NULL
11297       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11298       || TYPE_FIELD_NAME (type, 1) == NULL
11299       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11300     return;
11301
11302   /* Find the type of the method.  */
11303   pfn_type = TYPE_FIELD_TYPE (type, 0);
11304   if (pfn_type == NULL
11305       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11306       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11307     return;
11308
11309   /* Look for the "this" argument.  */
11310   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11311   if (TYPE_NFIELDS (pfn_type) == 0
11312       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11313       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11314     return;
11315
11316   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11317   new_type = alloc_type (objfile);
11318   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11319                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11320                         TYPE_VARARGS (pfn_type));
11321   smash_to_methodptr_type (type, new_type);
11322 }
11323
11324 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11325    (icc).  */
11326
11327 static int
11328 producer_is_icc (struct dwarf2_cu *cu)
11329 {
11330   if (!cu->checked_producer)
11331     check_producer (cu);
11332
11333   return cu->producer_is_icc;
11334 }
11335
11336 /* Called when we find the DIE that starts a structure or union scope
11337    (definition) to create a type for the structure or union.  Fill in
11338    the type's name and general properties; the members will not be
11339    processed until process_structure_scope.
11340
11341    NOTE: we need to call these functions regardless of whether or not the
11342    DIE has a DW_AT_name attribute, since it might be an anonymous
11343    structure or union.  This gets the type entered into our set of
11344    user defined types.
11345
11346    However, if the structure is incomplete (an opaque struct/union)
11347    then suppress creating a symbol table entry for it since gdb only
11348    wants to find the one with the complete definition.  Note that if
11349    it is complete, we just call new_symbol, which does it's own
11350    checking about whether the struct/union is anonymous or not (and
11351    suppresses creating a symbol table entry itself).  */
11352
11353 static struct type *
11354 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11355 {
11356   struct objfile *objfile = cu->objfile;
11357   struct type *type;
11358   struct attribute *attr;
11359   const char *name;
11360
11361   /* If the definition of this type lives in .debug_types, read that type.
11362      Don't follow DW_AT_specification though, that will take us back up
11363      the chain and we want to go down.  */
11364   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11365   if (attr)
11366     {
11367       struct dwarf2_cu *type_cu = cu;
11368       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11369
11370       /* We could just recurse on read_structure_type, but we need to call
11371          get_die_type to ensure only one type for this DIE is created.
11372          This is important, for example, because for c++ classes we need
11373          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11374       type = read_type_die (type_die, type_cu);
11375
11376       /* TYPE_CU may not be the same as CU.
11377          Ensure TYPE is recorded with CU in die_type_hash.  */
11378       return set_die_type (die, type, cu);
11379     }
11380
11381   type = alloc_type (objfile);
11382   INIT_CPLUS_SPECIFIC (type);
11383
11384   name = dwarf2_name (die, cu);
11385   if (name != NULL)
11386     {
11387       if (cu->language == language_cplus
11388           || cu->language == language_java)
11389         {
11390           const char *full_name = dwarf2_full_name (name, die, cu);
11391
11392           /* dwarf2_full_name might have already finished building the DIE's
11393              type.  If so, there is no need to continue.  */
11394           if (get_die_type (die, cu) != NULL)
11395             return get_die_type (die, cu);
11396
11397           TYPE_TAG_NAME (type) = full_name;
11398           if (die->tag == DW_TAG_structure_type
11399               || die->tag == DW_TAG_class_type)
11400             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11401         }
11402       else
11403         {
11404           /* The name is already allocated along with this objfile, so
11405              we don't need to duplicate it for the type.  */
11406           TYPE_TAG_NAME (type) = name;
11407           if (die->tag == DW_TAG_class_type)
11408             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11409         }
11410     }
11411
11412   if (die->tag == DW_TAG_structure_type)
11413     {
11414       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11415     }
11416   else if (die->tag == DW_TAG_union_type)
11417     {
11418       TYPE_CODE (type) = TYPE_CODE_UNION;
11419     }
11420   else
11421     {
11422       TYPE_CODE (type) = TYPE_CODE_CLASS;
11423     }
11424
11425   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11426     TYPE_DECLARED_CLASS (type) = 1;
11427
11428   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11429   if (attr)
11430     {
11431       TYPE_LENGTH (type) = DW_UNSND (attr);
11432     }
11433   else
11434     {
11435       TYPE_LENGTH (type) = 0;
11436     }
11437
11438   if (producer_is_icc (cu))
11439     {
11440       /* ICC does not output the required DW_AT_declaration
11441          on incomplete types, but gives them a size of zero.  */
11442     }
11443   else
11444     TYPE_STUB_SUPPORTED (type) = 1;
11445
11446   if (die_is_declaration (die, cu))
11447     TYPE_STUB (type) = 1;
11448   else if (attr == NULL && die->child == NULL
11449            && producer_is_realview (cu->producer))
11450     /* RealView does not output the required DW_AT_declaration
11451        on incomplete types.  */
11452     TYPE_STUB (type) = 1;
11453
11454   /* We need to add the type field to the die immediately so we don't
11455      infinitely recurse when dealing with pointers to the structure
11456      type within the structure itself.  */
11457   set_die_type (die, type, cu);
11458
11459   /* set_die_type should be already done.  */
11460   set_descriptive_type (type, die, cu);
11461
11462   return type;
11463 }
11464
11465 /* Finish creating a structure or union type, including filling in
11466    its members and creating a symbol for it.  */
11467
11468 static void
11469 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11470 {
11471   struct objfile *objfile = cu->objfile;
11472   struct die_info *child_die = die->child;
11473   struct type *type;
11474
11475   type = get_die_type (die, cu);
11476   if (type == NULL)
11477     type = read_structure_type (die, cu);
11478
11479   if (die->child != NULL && ! die_is_declaration (die, cu))
11480     {
11481       struct field_info fi;
11482       struct die_info *child_die;
11483       VEC (symbolp) *template_args = NULL;
11484       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11485
11486       memset (&fi, 0, sizeof (struct field_info));
11487
11488       child_die = die->child;
11489
11490       while (child_die && child_die->tag)
11491         {
11492           if (child_die->tag == DW_TAG_member
11493               || child_die->tag == DW_TAG_variable)
11494             {
11495               /* NOTE: carlton/2002-11-05: A C++ static data member
11496                  should be a DW_TAG_member that is a declaration, but
11497                  all versions of G++ as of this writing (so through at
11498                  least 3.2.1) incorrectly generate DW_TAG_variable
11499                  tags for them instead.  */
11500               dwarf2_add_field (&fi, child_die, cu);
11501             }
11502           else if (child_die->tag == DW_TAG_subprogram)
11503             {
11504               /* C++ member function.  */
11505               dwarf2_add_member_fn (&fi, child_die, type, cu);
11506             }
11507           else if (child_die->tag == DW_TAG_inheritance)
11508             {
11509               /* C++ base class field.  */
11510               dwarf2_add_field (&fi, child_die, cu);
11511             }
11512           else if (child_die->tag == DW_TAG_typedef)
11513             dwarf2_add_typedef (&fi, child_die, cu);
11514           else if (child_die->tag == DW_TAG_template_type_param
11515                    || child_die->tag == DW_TAG_template_value_param)
11516             {
11517               struct symbol *arg = new_symbol (child_die, NULL, cu);
11518
11519               if (arg != NULL)
11520                 VEC_safe_push (symbolp, template_args, arg);
11521             }
11522
11523           child_die = sibling_die (child_die);
11524         }
11525
11526       /* Attach template arguments to type.  */
11527       if (! VEC_empty (symbolp, template_args))
11528         {
11529           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11530           TYPE_N_TEMPLATE_ARGUMENTS (type)
11531             = VEC_length (symbolp, template_args);
11532           TYPE_TEMPLATE_ARGUMENTS (type)
11533             = obstack_alloc (&objfile->objfile_obstack,
11534                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11535                               * sizeof (struct symbol *)));
11536           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11537                   VEC_address (symbolp, template_args),
11538                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11539                    * sizeof (struct symbol *)));
11540           VEC_free (symbolp, template_args);
11541         }
11542
11543       /* Attach fields and member functions to the type.  */
11544       if (fi.nfields)
11545         dwarf2_attach_fields_to_type (&fi, type, cu);
11546       if (fi.nfnfields)
11547         {
11548           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11549
11550           /* Get the type which refers to the base class (possibly this
11551              class itself) which contains the vtable pointer for the current
11552              class from the DW_AT_containing_type attribute.  This use of
11553              DW_AT_containing_type is a GNU extension.  */
11554
11555           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11556             {
11557               struct type *t = die_containing_type (die, cu);
11558
11559               TYPE_VPTR_BASETYPE (type) = t;
11560               if (type == t)
11561                 {
11562                   int i;
11563
11564                   /* Our own class provides vtbl ptr.  */
11565                   for (i = TYPE_NFIELDS (t) - 1;
11566                        i >= TYPE_N_BASECLASSES (t);
11567                        --i)
11568                     {
11569                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11570
11571                       if (is_vtable_name (fieldname, cu))
11572                         {
11573                           TYPE_VPTR_FIELDNO (type) = i;
11574                           break;
11575                         }
11576                     }
11577
11578                   /* Complain if virtual function table field not found.  */
11579                   if (i < TYPE_N_BASECLASSES (t))
11580                     complaint (&symfile_complaints,
11581                                _("virtual function table pointer "
11582                                  "not found when defining class '%s'"),
11583                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11584                                "");
11585                 }
11586               else
11587                 {
11588                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11589                 }
11590             }
11591           else if (cu->producer
11592                    && strncmp (cu->producer,
11593                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11594             {
11595               /* The IBM XLC compiler does not provide direct indication
11596                  of the containing type, but the vtable pointer is
11597                  always named __vfp.  */
11598
11599               int i;
11600
11601               for (i = TYPE_NFIELDS (type) - 1;
11602                    i >= TYPE_N_BASECLASSES (type);
11603                    --i)
11604                 {
11605                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11606                     {
11607                       TYPE_VPTR_FIELDNO (type) = i;
11608                       TYPE_VPTR_BASETYPE (type) = type;
11609                       break;
11610                     }
11611                 }
11612             }
11613         }
11614
11615       /* Copy fi.typedef_field_list linked list elements content into the
11616          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11617       if (fi.typedef_field_list)
11618         {
11619           int i = fi.typedef_field_list_count;
11620
11621           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11622           TYPE_TYPEDEF_FIELD_ARRAY (type)
11623             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11624           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11625
11626           /* Reverse the list order to keep the debug info elements order.  */
11627           while (--i >= 0)
11628             {
11629               struct typedef_field *dest, *src;
11630
11631               dest = &TYPE_TYPEDEF_FIELD (type, i);
11632               src = &fi.typedef_field_list->field;
11633               fi.typedef_field_list = fi.typedef_field_list->next;
11634               *dest = *src;
11635             }
11636         }
11637
11638       do_cleanups (back_to);
11639
11640       if (HAVE_CPLUS_STRUCT (type))
11641         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11642     }
11643
11644   quirk_gcc_member_function_pointer (type, objfile);
11645
11646   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11647      snapshots) has been known to create a die giving a declaration
11648      for a class that has, as a child, a die giving a definition for a
11649      nested class.  So we have to process our children even if the
11650      current die is a declaration.  Normally, of course, a declaration
11651      won't have any children at all.  */
11652
11653   while (child_die != NULL && child_die->tag)
11654     {
11655       if (child_die->tag == DW_TAG_member
11656           || child_die->tag == DW_TAG_variable
11657           || child_die->tag == DW_TAG_inheritance
11658           || child_die->tag == DW_TAG_template_value_param
11659           || child_die->tag == DW_TAG_template_type_param)
11660         {
11661           /* Do nothing.  */
11662         }
11663       else
11664         process_die (child_die, cu);
11665
11666       child_die = sibling_die (child_die);
11667     }
11668
11669   /* Do not consider external references.  According to the DWARF standard,
11670      these DIEs are identified by the fact that they have no byte_size
11671      attribute, and a declaration attribute.  */
11672   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11673       || !die_is_declaration (die, cu))
11674     new_symbol (die, type, cu);
11675 }
11676
11677 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11678    complete the type's fields yet, or create any symbols.  */
11679
11680 static struct type *
11681 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11682 {
11683   struct objfile *objfile = cu->objfile;
11684   struct type *type;
11685   struct attribute *attr;
11686   const char *name;
11687
11688   /* If the definition of this type lives in .debug_types, read that type.
11689      Don't follow DW_AT_specification though, that will take us back up
11690      the chain and we want to go down.  */
11691   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11692   if (attr)
11693     {
11694       struct dwarf2_cu *type_cu = cu;
11695       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11696
11697       type = read_type_die (type_die, type_cu);
11698
11699       /* TYPE_CU may not be the same as CU.
11700          Ensure TYPE is recorded with CU in die_type_hash.  */
11701       return set_die_type (die, type, cu);
11702     }
11703
11704   type = alloc_type (objfile);
11705
11706   TYPE_CODE (type) = TYPE_CODE_ENUM;
11707   name = dwarf2_full_name (NULL, die, cu);
11708   if (name != NULL)
11709     TYPE_TAG_NAME (type) = name;
11710
11711   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11712   if (attr)
11713     {
11714       TYPE_LENGTH (type) = DW_UNSND (attr);
11715     }
11716   else
11717     {
11718       TYPE_LENGTH (type) = 0;
11719     }
11720
11721   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11722      declared as private in the package spec, and then defined only
11723      inside the package body.  Such types are known as Taft Amendment
11724      Types.  When another package uses such a type, an incomplete DIE
11725      may be generated by the compiler.  */
11726   if (die_is_declaration (die, cu))
11727     TYPE_STUB (type) = 1;
11728
11729   return set_die_type (die, type, cu);
11730 }
11731
11732 /* Given a pointer to a die which begins an enumeration, process all
11733    the dies that define the members of the enumeration, and create the
11734    symbol for the enumeration type.
11735
11736    NOTE: We reverse the order of the element list.  */
11737
11738 static void
11739 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11740 {
11741   struct type *this_type;
11742
11743   this_type = get_die_type (die, cu);
11744   if (this_type == NULL)
11745     this_type = read_enumeration_type (die, cu);
11746
11747   if (die->child != NULL)
11748     {
11749       struct die_info *child_die;
11750       struct symbol *sym;
11751       struct field *fields = NULL;
11752       int num_fields = 0;
11753       int unsigned_enum = 1;
11754       const char *name;
11755       int flag_enum = 1;
11756       ULONGEST mask = 0;
11757
11758       child_die = die->child;
11759       while (child_die && child_die->tag)
11760         {
11761           if (child_die->tag != DW_TAG_enumerator)
11762             {
11763               process_die (child_die, cu);
11764             }
11765           else
11766             {
11767               name = dwarf2_name (child_die, cu);
11768               if (name)
11769                 {
11770                   sym = new_symbol (child_die, this_type, cu);
11771                   if (SYMBOL_VALUE (sym) < 0)
11772                     {
11773                       unsigned_enum = 0;
11774                       flag_enum = 0;
11775                     }
11776                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11777                     flag_enum = 0;
11778                   else
11779                     mask |= SYMBOL_VALUE (sym);
11780
11781                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11782                     {
11783                       fields = (struct field *)
11784                         xrealloc (fields,
11785                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11786                                   * sizeof (struct field));
11787                     }
11788
11789                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11790                   FIELD_TYPE (fields[num_fields]) = NULL;
11791                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11792                   FIELD_BITSIZE (fields[num_fields]) = 0;
11793
11794                   num_fields++;
11795                 }
11796             }
11797
11798           child_die = sibling_die (child_die);
11799         }
11800
11801       if (num_fields)
11802         {
11803           TYPE_NFIELDS (this_type) = num_fields;
11804           TYPE_FIELDS (this_type) = (struct field *)
11805             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11806           memcpy (TYPE_FIELDS (this_type), fields,
11807                   sizeof (struct field) * num_fields);
11808           xfree (fields);
11809         }
11810       if (unsigned_enum)
11811         TYPE_UNSIGNED (this_type) = 1;
11812       if (flag_enum)
11813         TYPE_FLAG_ENUM (this_type) = 1;
11814     }
11815
11816   /* If we are reading an enum from a .debug_types unit, and the enum
11817      is a declaration, and the enum is not the signatured type in the
11818      unit, then we do not want to add a symbol for it.  Adding a
11819      symbol would in some cases obscure the true definition of the
11820      enum, giving users an incomplete type when the definition is
11821      actually available.  Note that we do not want to do this for all
11822      enums which are just declarations, because C++0x allows forward
11823      enum declarations.  */
11824   if (cu->per_cu->is_debug_types
11825       && die_is_declaration (die, cu))
11826     {
11827       struct signatured_type *sig_type;
11828
11829       sig_type = (struct signatured_type *) cu->per_cu;
11830       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11831       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11832         return;
11833     }
11834
11835   new_symbol (die, this_type, cu);
11836 }
11837
11838 /* Extract all information from a DW_TAG_array_type DIE and put it in
11839    the DIE's type field.  For now, this only handles one dimensional
11840    arrays.  */
11841
11842 static struct type *
11843 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11844 {
11845   struct objfile *objfile = cu->objfile;
11846   struct die_info *child_die;
11847   struct type *type;
11848   struct type *element_type, *range_type, *index_type;
11849   struct type **range_types = NULL;
11850   struct attribute *attr;
11851   int ndim = 0;
11852   struct cleanup *back_to;
11853   const char *name;
11854
11855   element_type = die_type (die, cu);
11856
11857   /* The die_type call above may have already set the type for this DIE.  */
11858   type = get_die_type (die, cu);
11859   if (type)
11860     return type;
11861
11862   /* Irix 6.2 native cc creates array types without children for
11863      arrays with unspecified length.  */
11864   if (die->child == NULL)
11865     {
11866       index_type = objfile_type (objfile)->builtin_int;
11867       range_type = create_range_type (NULL, index_type, 0, -1);
11868       type = create_array_type (NULL, element_type, range_type);
11869       return set_die_type (die, type, cu);
11870     }
11871
11872   back_to = make_cleanup (null_cleanup, NULL);
11873   child_die = die->child;
11874   while (child_die && child_die->tag)
11875     {
11876       if (child_die->tag == DW_TAG_subrange_type)
11877         {
11878           struct type *child_type = read_type_die (child_die, cu);
11879
11880           if (child_type != NULL)
11881             {
11882               /* The range type was succesfully read.  Save it for the
11883                  array type creation.  */
11884               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11885                 {
11886                   range_types = (struct type **)
11887                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11888                               * sizeof (struct type *));
11889                   if (ndim == 0)
11890                     make_cleanup (free_current_contents, &range_types);
11891                 }
11892               range_types[ndim++] = child_type;
11893             }
11894         }
11895       child_die = sibling_die (child_die);
11896     }
11897
11898   /* Dwarf2 dimensions are output from left to right, create the
11899      necessary array types in backwards order.  */
11900
11901   type = element_type;
11902
11903   if (read_array_order (die, cu) == DW_ORD_col_major)
11904     {
11905       int i = 0;
11906
11907       while (i < ndim)
11908         type = create_array_type (NULL, type, range_types[i++]);
11909     }
11910   else
11911     {
11912       while (ndim-- > 0)
11913         type = create_array_type (NULL, type, range_types[ndim]);
11914     }
11915
11916   /* Understand Dwarf2 support for vector types (like they occur on
11917      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11918      array type.  This is not part of the Dwarf2/3 standard yet, but a
11919      custom vendor extension.  The main difference between a regular
11920      array and the vector variant is that vectors are passed by value
11921      to functions.  */
11922   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11923   if (attr)
11924     make_vector_type (type);
11925
11926   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11927      implementation may choose to implement triple vectors using this
11928      attribute.  */
11929   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11930   if (attr)
11931     {
11932       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11933         TYPE_LENGTH (type) = DW_UNSND (attr);
11934       else
11935         complaint (&symfile_complaints,
11936                    _("DW_AT_byte_size for array type smaller "
11937                      "than the total size of elements"));
11938     }
11939
11940   name = dwarf2_name (die, cu);
11941   if (name)
11942     TYPE_NAME (type) = name;
11943
11944   /* Install the type in the die.  */
11945   set_die_type (die, type, cu);
11946
11947   /* set_die_type should be already done.  */
11948   set_descriptive_type (type, die, cu);
11949
11950   do_cleanups (back_to);
11951
11952   return type;
11953 }
11954
11955 static enum dwarf_array_dim_ordering
11956 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11957 {
11958   struct attribute *attr;
11959
11960   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11961
11962   if (attr) return DW_SND (attr);
11963
11964   /* GNU F77 is a special case, as at 08/2004 array type info is the
11965      opposite order to the dwarf2 specification, but data is still
11966      laid out as per normal fortran.
11967
11968      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11969      version checking.  */
11970
11971   if (cu->language == language_fortran
11972       && cu->producer && strstr (cu->producer, "GNU F77"))
11973     {
11974       return DW_ORD_row_major;
11975     }
11976
11977   switch (cu->language_defn->la_array_ordering)
11978     {
11979     case array_column_major:
11980       return DW_ORD_col_major;
11981     case array_row_major:
11982     default:
11983       return DW_ORD_row_major;
11984     };
11985 }
11986
11987 /* Extract all information from a DW_TAG_set_type DIE and put it in
11988    the DIE's type field.  */
11989
11990 static struct type *
11991 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11992 {
11993   struct type *domain_type, *set_type;
11994   struct attribute *attr;
11995
11996   domain_type = die_type (die, cu);
11997
11998   /* The die_type call above may have already set the type for this DIE.  */
11999   set_type = get_die_type (die, cu);
12000   if (set_type)
12001     return set_type;
12002
12003   set_type = create_set_type (NULL, domain_type);
12004
12005   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12006   if (attr)
12007     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12008
12009   return set_die_type (die, set_type, cu);
12010 }
12011
12012 /* A helper for read_common_block that creates a locexpr baton.
12013    SYM is the symbol which we are marking as computed.
12014    COMMON_DIE is the DIE for the common block.
12015    COMMON_LOC is the location expression attribute for the common
12016    block itself.
12017    MEMBER_LOC is the location expression attribute for the particular
12018    member of the common block that we are processing.
12019    CU is the CU from which the above come.  */
12020
12021 static void
12022 mark_common_block_symbol_computed (struct symbol *sym,
12023                                    struct die_info *common_die,
12024                                    struct attribute *common_loc,
12025                                    struct attribute *member_loc,
12026                                    struct dwarf2_cu *cu)
12027 {
12028   struct objfile *objfile = dwarf2_per_objfile->objfile;
12029   struct dwarf2_locexpr_baton *baton;
12030   gdb_byte *ptr;
12031   unsigned int cu_off;
12032   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12033   LONGEST offset = 0;
12034
12035   gdb_assert (common_loc && member_loc);
12036   gdb_assert (attr_form_is_block (common_loc));
12037   gdb_assert (attr_form_is_block (member_loc)
12038               || attr_form_is_constant (member_loc));
12039
12040   baton = obstack_alloc (&objfile->objfile_obstack,
12041                          sizeof (struct dwarf2_locexpr_baton));
12042   baton->per_cu = cu->per_cu;
12043   gdb_assert (baton->per_cu);
12044
12045   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12046
12047   if (attr_form_is_constant (member_loc))
12048     {
12049       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12050       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12051     }
12052   else
12053     baton->size += DW_BLOCK (member_loc)->size;
12054
12055   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12056   baton->data = ptr;
12057
12058   *ptr++ = DW_OP_call4;
12059   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12060   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12061   ptr += 4;
12062
12063   if (attr_form_is_constant (member_loc))
12064     {
12065       *ptr++ = DW_OP_addr;
12066       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12067       ptr += cu->header.addr_size;
12068     }
12069   else
12070     {
12071       /* We have to copy the data here, because DW_OP_call4 will only
12072          use a DW_AT_location attribute.  */
12073       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12074       ptr += DW_BLOCK (member_loc)->size;
12075     }
12076
12077   *ptr++ = DW_OP_plus;
12078   gdb_assert (ptr - baton->data == baton->size);
12079
12080   SYMBOL_LOCATION_BATON (sym) = baton;
12081   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12082 }
12083
12084 /* Create appropriate locally-scoped variables for all the
12085    DW_TAG_common_block entries.  Also create a struct common_block
12086    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12087    is used to sepate the common blocks name namespace from regular
12088    variable names.  */
12089
12090 static void
12091 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12092 {
12093   struct attribute *attr;
12094
12095   attr = dwarf2_attr (die, DW_AT_location, cu);
12096   if (attr)
12097     {
12098       /* Support the .debug_loc offsets.  */
12099       if (attr_form_is_block (attr))
12100         {
12101           /* Ok.  */
12102         }
12103       else if (attr_form_is_section_offset (attr))
12104         {
12105           dwarf2_complex_location_expr_complaint ();
12106           attr = NULL;
12107         }
12108       else
12109         {
12110           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12111                                                  "common block member");
12112           attr = NULL;
12113         }
12114     }
12115
12116   if (die->child != NULL)
12117     {
12118       struct objfile *objfile = cu->objfile;
12119       struct die_info *child_die;
12120       size_t n_entries = 0, size;
12121       struct common_block *common_block;
12122       struct symbol *sym;
12123
12124       for (child_die = die->child;
12125            child_die && child_die->tag;
12126            child_die = sibling_die (child_die))
12127         ++n_entries;
12128
12129       size = (sizeof (struct common_block)
12130               + (n_entries - 1) * sizeof (struct symbol *));
12131       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12132       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12133       common_block->n_entries = 0;
12134
12135       for (child_die = die->child;
12136            child_die && child_die->tag;
12137            child_die = sibling_die (child_die))
12138         {
12139           /* Create the symbol in the DW_TAG_common_block block in the current
12140              symbol scope.  */
12141           sym = new_symbol (child_die, NULL, cu);
12142           if (sym != NULL)
12143             {
12144               struct attribute *member_loc;
12145
12146               common_block->contents[common_block->n_entries++] = sym;
12147
12148               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12149                                         cu);
12150               if (member_loc)
12151                 {
12152                   /* GDB has handled this for a long time, but it is
12153                      not specified by DWARF.  It seems to have been
12154                      emitted by gfortran at least as recently as:
12155                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12156                   complaint (&symfile_complaints,
12157                              _("Variable in common block has "
12158                                "DW_AT_data_member_location "
12159                                "- DIE at 0x%x [in module %s]"),
12160                              child_die->offset.sect_off, cu->objfile->name);
12161
12162                   if (attr_form_is_section_offset (member_loc))
12163                     dwarf2_complex_location_expr_complaint ();
12164                   else if (attr_form_is_constant (member_loc)
12165                            || attr_form_is_block (member_loc))
12166                     {
12167                       if (attr)
12168                         mark_common_block_symbol_computed (sym, die, attr,
12169                                                            member_loc, cu);
12170                     }
12171                   else
12172                     dwarf2_complex_location_expr_complaint ();
12173                 }
12174             }
12175         }
12176
12177       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12178       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12179     }
12180 }
12181
12182 /* Create a type for a C++ namespace.  */
12183
12184 static struct type *
12185 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12186 {
12187   struct objfile *objfile = cu->objfile;
12188   const char *previous_prefix, *name;
12189   int is_anonymous;
12190   struct type *type;
12191
12192   /* For extensions, reuse the type of the original namespace.  */
12193   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12194     {
12195       struct die_info *ext_die;
12196       struct dwarf2_cu *ext_cu = cu;
12197
12198       ext_die = dwarf2_extension (die, &ext_cu);
12199       type = read_type_die (ext_die, ext_cu);
12200
12201       /* EXT_CU may not be the same as CU.
12202          Ensure TYPE is recorded with CU in die_type_hash.  */
12203       return set_die_type (die, type, cu);
12204     }
12205
12206   name = namespace_name (die, &is_anonymous, cu);
12207
12208   /* Now build the name of the current namespace.  */
12209
12210   previous_prefix = determine_prefix (die, cu);
12211   if (previous_prefix[0] != '\0')
12212     name = typename_concat (&objfile->objfile_obstack,
12213                             previous_prefix, name, 0, cu);
12214
12215   /* Create the type.  */
12216   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12217                     objfile);
12218   TYPE_NAME (type) = name;
12219   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12220
12221   return set_die_type (die, type, cu);
12222 }
12223
12224 /* Read a C++ namespace.  */
12225
12226 static void
12227 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12228 {
12229   struct objfile *objfile = cu->objfile;
12230   int is_anonymous;
12231
12232   /* Add a symbol associated to this if we haven't seen the namespace
12233      before.  Also, add a using directive if it's an anonymous
12234      namespace.  */
12235
12236   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12237     {
12238       struct type *type;
12239
12240       type = read_type_die (die, cu);
12241       new_symbol (die, type, cu);
12242
12243       namespace_name (die, &is_anonymous, cu);
12244       if (is_anonymous)
12245         {
12246           const char *previous_prefix = determine_prefix (die, cu);
12247
12248           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12249                                   NULL, NULL, 0, &objfile->objfile_obstack);
12250         }
12251     }
12252
12253   if (die->child != NULL)
12254     {
12255       struct die_info *child_die = die->child;
12256
12257       while (child_die && child_die->tag)
12258         {
12259           process_die (child_die, cu);
12260           child_die = sibling_die (child_die);
12261         }
12262     }
12263 }
12264
12265 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12266    imported module.  Still we need that type as local Fortran "use ... only"
12267    declaration imports depend on the created type in determine_prefix.  */
12268
12269 static struct type *
12270 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12271 {
12272   struct objfile *objfile = cu->objfile;
12273   const char *module_name;
12274   struct type *type;
12275
12276   module_name = dwarf2_name (die, cu);
12277   if (!module_name)
12278     complaint (&symfile_complaints,
12279                _("DW_TAG_module has no name, offset 0x%x"),
12280                die->offset.sect_off);
12281   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12282
12283   /* determine_prefix uses TYPE_TAG_NAME.  */
12284   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12285
12286   return set_die_type (die, type, cu);
12287 }
12288
12289 /* Read a Fortran module.  */
12290
12291 static void
12292 read_module (struct die_info *die, struct dwarf2_cu *cu)
12293 {
12294   struct die_info *child_die = die->child;
12295
12296   while (child_die && child_die->tag)
12297     {
12298       process_die (child_die, cu);
12299       child_die = sibling_die (child_die);
12300     }
12301 }
12302
12303 /* Return the name of the namespace represented by DIE.  Set
12304    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12305    namespace.  */
12306
12307 static const char *
12308 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12309 {
12310   struct die_info *current_die;
12311   const char *name = NULL;
12312
12313   /* Loop through the extensions until we find a name.  */
12314
12315   for (current_die = die;
12316        current_die != NULL;
12317        current_die = dwarf2_extension (die, &cu))
12318     {
12319       name = dwarf2_name (current_die, cu);
12320       if (name != NULL)
12321         break;
12322     }
12323
12324   /* Is it an anonymous namespace?  */
12325
12326   *is_anonymous = (name == NULL);
12327   if (*is_anonymous)
12328     name = CP_ANONYMOUS_NAMESPACE_STR;
12329
12330   return name;
12331 }
12332
12333 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12334    the user defined type vector.  */
12335
12336 static struct type *
12337 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12338 {
12339   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12340   struct comp_unit_head *cu_header = &cu->header;
12341   struct type *type;
12342   struct attribute *attr_byte_size;
12343   struct attribute *attr_address_class;
12344   int byte_size, addr_class;
12345   struct type *target_type;
12346
12347   target_type = die_type (die, cu);
12348
12349   /* The die_type call above may have already set the type for this DIE.  */
12350   type = get_die_type (die, cu);
12351   if (type)
12352     return type;
12353
12354   type = lookup_pointer_type (target_type);
12355
12356   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12357   if (attr_byte_size)
12358     byte_size = DW_UNSND (attr_byte_size);
12359   else
12360     byte_size = cu_header->addr_size;
12361
12362   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12363   if (attr_address_class)
12364     addr_class = DW_UNSND (attr_address_class);
12365   else
12366     addr_class = DW_ADDR_none;
12367
12368   /* If the pointer size or address class is different than the
12369      default, create a type variant marked as such and set the
12370      length accordingly.  */
12371   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12372     {
12373       if (gdbarch_address_class_type_flags_p (gdbarch))
12374         {
12375           int type_flags;
12376
12377           type_flags = gdbarch_address_class_type_flags
12378                          (gdbarch, byte_size, addr_class);
12379           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12380                       == 0);
12381           type = make_type_with_address_space (type, type_flags);
12382         }
12383       else if (TYPE_LENGTH (type) != byte_size)
12384         {
12385           complaint (&symfile_complaints,
12386                      _("invalid pointer size %d"), byte_size);
12387         }
12388       else
12389         {
12390           /* Should we also complain about unhandled address classes?  */
12391         }
12392     }
12393
12394   TYPE_LENGTH (type) = byte_size;
12395   return set_die_type (die, type, cu);
12396 }
12397
12398 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12399    the user defined type vector.  */
12400
12401 static struct type *
12402 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12403 {
12404   struct type *type;
12405   struct type *to_type;
12406   struct type *domain;
12407
12408   to_type = die_type (die, cu);
12409   domain = die_containing_type (die, cu);
12410
12411   /* The calls above may have already set the type for this DIE.  */
12412   type = get_die_type (die, cu);
12413   if (type)
12414     return type;
12415
12416   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12417     type = lookup_methodptr_type (to_type);
12418   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12419     {
12420       struct type *new_type = alloc_type (cu->objfile);
12421
12422       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12423                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12424                             TYPE_VARARGS (to_type));
12425       type = lookup_methodptr_type (new_type);
12426     }
12427   else
12428     type = lookup_memberptr_type (to_type, domain);
12429
12430   return set_die_type (die, type, cu);
12431 }
12432
12433 /* Extract all information from a DW_TAG_reference_type DIE and add to
12434    the user defined type vector.  */
12435
12436 static struct type *
12437 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12438 {
12439   struct comp_unit_head *cu_header = &cu->header;
12440   struct type *type, *target_type;
12441   struct attribute *attr;
12442
12443   target_type = die_type (die, cu);
12444
12445   /* The die_type call above may have already set the type for this DIE.  */
12446   type = get_die_type (die, cu);
12447   if (type)
12448     return type;
12449
12450   type = lookup_reference_type (target_type);
12451   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12452   if (attr)
12453     {
12454       TYPE_LENGTH (type) = DW_UNSND (attr);
12455     }
12456   else
12457     {
12458       TYPE_LENGTH (type) = cu_header->addr_size;
12459     }
12460   return set_die_type (die, type, cu);
12461 }
12462
12463 static struct type *
12464 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12465 {
12466   struct type *base_type, *cv_type;
12467
12468   base_type = die_type (die, cu);
12469
12470   /* The die_type call above may have already set the type for this DIE.  */
12471   cv_type = get_die_type (die, cu);
12472   if (cv_type)
12473     return cv_type;
12474
12475   /* In case the const qualifier is applied to an array type, the element type
12476      is so qualified, not the array type (section 6.7.3 of C99).  */
12477   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12478     {
12479       struct type *el_type, *inner_array;
12480
12481       base_type = copy_type (base_type);
12482       inner_array = base_type;
12483
12484       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12485         {
12486           TYPE_TARGET_TYPE (inner_array) =
12487             copy_type (TYPE_TARGET_TYPE (inner_array));
12488           inner_array = TYPE_TARGET_TYPE (inner_array);
12489         }
12490
12491       el_type = TYPE_TARGET_TYPE (inner_array);
12492       TYPE_TARGET_TYPE (inner_array) =
12493         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12494
12495       return set_die_type (die, base_type, cu);
12496     }
12497
12498   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12499   return set_die_type (die, cv_type, cu);
12500 }
12501
12502 static struct type *
12503 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12504 {
12505   struct type *base_type, *cv_type;
12506
12507   base_type = die_type (die, cu);
12508
12509   /* The die_type call above may have already set the type for this DIE.  */
12510   cv_type = get_die_type (die, cu);
12511   if (cv_type)
12512     return cv_type;
12513
12514   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12515   return set_die_type (die, cv_type, cu);
12516 }
12517
12518 /* Handle DW_TAG_restrict_type.  */
12519
12520 static struct type *
12521 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12522 {
12523   struct type *base_type, *cv_type;
12524
12525   base_type = die_type (die, cu);
12526
12527   /* The die_type call above may have already set the type for this DIE.  */
12528   cv_type = get_die_type (die, cu);
12529   if (cv_type)
12530     return cv_type;
12531
12532   cv_type = make_restrict_type (base_type);
12533   return set_die_type (die, cv_type, cu);
12534 }
12535
12536 /* Extract all information from a DW_TAG_string_type DIE and add to
12537    the user defined type vector.  It isn't really a user defined type,
12538    but it behaves like one, with other DIE's using an AT_user_def_type
12539    attribute to reference it.  */
12540
12541 static struct type *
12542 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12543 {
12544   struct objfile *objfile = cu->objfile;
12545   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12546   struct type *type, *range_type, *index_type, *char_type;
12547   struct attribute *attr;
12548   unsigned int length;
12549
12550   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12551   if (attr)
12552     {
12553       length = DW_UNSND (attr);
12554     }
12555   else
12556     {
12557       /* Check for the DW_AT_byte_size attribute.  */
12558       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12559       if (attr)
12560         {
12561           length = DW_UNSND (attr);
12562         }
12563       else
12564         {
12565           length = 1;
12566         }
12567     }
12568
12569   index_type = objfile_type (objfile)->builtin_int;
12570   range_type = create_range_type (NULL, index_type, 1, length);
12571   char_type = language_string_char_type (cu->language_defn, gdbarch);
12572   type = create_string_type (NULL, char_type, range_type);
12573
12574   return set_die_type (die, type, cu);
12575 }
12576
12577 /* Handle DIES due to C code like:
12578
12579    struct foo
12580    {
12581    int (*funcp)(int a, long l);
12582    int b;
12583    };
12584
12585    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12586
12587 static struct type *
12588 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12589 {
12590   struct objfile *objfile = cu->objfile;
12591   struct type *type;            /* Type that this function returns.  */
12592   struct type *ftype;           /* Function that returns above type.  */
12593   struct attribute *attr;
12594
12595   type = die_type (die, cu);
12596
12597   /* The die_type call above may have already set the type for this DIE.  */
12598   ftype = get_die_type (die, cu);
12599   if (ftype)
12600     return ftype;
12601
12602   ftype = lookup_function_type (type);
12603
12604   /* All functions in C++, Pascal and Java have prototypes.  */
12605   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12606   if ((attr && (DW_UNSND (attr) != 0))
12607       || cu->language == language_cplus
12608       || cu->language == language_java
12609       || cu->language == language_pascal)
12610     TYPE_PROTOTYPED (ftype) = 1;
12611   else if (producer_is_realview (cu->producer))
12612     /* RealView does not emit DW_AT_prototyped.  We can not
12613        distinguish prototyped and unprototyped functions; default to
12614        prototyped, since that is more common in modern code (and
12615        RealView warns about unprototyped functions).  */
12616     TYPE_PROTOTYPED (ftype) = 1;
12617
12618   /* Store the calling convention in the type if it's available in
12619      the subroutine die.  Otherwise set the calling convention to
12620      the default value DW_CC_normal.  */
12621   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12622   if (attr)
12623     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12624   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12625     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12626   else
12627     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12628
12629   /* We need to add the subroutine type to the die immediately so
12630      we don't infinitely recurse when dealing with parameters
12631      declared as the same subroutine type.  */
12632   set_die_type (die, ftype, cu);
12633
12634   if (die->child != NULL)
12635     {
12636       struct type *void_type = objfile_type (objfile)->builtin_void;
12637       struct die_info *child_die;
12638       int nparams, iparams;
12639
12640       /* Count the number of parameters.
12641          FIXME: GDB currently ignores vararg functions, but knows about
12642          vararg member functions.  */
12643       nparams = 0;
12644       child_die = die->child;
12645       while (child_die && child_die->tag)
12646         {
12647           if (child_die->tag == DW_TAG_formal_parameter)
12648             nparams++;
12649           else if (child_die->tag == DW_TAG_unspecified_parameters)
12650             TYPE_VARARGS (ftype) = 1;
12651           child_die = sibling_die (child_die);
12652         }
12653
12654       /* Allocate storage for parameters and fill them in.  */
12655       TYPE_NFIELDS (ftype) = nparams;
12656       TYPE_FIELDS (ftype) = (struct field *)
12657         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12658
12659       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12660          even if we error out during the parameters reading below.  */
12661       for (iparams = 0; iparams < nparams; iparams++)
12662         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12663
12664       iparams = 0;
12665       child_die = die->child;
12666       while (child_die && child_die->tag)
12667         {
12668           if (child_die->tag == DW_TAG_formal_parameter)
12669             {
12670               struct type *arg_type;
12671
12672               /* DWARF version 2 has no clean way to discern C++
12673                  static and non-static member functions.  G++ helps
12674                  GDB by marking the first parameter for non-static
12675                  member functions (which is the this pointer) as
12676                  artificial.  We pass this information to
12677                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12678
12679                  DWARF version 3 added DW_AT_object_pointer, which GCC
12680                  4.5 does not yet generate.  */
12681               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12682               if (attr)
12683                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12684               else
12685                 {
12686                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12687
12688                   /* GCC/43521: In java, the formal parameter
12689                      "this" is sometimes not marked with DW_AT_artificial.  */
12690                   if (cu->language == language_java)
12691                     {
12692                       const char *name = dwarf2_name (child_die, cu);
12693
12694                       if (name && !strcmp (name, "this"))
12695                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12696                     }
12697                 }
12698               arg_type = die_type (child_die, cu);
12699
12700               /* RealView does not mark THIS as const, which the testsuite
12701                  expects.  GCC marks THIS as const in method definitions,
12702                  but not in the class specifications (GCC PR 43053).  */
12703               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12704                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12705                 {
12706                   int is_this = 0;
12707                   struct dwarf2_cu *arg_cu = cu;
12708                   const char *name = dwarf2_name (child_die, cu);
12709
12710                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12711                   if (attr)
12712                     {
12713                       /* If the compiler emits this, use it.  */
12714                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12715                         is_this = 1;
12716                     }
12717                   else if (name && strcmp (name, "this") == 0)
12718                     /* Function definitions will have the argument names.  */
12719                     is_this = 1;
12720                   else if (name == NULL && iparams == 0)
12721                     /* Declarations may not have the names, so like
12722                        elsewhere in GDB, assume an artificial first
12723                        argument is "this".  */
12724                     is_this = 1;
12725
12726                   if (is_this)
12727                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12728                                              arg_type, 0);
12729                 }
12730
12731               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12732               iparams++;
12733             }
12734           child_die = sibling_die (child_die);
12735         }
12736     }
12737
12738   return ftype;
12739 }
12740
12741 static struct type *
12742 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12743 {
12744   struct objfile *objfile = cu->objfile;
12745   const char *name = NULL;
12746   struct type *this_type, *target_type;
12747
12748   name = dwarf2_full_name (NULL, die, cu);
12749   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12750                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12751   TYPE_NAME (this_type) = name;
12752   set_die_type (die, this_type, cu);
12753   target_type = die_type (die, cu);
12754   if (target_type != this_type)
12755     TYPE_TARGET_TYPE (this_type) = target_type;
12756   else
12757     {
12758       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12759          spec and cause infinite loops in GDB.  */
12760       complaint (&symfile_complaints,
12761                  _("Self-referential DW_TAG_typedef "
12762                    "- DIE at 0x%x [in module %s]"),
12763                  die->offset.sect_off, objfile->name);
12764       TYPE_TARGET_TYPE (this_type) = NULL;
12765     }
12766   return this_type;
12767 }
12768
12769 /* Find a representation of a given base type and install
12770    it in the TYPE field of the die.  */
12771
12772 static struct type *
12773 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12774 {
12775   struct objfile *objfile = cu->objfile;
12776   struct type *type;
12777   struct attribute *attr;
12778   int encoding = 0, size = 0;
12779   const char *name;
12780   enum type_code code = TYPE_CODE_INT;
12781   int type_flags = 0;
12782   struct type *target_type = NULL;
12783
12784   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12785   if (attr)
12786     {
12787       encoding = DW_UNSND (attr);
12788     }
12789   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12790   if (attr)
12791     {
12792       size = DW_UNSND (attr);
12793     }
12794   name = dwarf2_name (die, cu);
12795   if (!name)
12796     {
12797       complaint (&symfile_complaints,
12798                  _("DW_AT_name missing from DW_TAG_base_type"));
12799     }
12800
12801   switch (encoding)
12802     {
12803       case DW_ATE_address:
12804         /* Turn DW_ATE_address into a void * pointer.  */
12805         code = TYPE_CODE_PTR;
12806         type_flags |= TYPE_FLAG_UNSIGNED;
12807         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12808         break;
12809       case DW_ATE_boolean:
12810         code = TYPE_CODE_BOOL;
12811         type_flags |= TYPE_FLAG_UNSIGNED;
12812         break;
12813       case DW_ATE_complex_float:
12814         code = TYPE_CODE_COMPLEX;
12815         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12816         break;
12817       case DW_ATE_decimal_float:
12818         code = TYPE_CODE_DECFLOAT;
12819         break;
12820       case DW_ATE_float:
12821         code = TYPE_CODE_FLT;
12822         break;
12823       case DW_ATE_signed:
12824         break;
12825       case DW_ATE_unsigned:
12826         type_flags |= TYPE_FLAG_UNSIGNED;
12827         if (cu->language == language_fortran
12828             && name
12829             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12830           code = TYPE_CODE_CHAR;
12831         break;
12832       case DW_ATE_signed_char:
12833         if (cu->language == language_ada || cu->language == language_m2
12834             || cu->language == language_pascal
12835             || cu->language == language_fortran)
12836           code = TYPE_CODE_CHAR;
12837         break;
12838       case DW_ATE_unsigned_char:
12839         if (cu->language == language_ada || cu->language == language_m2
12840             || cu->language == language_pascal
12841             || cu->language == language_fortran)
12842           code = TYPE_CODE_CHAR;
12843         type_flags |= TYPE_FLAG_UNSIGNED;
12844         break;
12845       case DW_ATE_UTF:
12846         /* We just treat this as an integer and then recognize the
12847            type by name elsewhere.  */
12848         break;
12849
12850       default:
12851         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12852                    dwarf_type_encoding_name (encoding));
12853         break;
12854     }
12855
12856   type = init_type (code, size, type_flags, NULL, objfile);
12857   TYPE_NAME (type) = name;
12858   TYPE_TARGET_TYPE (type) = target_type;
12859
12860   if (name && strcmp (name, "char") == 0)
12861     TYPE_NOSIGN (type) = 1;
12862
12863   return set_die_type (die, type, cu);
12864 }
12865
12866 /* Read the given DW_AT_subrange DIE.  */
12867
12868 static struct type *
12869 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12870 {
12871   struct type *base_type, *orig_base_type;
12872   struct type *range_type;
12873   struct attribute *attr;
12874   LONGEST low, high;
12875   int low_default_is_valid;
12876   const char *name;
12877   LONGEST negative_mask;
12878
12879   orig_base_type = die_type (die, cu);
12880   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
12881      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
12882      creating the range type, but we use the result of check_typedef
12883      when examining properties of the type.  */
12884   base_type = check_typedef (orig_base_type);
12885
12886   /* The die_type call above may have already set the type for this DIE.  */
12887   range_type = get_die_type (die, cu);
12888   if (range_type)
12889     return range_type;
12890
12891   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12892      omitting DW_AT_lower_bound.  */
12893   switch (cu->language)
12894     {
12895     case language_c:
12896     case language_cplus:
12897       low = 0;
12898       low_default_is_valid = 1;
12899       break;
12900     case language_fortran:
12901       low = 1;
12902       low_default_is_valid = 1;
12903       break;
12904     case language_d:
12905     case language_java:
12906     case language_objc:
12907       low = 0;
12908       low_default_is_valid = (cu->header.version >= 4);
12909       break;
12910     case language_ada:
12911     case language_m2:
12912     case language_pascal:
12913       low = 1;
12914       low_default_is_valid = (cu->header.version >= 4);
12915       break;
12916     default:
12917       low = 0;
12918       low_default_is_valid = 0;
12919       break;
12920     }
12921
12922   /* FIXME: For variable sized arrays either of these could be
12923      a variable rather than a constant value.  We'll allow it,
12924      but we don't know how to handle it.  */
12925   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12926   if (attr)
12927     low = dwarf2_get_attr_constant_value (attr, low);
12928   else if (!low_default_is_valid)
12929     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12930                                       "- DIE at 0x%x [in module %s]"),
12931                die->offset.sect_off, cu->objfile->name);
12932
12933   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12934   if (attr)
12935     {
12936       if (attr_form_is_block (attr) || is_ref_attr (attr))
12937         {
12938           /* GCC encodes arrays with unspecified or dynamic length
12939              with a DW_FORM_block1 attribute or a reference attribute.
12940              FIXME: GDB does not yet know how to handle dynamic
12941              arrays properly, treat them as arrays with unspecified
12942              length for now.
12943
12944              FIXME: jimb/2003-09-22: GDB does not really know
12945              how to handle arrays of unspecified length
12946              either; we just represent them as zero-length
12947              arrays.  Choose an appropriate upper bound given
12948              the lower bound we've computed above.  */
12949           high = low - 1;
12950         }
12951       else
12952         high = dwarf2_get_attr_constant_value (attr, 1);
12953     }
12954   else
12955     {
12956       attr = dwarf2_attr (die, DW_AT_count, cu);
12957       if (attr)
12958         {
12959           int count = dwarf2_get_attr_constant_value (attr, 1);
12960           high = low + count - 1;
12961         }
12962       else
12963         {
12964           /* Unspecified array length.  */
12965           high = low - 1;
12966         }
12967     }
12968
12969   /* Dwarf-2 specifications explicitly allows to create subrange types
12970      without specifying a base type.
12971      In that case, the base type must be set to the type of
12972      the lower bound, upper bound or count, in that order, if any of these
12973      three attributes references an object that has a type.
12974      If no base type is found, the Dwarf-2 specifications say that
12975      a signed integer type of size equal to the size of an address should
12976      be used.
12977      For the following C code: `extern char gdb_int [];'
12978      GCC produces an empty range DIE.
12979      FIXME: muller/2010-05-28: Possible references to object for low bound,
12980      high bound or count are not yet handled by this code.  */
12981   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12982     {
12983       struct objfile *objfile = cu->objfile;
12984       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12985       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12986       struct type *int_type = objfile_type (objfile)->builtin_int;
12987
12988       /* Test "int", "long int", and "long long int" objfile types,
12989          and select the first one having a size above or equal to the
12990          architecture address size.  */
12991       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12992         base_type = int_type;
12993       else
12994         {
12995           int_type = objfile_type (objfile)->builtin_long;
12996           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12997             base_type = int_type;
12998           else
12999             {
13000               int_type = objfile_type (objfile)->builtin_long_long;
13001               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
13002                 base_type = int_type;
13003             }
13004         }
13005     }
13006
13007   negative_mask =
13008     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13009   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13010     low |= negative_mask;
13011   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13012     high |= negative_mask;
13013
13014   range_type = create_range_type (NULL, orig_base_type, low, high);
13015
13016   /* Mark arrays with dynamic length at least as an array of unspecified
13017      length.  GDB could check the boundary but before it gets implemented at
13018      least allow accessing the array elements.  */
13019   if (attr && attr_form_is_block (attr))
13020     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13021
13022   /* Ada expects an empty array on no boundary attributes.  */
13023   if (attr == NULL && cu->language != language_ada)
13024     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13025
13026   name = dwarf2_name (die, cu);
13027   if (name)
13028     TYPE_NAME (range_type) = name;
13029
13030   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13031   if (attr)
13032     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13033
13034   set_die_type (die, range_type, cu);
13035
13036   /* set_die_type should be already done.  */
13037   set_descriptive_type (range_type, die, cu);
13038
13039   return range_type;
13040 }
13041
13042 static struct type *
13043 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13044 {
13045   struct type *type;
13046
13047   /* For now, we only support the C meaning of an unspecified type: void.  */
13048
13049   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13050   TYPE_NAME (type) = dwarf2_name (die, cu);
13051
13052   return set_die_type (die, type, cu);
13053 }
13054
13055 /* Read a single die and all its descendents.  Set the die's sibling
13056    field to NULL; set other fields in the die correctly, and set all
13057    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13058    location of the info_ptr after reading all of those dies.  PARENT
13059    is the parent of the die in question.  */
13060
13061 static struct die_info *
13062 read_die_and_children (const struct die_reader_specs *reader,
13063                        const gdb_byte *info_ptr,
13064                        const gdb_byte **new_info_ptr,
13065                        struct die_info *parent)
13066 {
13067   struct die_info *die;
13068   const gdb_byte *cur_ptr;
13069   int has_children;
13070
13071   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13072   if (die == NULL)
13073     {
13074       *new_info_ptr = cur_ptr;
13075       return NULL;
13076     }
13077   store_in_ref_table (die, reader->cu);
13078
13079   if (has_children)
13080     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13081   else
13082     {
13083       die->child = NULL;
13084       *new_info_ptr = cur_ptr;
13085     }
13086
13087   die->sibling = NULL;
13088   die->parent = parent;
13089   return die;
13090 }
13091
13092 /* Read a die, all of its descendents, and all of its siblings; set
13093    all of the fields of all of the dies correctly.  Arguments are as
13094    in read_die_and_children.  */
13095
13096 static struct die_info *
13097 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13098                          const gdb_byte *info_ptr,
13099                          const gdb_byte **new_info_ptr,
13100                          struct die_info *parent)
13101 {
13102   struct die_info *first_die, *last_sibling;
13103   const gdb_byte *cur_ptr;
13104
13105   cur_ptr = info_ptr;
13106   first_die = last_sibling = NULL;
13107
13108   while (1)
13109     {
13110       struct die_info *die
13111         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13112
13113       if (die == NULL)
13114         {
13115           *new_info_ptr = cur_ptr;
13116           return first_die;
13117         }
13118
13119       if (!first_die)
13120         first_die = die;
13121       else
13122         last_sibling->sibling = die;
13123
13124       last_sibling = die;
13125     }
13126 }
13127
13128 /* Read a die, all of its descendents, and all of its siblings; set
13129    all of the fields of all of the dies correctly.  Arguments are as
13130    in read_die_and_children.
13131    This the main entry point for reading a DIE and all its children.  */
13132
13133 static struct die_info *
13134 read_die_and_siblings (const struct die_reader_specs *reader,
13135                        const gdb_byte *info_ptr,
13136                        const gdb_byte **new_info_ptr,
13137                        struct die_info *parent)
13138 {
13139   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13140                                                   new_info_ptr, parent);
13141
13142   if (dwarf2_die_debug)
13143     {
13144       fprintf_unfiltered (gdb_stdlog,
13145                           "Read die from %s@0x%x of %s:\n",
13146                           bfd_section_name (reader->abfd,
13147                                             reader->die_section->asection),
13148                           (unsigned) (info_ptr - reader->die_section->buffer),
13149                           bfd_get_filename (reader->abfd));
13150       dump_die (die, dwarf2_die_debug);
13151     }
13152
13153   return die;
13154 }
13155
13156 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13157    attributes.
13158    The caller is responsible for filling in the extra attributes
13159    and updating (*DIEP)->num_attrs.
13160    Set DIEP to point to a newly allocated die with its information,
13161    except for its child, sibling, and parent fields.
13162    Set HAS_CHILDREN to tell whether the die has children or not.  */
13163
13164 static const gdb_byte *
13165 read_full_die_1 (const struct die_reader_specs *reader,
13166                  struct die_info **diep, const gdb_byte *info_ptr,
13167                  int *has_children, int num_extra_attrs)
13168 {
13169   unsigned int abbrev_number, bytes_read, i;
13170   sect_offset offset;
13171   struct abbrev_info *abbrev;
13172   struct die_info *die;
13173   struct dwarf2_cu *cu = reader->cu;
13174   bfd *abfd = reader->abfd;
13175
13176   offset.sect_off = info_ptr - reader->buffer;
13177   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13178   info_ptr += bytes_read;
13179   if (!abbrev_number)
13180     {
13181       *diep = NULL;
13182       *has_children = 0;
13183       return info_ptr;
13184     }
13185
13186   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13187   if (!abbrev)
13188     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13189            abbrev_number,
13190            bfd_get_filename (abfd));
13191
13192   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13193   die->offset = offset;
13194   die->tag = abbrev->tag;
13195   die->abbrev = abbrev_number;
13196
13197   /* Make the result usable.
13198      The caller needs to update num_attrs after adding the extra
13199      attributes.  */
13200   die->num_attrs = abbrev->num_attrs;
13201
13202   for (i = 0; i < abbrev->num_attrs; ++i)
13203     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13204                                info_ptr);
13205
13206   *diep = die;
13207   *has_children = abbrev->has_children;
13208   return info_ptr;
13209 }
13210
13211 /* Read a die and all its attributes.
13212    Set DIEP to point to a newly allocated die with its information,
13213    except for its child, sibling, and parent fields.
13214    Set HAS_CHILDREN to tell whether the die has children or not.  */
13215
13216 static const gdb_byte *
13217 read_full_die (const struct die_reader_specs *reader,
13218                struct die_info **diep, const gdb_byte *info_ptr,
13219                int *has_children)
13220 {
13221   const gdb_byte *result;
13222
13223   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13224
13225   if (dwarf2_die_debug)
13226     {
13227       fprintf_unfiltered (gdb_stdlog,
13228                           "Read die from %s@0x%x of %s:\n",
13229                           bfd_section_name (reader->abfd,
13230                                             reader->die_section->asection),
13231                           (unsigned) (info_ptr - reader->die_section->buffer),
13232                           bfd_get_filename (reader->abfd));
13233       dump_die (*diep, dwarf2_die_debug);
13234     }
13235
13236   return result;
13237 }
13238 \f
13239 /* Abbreviation tables.
13240
13241    In DWARF version 2, the description of the debugging information is
13242    stored in a separate .debug_abbrev section.  Before we read any
13243    dies from a section we read in all abbreviations and install them
13244    in a hash table.  */
13245
13246 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13247
13248 static struct abbrev_info *
13249 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13250 {
13251   struct abbrev_info *abbrev;
13252
13253   abbrev = (struct abbrev_info *)
13254     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13255   memset (abbrev, 0, sizeof (struct abbrev_info));
13256   return abbrev;
13257 }
13258
13259 /* Add an abbreviation to the table.  */
13260
13261 static void
13262 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13263                          unsigned int abbrev_number,
13264                          struct abbrev_info *abbrev)
13265 {
13266   unsigned int hash_number;
13267
13268   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13269   abbrev->next = abbrev_table->abbrevs[hash_number];
13270   abbrev_table->abbrevs[hash_number] = abbrev;
13271 }
13272
13273 /* Look up an abbrev in the table.
13274    Returns NULL if the abbrev is not found.  */
13275
13276 static struct abbrev_info *
13277 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13278                             unsigned int abbrev_number)
13279 {
13280   unsigned int hash_number;
13281   struct abbrev_info *abbrev;
13282
13283   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13284   abbrev = abbrev_table->abbrevs[hash_number];
13285
13286   while (abbrev)
13287     {
13288       if (abbrev->number == abbrev_number)
13289         return abbrev;
13290       abbrev = abbrev->next;
13291     }
13292   return NULL;
13293 }
13294
13295 /* Read in an abbrev table.  */
13296
13297 static struct abbrev_table *
13298 abbrev_table_read_table (struct dwarf2_section_info *section,
13299                          sect_offset offset)
13300 {
13301   struct objfile *objfile = dwarf2_per_objfile->objfile;
13302   bfd *abfd = section->asection->owner;
13303   struct abbrev_table *abbrev_table;
13304   const gdb_byte *abbrev_ptr;
13305   struct abbrev_info *cur_abbrev;
13306   unsigned int abbrev_number, bytes_read, abbrev_name;
13307   unsigned int abbrev_form;
13308   struct attr_abbrev *cur_attrs;
13309   unsigned int allocated_attrs;
13310
13311   abbrev_table = XMALLOC (struct abbrev_table);
13312   abbrev_table->offset = offset;
13313   obstack_init (&abbrev_table->abbrev_obstack);
13314   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13315                                          (ABBREV_HASH_SIZE
13316                                           * sizeof (struct abbrev_info *)));
13317   memset (abbrev_table->abbrevs, 0,
13318           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13319
13320   dwarf2_read_section (objfile, section);
13321   abbrev_ptr = section->buffer + offset.sect_off;
13322   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13323   abbrev_ptr += bytes_read;
13324
13325   allocated_attrs = ATTR_ALLOC_CHUNK;
13326   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13327
13328   /* Loop until we reach an abbrev number of 0.  */
13329   while (abbrev_number)
13330     {
13331       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13332
13333       /* read in abbrev header */
13334       cur_abbrev->number = abbrev_number;
13335       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13336       abbrev_ptr += bytes_read;
13337       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13338       abbrev_ptr += 1;
13339
13340       /* now read in declarations */
13341       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13342       abbrev_ptr += bytes_read;
13343       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13344       abbrev_ptr += bytes_read;
13345       while (abbrev_name)
13346         {
13347           if (cur_abbrev->num_attrs == allocated_attrs)
13348             {
13349               allocated_attrs += ATTR_ALLOC_CHUNK;
13350               cur_attrs
13351                 = xrealloc (cur_attrs, (allocated_attrs
13352                                         * sizeof (struct attr_abbrev)));
13353             }
13354
13355           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13356           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13357           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13358           abbrev_ptr += bytes_read;
13359           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13360           abbrev_ptr += bytes_read;
13361         }
13362
13363       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13364                                          (cur_abbrev->num_attrs
13365                                           * sizeof (struct attr_abbrev)));
13366       memcpy (cur_abbrev->attrs, cur_attrs,
13367               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13368
13369       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13370
13371       /* Get next abbreviation.
13372          Under Irix6 the abbreviations for a compilation unit are not
13373          always properly terminated with an abbrev number of 0.
13374          Exit loop if we encounter an abbreviation which we have
13375          already read (which means we are about to read the abbreviations
13376          for the next compile unit) or if the end of the abbreviation
13377          table is reached.  */
13378       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13379         break;
13380       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13381       abbrev_ptr += bytes_read;
13382       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13383         break;
13384     }
13385
13386   xfree (cur_attrs);
13387   return abbrev_table;
13388 }
13389
13390 /* Free the resources held by ABBREV_TABLE.  */
13391
13392 static void
13393 abbrev_table_free (struct abbrev_table *abbrev_table)
13394 {
13395   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13396   xfree (abbrev_table);
13397 }
13398
13399 /* Same as abbrev_table_free but as a cleanup.
13400    We pass in a pointer to the pointer to the table so that we can
13401    set the pointer to NULL when we're done.  It also simplifies
13402    build_type_unit_groups.  */
13403
13404 static void
13405 abbrev_table_free_cleanup (void *table_ptr)
13406 {
13407   struct abbrev_table **abbrev_table_ptr = table_ptr;
13408
13409   if (*abbrev_table_ptr != NULL)
13410     abbrev_table_free (*abbrev_table_ptr);
13411   *abbrev_table_ptr = NULL;
13412 }
13413
13414 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13415
13416 static void
13417 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13418                      struct dwarf2_section_info *abbrev_section)
13419 {
13420   cu->abbrev_table =
13421     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13422 }
13423
13424 /* Release the memory used by the abbrev table for a compilation unit.  */
13425
13426 static void
13427 dwarf2_free_abbrev_table (void *ptr_to_cu)
13428 {
13429   struct dwarf2_cu *cu = ptr_to_cu;
13430
13431   abbrev_table_free (cu->abbrev_table);
13432   /* Set this to NULL so that we SEGV if we try to read it later,
13433      and also because free_comp_unit verifies this is NULL.  */
13434   cu->abbrev_table = NULL;
13435 }
13436 \f
13437 /* Returns nonzero if TAG represents a type that we might generate a partial
13438    symbol for.  */
13439
13440 static int
13441 is_type_tag_for_partial (int tag)
13442 {
13443   switch (tag)
13444     {
13445 #if 0
13446     /* Some types that would be reasonable to generate partial symbols for,
13447        that we don't at present.  */
13448     case DW_TAG_array_type:
13449     case DW_TAG_file_type:
13450     case DW_TAG_ptr_to_member_type:
13451     case DW_TAG_set_type:
13452     case DW_TAG_string_type:
13453     case DW_TAG_subroutine_type:
13454 #endif
13455     case DW_TAG_base_type:
13456     case DW_TAG_class_type:
13457     case DW_TAG_interface_type:
13458     case DW_TAG_enumeration_type:
13459     case DW_TAG_structure_type:
13460     case DW_TAG_subrange_type:
13461     case DW_TAG_typedef:
13462     case DW_TAG_union_type:
13463       return 1;
13464     default:
13465       return 0;
13466     }
13467 }
13468
13469 /* Load all DIEs that are interesting for partial symbols into memory.  */
13470
13471 static struct partial_die_info *
13472 load_partial_dies (const struct die_reader_specs *reader,
13473                    const gdb_byte *info_ptr, int building_psymtab)
13474 {
13475   struct dwarf2_cu *cu = reader->cu;
13476   struct objfile *objfile = cu->objfile;
13477   struct partial_die_info *part_die;
13478   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13479   struct abbrev_info *abbrev;
13480   unsigned int bytes_read;
13481   unsigned int load_all = 0;
13482   int nesting_level = 1;
13483
13484   parent_die = NULL;
13485   last_die = NULL;
13486
13487   gdb_assert (cu->per_cu != NULL);
13488   if (cu->per_cu->load_all_dies)
13489     load_all = 1;
13490
13491   cu->partial_dies
13492     = htab_create_alloc_ex (cu->header.length / 12,
13493                             partial_die_hash,
13494                             partial_die_eq,
13495                             NULL,
13496                             &cu->comp_unit_obstack,
13497                             hashtab_obstack_allocate,
13498                             dummy_obstack_deallocate);
13499
13500   part_die = obstack_alloc (&cu->comp_unit_obstack,
13501                             sizeof (struct partial_die_info));
13502
13503   while (1)
13504     {
13505       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13506
13507       /* A NULL abbrev means the end of a series of children.  */
13508       if (abbrev == NULL)
13509         {
13510           if (--nesting_level == 0)
13511             {
13512               /* PART_DIE was probably the last thing allocated on the
13513                  comp_unit_obstack, so we could call obstack_free
13514                  here.  We don't do that because the waste is small,
13515                  and will be cleaned up when we're done with this
13516                  compilation unit.  This way, we're also more robust
13517                  against other users of the comp_unit_obstack.  */
13518               return first_die;
13519             }
13520           info_ptr += bytes_read;
13521           last_die = parent_die;
13522           parent_die = parent_die->die_parent;
13523           continue;
13524         }
13525
13526       /* Check for template arguments.  We never save these; if
13527          they're seen, we just mark the parent, and go on our way.  */
13528       if (parent_die != NULL
13529           && cu->language == language_cplus
13530           && (abbrev->tag == DW_TAG_template_type_param
13531               || abbrev->tag == DW_TAG_template_value_param))
13532         {
13533           parent_die->has_template_arguments = 1;
13534
13535           if (!load_all)
13536             {
13537               /* We don't need a partial DIE for the template argument.  */
13538               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13539               continue;
13540             }
13541         }
13542
13543       /* We only recurse into c++ subprograms looking for template arguments.
13544          Skip their other children.  */
13545       if (!load_all
13546           && cu->language == language_cplus
13547           && parent_die != NULL
13548           && parent_die->tag == DW_TAG_subprogram)
13549         {
13550           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13551           continue;
13552         }
13553
13554       /* Check whether this DIE is interesting enough to save.  Normally
13555          we would not be interested in members here, but there may be
13556          later variables referencing them via DW_AT_specification (for
13557          static members).  */
13558       if (!load_all
13559           && !is_type_tag_for_partial (abbrev->tag)
13560           && abbrev->tag != DW_TAG_constant
13561           && abbrev->tag != DW_TAG_enumerator
13562           && abbrev->tag != DW_TAG_subprogram
13563           && abbrev->tag != DW_TAG_lexical_block
13564           && abbrev->tag != DW_TAG_variable
13565           && abbrev->tag != DW_TAG_namespace
13566           && abbrev->tag != DW_TAG_module
13567           && abbrev->tag != DW_TAG_member
13568           && abbrev->tag != DW_TAG_imported_unit)
13569         {
13570           /* Otherwise we skip to the next sibling, if any.  */
13571           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13572           continue;
13573         }
13574
13575       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13576                                    info_ptr);
13577
13578       /* This two-pass algorithm for processing partial symbols has a
13579          high cost in cache pressure.  Thus, handle some simple cases
13580          here which cover the majority of C partial symbols.  DIEs
13581          which neither have specification tags in them, nor could have
13582          specification tags elsewhere pointing at them, can simply be
13583          processed and discarded.
13584
13585          This segment is also optional; scan_partial_symbols and
13586          add_partial_symbol will handle these DIEs if we chain
13587          them in normally.  When compilers which do not emit large
13588          quantities of duplicate debug information are more common,
13589          this code can probably be removed.  */
13590
13591       /* Any complete simple types at the top level (pretty much all
13592          of them, for a language without namespaces), can be processed
13593          directly.  */
13594       if (parent_die == NULL
13595           && part_die->has_specification == 0
13596           && part_die->is_declaration == 0
13597           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13598               || part_die->tag == DW_TAG_base_type
13599               || part_die->tag == DW_TAG_subrange_type))
13600         {
13601           if (building_psymtab && part_die->name != NULL)
13602             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13603                                  VAR_DOMAIN, LOC_TYPEDEF,
13604                                  &objfile->static_psymbols,
13605                                  0, (CORE_ADDR) 0, cu->language, objfile);
13606           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13607           continue;
13608         }
13609
13610       /* The exception for DW_TAG_typedef with has_children above is
13611          a workaround of GCC PR debug/47510.  In the case of this complaint
13612          type_name_no_tag_or_error will error on such types later.
13613
13614          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13615          it could not find the child DIEs referenced later, this is checked
13616          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13617
13618       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13619         complaint (&symfile_complaints,
13620                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13621                      "- DIE at 0x%x [in module %s]"),
13622                    part_die->offset.sect_off, objfile->name);
13623
13624       /* If we're at the second level, and we're an enumerator, and
13625          our parent has no specification (meaning possibly lives in a
13626          namespace elsewhere), then we can add the partial symbol now
13627          instead of queueing it.  */
13628       if (part_die->tag == DW_TAG_enumerator
13629           && parent_die != NULL
13630           && parent_die->die_parent == NULL
13631           && parent_die->tag == DW_TAG_enumeration_type
13632           && parent_die->has_specification == 0)
13633         {
13634           if (part_die->name == NULL)
13635             complaint (&symfile_complaints,
13636                        _("malformed enumerator DIE ignored"));
13637           else if (building_psymtab)
13638             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13639                                  VAR_DOMAIN, LOC_CONST,
13640                                  (cu->language == language_cplus
13641                                   || cu->language == language_java)
13642                                  ? &objfile->global_psymbols
13643                                  : &objfile->static_psymbols,
13644                                  0, (CORE_ADDR) 0, cu->language, objfile);
13645
13646           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13647           continue;
13648         }
13649
13650       /* We'll save this DIE so link it in.  */
13651       part_die->die_parent = parent_die;
13652       part_die->die_sibling = NULL;
13653       part_die->die_child = NULL;
13654
13655       if (last_die && last_die == parent_die)
13656         last_die->die_child = part_die;
13657       else if (last_die)
13658         last_die->die_sibling = part_die;
13659
13660       last_die = part_die;
13661
13662       if (first_die == NULL)
13663         first_die = part_die;
13664
13665       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13666          find interesting need to be in the hash table, because we
13667          also have the parent/sibling/child chains; only those that we
13668          might refer to by offset later during partial symbol reading.
13669
13670          For now this means things that might have be the target of a
13671          DW_AT_specification, DW_AT_abstract_origin, or
13672          DW_AT_extension.  DW_AT_extension will refer only to
13673          namespaces; DW_AT_abstract_origin refers to functions (and
13674          many things under the function DIE, but we do not recurse
13675          into function DIEs during partial symbol reading) and
13676          possibly variables as well; DW_AT_specification refers to
13677          declarations.  Declarations ought to have the DW_AT_declaration
13678          flag.  It happens that GCC forgets to put it in sometimes, but
13679          only for functions, not for types.
13680
13681          Adding more things than necessary to the hash table is harmless
13682          except for the performance cost.  Adding too few will result in
13683          wasted time in find_partial_die, when we reread the compilation
13684          unit with load_all_dies set.  */
13685
13686       if (load_all
13687           || abbrev->tag == DW_TAG_constant
13688           || abbrev->tag == DW_TAG_subprogram
13689           || abbrev->tag == DW_TAG_variable
13690           || abbrev->tag == DW_TAG_namespace
13691           || part_die->is_declaration)
13692         {
13693           void **slot;
13694
13695           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13696                                            part_die->offset.sect_off, INSERT);
13697           *slot = part_die;
13698         }
13699
13700       part_die = obstack_alloc (&cu->comp_unit_obstack,
13701                                 sizeof (struct partial_die_info));
13702
13703       /* For some DIEs we want to follow their children (if any).  For C
13704          we have no reason to follow the children of structures; for other
13705          languages we have to, so that we can get at method physnames
13706          to infer fully qualified class names, for DW_AT_specification,
13707          and for C++ template arguments.  For C++, we also look one level
13708          inside functions to find template arguments (if the name of the
13709          function does not already contain the template arguments).
13710
13711          For Ada, we need to scan the children of subprograms and lexical
13712          blocks as well because Ada allows the definition of nested
13713          entities that could be interesting for the debugger, such as
13714          nested subprograms for instance.  */
13715       if (last_die->has_children
13716           && (load_all
13717               || last_die->tag == DW_TAG_namespace
13718               || last_die->tag == DW_TAG_module
13719               || last_die->tag == DW_TAG_enumeration_type
13720               || (cu->language == language_cplus
13721                   && last_die->tag == DW_TAG_subprogram
13722                   && (last_die->name == NULL
13723                       || strchr (last_die->name, '<') == NULL))
13724               || (cu->language != language_c
13725                   && (last_die->tag == DW_TAG_class_type
13726                       || last_die->tag == DW_TAG_interface_type
13727                       || last_die->tag == DW_TAG_structure_type
13728                       || last_die->tag == DW_TAG_union_type))
13729               || (cu->language == language_ada
13730                   && (last_die->tag == DW_TAG_subprogram
13731                       || last_die->tag == DW_TAG_lexical_block))))
13732         {
13733           nesting_level++;
13734           parent_die = last_die;
13735           continue;
13736         }
13737
13738       /* Otherwise we skip to the next sibling, if any.  */
13739       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13740
13741       /* Back to the top, do it again.  */
13742     }
13743 }
13744
13745 /* Read a minimal amount of information into the minimal die structure.  */
13746
13747 static const gdb_byte *
13748 read_partial_die (const struct die_reader_specs *reader,
13749                   struct partial_die_info *part_die,
13750                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13751                   const gdb_byte *info_ptr)
13752 {
13753   struct dwarf2_cu *cu = reader->cu;
13754   struct objfile *objfile = cu->objfile;
13755   const gdb_byte *buffer = reader->buffer;
13756   unsigned int i;
13757   struct attribute attr;
13758   int has_low_pc_attr = 0;
13759   int has_high_pc_attr = 0;
13760   int high_pc_relative = 0;
13761
13762   memset (part_die, 0, sizeof (struct partial_die_info));
13763
13764   part_die->offset.sect_off = info_ptr - buffer;
13765
13766   info_ptr += abbrev_len;
13767
13768   if (abbrev == NULL)
13769     return info_ptr;
13770
13771   part_die->tag = abbrev->tag;
13772   part_die->has_children = abbrev->has_children;
13773
13774   for (i = 0; i < abbrev->num_attrs; ++i)
13775     {
13776       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13777
13778       /* Store the data if it is of an attribute we want to keep in a
13779          partial symbol table.  */
13780       switch (attr.name)
13781         {
13782         case DW_AT_name:
13783           switch (part_die->tag)
13784             {
13785             case DW_TAG_compile_unit:
13786             case DW_TAG_partial_unit:
13787             case DW_TAG_type_unit:
13788               /* Compilation units have a DW_AT_name that is a filename, not
13789                  a source language identifier.  */
13790             case DW_TAG_enumeration_type:
13791             case DW_TAG_enumerator:
13792               /* These tags always have simple identifiers already; no need
13793                  to canonicalize them.  */
13794               part_die->name = DW_STRING (&attr);
13795               break;
13796             default:
13797               part_die->name
13798                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13799                                             &objfile->objfile_obstack);
13800               break;
13801             }
13802           break;
13803         case DW_AT_linkage_name:
13804         case DW_AT_MIPS_linkage_name:
13805           /* Note that both forms of linkage name might appear.  We
13806              assume they will be the same, and we only store the last
13807              one we see.  */
13808           if (cu->language == language_ada)
13809             part_die->name = DW_STRING (&attr);
13810           part_die->linkage_name = DW_STRING (&attr);
13811           break;
13812         case DW_AT_low_pc:
13813           has_low_pc_attr = 1;
13814           part_die->lowpc = DW_ADDR (&attr);
13815           break;
13816         case DW_AT_high_pc:
13817           has_high_pc_attr = 1;
13818           if (attr.form == DW_FORM_addr
13819               || attr.form == DW_FORM_GNU_addr_index)
13820             part_die->highpc = DW_ADDR (&attr);
13821           else
13822             {
13823               high_pc_relative = 1;
13824               part_die->highpc = DW_UNSND (&attr);
13825             }
13826           break;
13827         case DW_AT_location:
13828           /* Support the .debug_loc offsets.  */
13829           if (attr_form_is_block (&attr))
13830             {
13831                part_die->d.locdesc = DW_BLOCK (&attr);
13832             }
13833           else if (attr_form_is_section_offset (&attr))
13834             {
13835               dwarf2_complex_location_expr_complaint ();
13836             }
13837           else
13838             {
13839               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13840                                                      "partial symbol information");
13841             }
13842           break;
13843         case DW_AT_external:
13844           part_die->is_external = DW_UNSND (&attr);
13845           break;
13846         case DW_AT_declaration:
13847           part_die->is_declaration = DW_UNSND (&attr);
13848           break;
13849         case DW_AT_type:
13850           part_die->has_type = 1;
13851           break;
13852         case DW_AT_abstract_origin:
13853         case DW_AT_specification:
13854         case DW_AT_extension:
13855           part_die->has_specification = 1;
13856           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13857           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13858                                    || cu->per_cu->is_dwz);
13859           break;
13860         case DW_AT_sibling:
13861           /* Ignore absolute siblings, they might point outside of
13862              the current compile unit.  */
13863           if (attr.form == DW_FORM_ref_addr)
13864             complaint (&symfile_complaints,
13865                        _("ignoring absolute DW_AT_sibling"));
13866           else
13867             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13868           break;
13869         case DW_AT_byte_size:
13870           part_die->has_byte_size = 1;
13871           break;
13872         case DW_AT_calling_convention:
13873           /* DWARF doesn't provide a way to identify a program's source-level
13874              entry point.  DW_AT_calling_convention attributes are only meant
13875              to describe functions' calling conventions.
13876
13877              However, because it's a necessary piece of information in
13878              Fortran, and because DW_CC_program is the only piece of debugging
13879              information whose definition refers to a 'main program' at all,
13880              several compilers have begun marking Fortran main programs with
13881              DW_CC_program --- even when those functions use the standard
13882              calling conventions.
13883
13884              So until DWARF specifies a way to provide this information and
13885              compilers pick up the new representation, we'll support this
13886              practice.  */
13887           if (DW_UNSND (&attr) == DW_CC_program
13888               && cu->language == language_fortran)
13889             {
13890               set_main_name (part_die->name);
13891
13892               /* As this DIE has a static linkage the name would be difficult
13893                  to look up later.  */
13894               language_of_main = language_fortran;
13895             }
13896           break;
13897         case DW_AT_inline:
13898           if (DW_UNSND (&attr) == DW_INL_inlined
13899               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13900             part_die->may_be_inlined = 1;
13901           break;
13902
13903         case DW_AT_import:
13904           if (part_die->tag == DW_TAG_imported_unit)
13905             {
13906               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13907               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13908                                   || cu->per_cu->is_dwz);
13909             }
13910           break;
13911
13912         default:
13913           break;
13914         }
13915     }
13916
13917   if (high_pc_relative)
13918     part_die->highpc += part_die->lowpc;
13919
13920   if (has_low_pc_attr && has_high_pc_attr)
13921     {
13922       /* When using the GNU linker, .gnu.linkonce. sections are used to
13923          eliminate duplicate copies of functions and vtables and such.
13924          The linker will arbitrarily choose one and discard the others.
13925          The AT_*_pc values for such functions refer to local labels in
13926          these sections.  If the section from that file was discarded, the
13927          labels are not in the output, so the relocs get a value of 0.
13928          If this is a discarded function, mark the pc bounds as invalid,
13929          so that GDB will ignore it.  */
13930       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13931         {
13932           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13933
13934           complaint (&symfile_complaints,
13935                      _("DW_AT_low_pc %s is zero "
13936                        "for DIE at 0x%x [in module %s]"),
13937                      paddress (gdbarch, part_die->lowpc),
13938                      part_die->offset.sect_off, objfile->name);
13939         }
13940       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13941       else if (part_die->lowpc >= part_die->highpc)
13942         {
13943           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13944
13945           complaint (&symfile_complaints,
13946                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13947                        "for DIE at 0x%x [in module %s]"),
13948                      paddress (gdbarch, part_die->lowpc),
13949                      paddress (gdbarch, part_die->highpc),
13950                      part_die->offset.sect_off, objfile->name);
13951         }
13952       else
13953         part_die->has_pc_info = 1;
13954     }
13955
13956   return info_ptr;
13957 }
13958
13959 /* Find a cached partial DIE at OFFSET in CU.  */
13960
13961 static struct partial_die_info *
13962 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13963 {
13964   struct partial_die_info *lookup_die = NULL;
13965   struct partial_die_info part_die;
13966
13967   part_die.offset = offset;
13968   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13969                                     offset.sect_off);
13970
13971   return lookup_die;
13972 }
13973
13974 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13975    except in the case of .debug_types DIEs which do not reference
13976    outside their CU (they do however referencing other types via
13977    DW_FORM_ref_sig8).  */
13978
13979 static struct partial_die_info *
13980 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13981 {
13982   struct objfile *objfile = cu->objfile;
13983   struct dwarf2_per_cu_data *per_cu = NULL;
13984   struct partial_die_info *pd = NULL;
13985
13986   if (offset_in_dwz == cu->per_cu->is_dwz
13987       && offset_in_cu_p (&cu->header, offset))
13988     {
13989       pd = find_partial_die_in_comp_unit (offset, cu);
13990       if (pd != NULL)
13991         return pd;
13992       /* We missed recording what we needed.
13993          Load all dies and try again.  */
13994       per_cu = cu->per_cu;
13995     }
13996   else
13997     {
13998       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13999       if (cu->per_cu->is_debug_types)
14000         {
14001           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
14002                    " external reference to offset 0x%lx [in module %s].\n"),
14003                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14004                  bfd_get_filename (objfile->obfd));
14005         }
14006       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14007                                                  objfile);
14008
14009       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14010         load_partial_comp_unit (per_cu);
14011
14012       per_cu->cu->last_used = 0;
14013       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14014     }
14015
14016   /* If we didn't find it, and not all dies have been loaded,
14017      load them all and try again.  */
14018
14019   if (pd == NULL && per_cu->load_all_dies == 0)
14020     {
14021       per_cu->load_all_dies = 1;
14022
14023       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14024          THIS_CU->cu may already be in use.  So we can't just free it and
14025          replace its DIEs with the ones we read in.  Instead, we leave those
14026          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14027          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14028          set.  */
14029       load_partial_comp_unit (per_cu);
14030
14031       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14032     }
14033
14034   if (pd == NULL)
14035     internal_error (__FILE__, __LINE__,
14036                     _("could not find partial DIE 0x%x "
14037                       "in cache [from module %s]\n"),
14038                     offset.sect_off, bfd_get_filename (objfile->obfd));
14039   return pd;
14040 }
14041
14042 /* See if we can figure out if the class lives in a namespace.  We do
14043    this by looking for a member function; its demangled name will
14044    contain namespace info, if there is any.  */
14045
14046 static void
14047 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14048                                   struct dwarf2_cu *cu)
14049 {
14050   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14051      what template types look like, because the demangler
14052      frequently doesn't give the same name as the debug info.  We
14053      could fix this by only using the demangled name to get the
14054      prefix (but see comment in read_structure_type).  */
14055
14056   struct partial_die_info *real_pdi;
14057   struct partial_die_info *child_pdi;
14058
14059   /* If this DIE (this DIE's specification, if any) has a parent, then
14060      we should not do this.  We'll prepend the parent's fully qualified
14061      name when we create the partial symbol.  */
14062
14063   real_pdi = struct_pdi;
14064   while (real_pdi->has_specification)
14065     real_pdi = find_partial_die (real_pdi->spec_offset,
14066                                  real_pdi->spec_is_dwz, cu);
14067
14068   if (real_pdi->die_parent != NULL)
14069     return;
14070
14071   for (child_pdi = struct_pdi->die_child;
14072        child_pdi != NULL;
14073        child_pdi = child_pdi->die_sibling)
14074     {
14075       if (child_pdi->tag == DW_TAG_subprogram
14076           && child_pdi->linkage_name != NULL)
14077         {
14078           char *actual_class_name
14079             = language_class_name_from_physname (cu->language_defn,
14080                                                  child_pdi->linkage_name);
14081           if (actual_class_name != NULL)
14082             {
14083               struct_pdi->name
14084                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14085                                  actual_class_name,
14086                                  strlen (actual_class_name));
14087               xfree (actual_class_name);
14088             }
14089           break;
14090         }
14091     }
14092 }
14093
14094 /* Adjust PART_DIE before generating a symbol for it.  This function
14095    may set the is_external flag or change the DIE's name.  */
14096
14097 static void
14098 fixup_partial_die (struct partial_die_info *part_die,
14099                    struct dwarf2_cu *cu)
14100 {
14101   /* Once we've fixed up a die, there's no point in doing so again.
14102      This also avoids a memory leak if we were to call
14103      guess_partial_die_structure_name multiple times.  */
14104   if (part_die->fixup_called)
14105     return;
14106
14107   /* If we found a reference attribute and the DIE has no name, try
14108      to find a name in the referred to DIE.  */
14109
14110   if (part_die->name == NULL && part_die->has_specification)
14111     {
14112       struct partial_die_info *spec_die;
14113
14114       spec_die = find_partial_die (part_die->spec_offset,
14115                                    part_die->spec_is_dwz, cu);
14116
14117       fixup_partial_die (spec_die, cu);
14118
14119       if (spec_die->name)
14120         {
14121           part_die->name = spec_die->name;
14122
14123           /* Copy DW_AT_external attribute if it is set.  */
14124           if (spec_die->is_external)
14125             part_die->is_external = spec_die->is_external;
14126         }
14127     }
14128
14129   /* Set default names for some unnamed DIEs.  */
14130
14131   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14132     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14133
14134   /* If there is no parent die to provide a namespace, and there are
14135      children, see if we can determine the namespace from their linkage
14136      name.  */
14137   if (cu->language == language_cplus
14138       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14139       && part_die->die_parent == NULL
14140       && part_die->has_children
14141       && (part_die->tag == DW_TAG_class_type
14142           || part_die->tag == DW_TAG_structure_type
14143           || part_die->tag == DW_TAG_union_type))
14144     guess_partial_die_structure_name (part_die, cu);
14145
14146   /* GCC might emit a nameless struct or union that has a linkage
14147      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14148   if (part_die->name == NULL
14149       && (part_die->tag == DW_TAG_class_type
14150           || part_die->tag == DW_TAG_interface_type
14151           || part_die->tag == DW_TAG_structure_type
14152           || part_die->tag == DW_TAG_union_type)
14153       && part_die->linkage_name != NULL)
14154     {
14155       char *demangled;
14156
14157       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14158       if (demangled)
14159         {
14160           const char *base;
14161
14162           /* Strip any leading namespaces/classes, keep only the base name.
14163              DW_AT_name for named DIEs does not contain the prefixes.  */
14164           base = strrchr (demangled, ':');
14165           if (base && base > demangled && base[-1] == ':')
14166             base++;
14167           else
14168             base = demangled;
14169
14170           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14171                                           base, strlen (base));
14172           xfree (demangled);
14173         }
14174     }
14175
14176   part_die->fixup_called = 1;
14177 }
14178
14179 /* Read an attribute value described by an attribute form.  */
14180
14181 static const gdb_byte *
14182 read_attribute_value (const struct die_reader_specs *reader,
14183                       struct attribute *attr, unsigned form,
14184                       const gdb_byte *info_ptr)
14185 {
14186   struct dwarf2_cu *cu = reader->cu;
14187   bfd *abfd = reader->abfd;
14188   struct comp_unit_head *cu_header = &cu->header;
14189   unsigned int bytes_read;
14190   struct dwarf_block *blk;
14191
14192   attr->form = form;
14193   switch (form)
14194     {
14195     case DW_FORM_ref_addr:
14196       if (cu->header.version == 2)
14197         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14198       else
14199         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14200                                        &cu->header, &bytes_read);
14201       info_ptr += bytes_read;
14202       break;
14203     case DW_FORM_GNU_ref_alt:
14204       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14205       info_ptr += bytes_read;
14206       break;
14207     case DW_FORM_addr:
14208       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14209       info_ptr += bytes_read;
14210       break;
14211     case DW_FORM_block2:
14212       blk = dwarf_alloc_block (cu);
14213       blk->size = read_2_bytes (abfd, info_ptr);
14214       info_ptr += 2;
14215       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14216       info_ptr += blk->size;
14217       DW_BLOCK (attr) = blk;
14218       break;
14219     case DW_FORM_block4:
14220       blk = dwarf_alloc_block (cu);
14221       blk->size = read_4_bytes (abfd, info_ptr);
14222       info_ptr += 4;
14223       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14224       info_ptr += blk->size;
14225       DW_BLOCK (attr) = blk;
14226       break;
14227     case DW_FORM_data2:
14228       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14229       info_ptr += 2;
14230       break;
14231     case DW_FORM_data4:
14232       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14233       info_ptr += 4;
14234       break;
14235     case DW_FORM_data8:
14236       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14237       info_ptr += 8;
14238       break;
14239     case DW_FORM_sec_offset:
14240       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14241       info_ptr += bytes_read;
14242       break;
14243     case DW_FORM_string:
14244       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14245       DW_STRING_IS_CANONICAL (attr) = 0;
14246       info_ptr += bytes_read;
14247       break;
14248     case DW_FORM_strp:
14249       if (!cu->per_cu->is_dwz)
14250         {
14251           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14252                                                    &bytes_read);
14253           DW_STRING_IS_CANONICAL (attr) = 0;
14254           info_ptr += bytes_read;
14255           break;
14256         }
14257       /* FALLTHROUGH */
14258     case DW_FORM_GNU_strp_alt:
14259       {
14260         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14261         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14262                                           &bytes_read);
14263
14264         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14265         DW_STRING_IS_CANONICAL (attr) = 0;
14266         info_ptr += bytes_read;
14267       }
14268       break;
14269     case DW_FORM_exprloc:
14270     case DW_FORM_block:
14271       blk = dwarf_alloc_block (cu);
14272       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14273       info_ptr += bytes_read;
14274       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14275       info_ptr += blk->size;
14276       DW_BLOCK (attr) = blk;
14277       break;
14278     case DW_FORM_block1:
14279       blk = dwarf_alloc_block (cu);
14280       blk->size = read_1_byte (abfd, info_ptr);
14281       info_ptr += 1;
14282       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14283       info_ptr += blk->size;
14284       DW_BLOCK (attr) = blk;
14285       break;
14286     case DW_FORM_data1:
14287       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14288       info_ptr += 1;
14289       break;
14290     case DW_FORM_flag:
14291       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14292       info_ptr += 1;
14293       break;
14294     case DW_FORM_flag_present:
14295       DW_UNSND (attr) = 1;
14296       break;
14297     case DW_FORM_sdata:
14298       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14299       info_ptr += bytes_read;
14300       break;
14301     case DW_FORM_udata:
14302       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14303       info_ptr += bytes_read;
14304       break;
14305     case DW_FORM_ref1:
14306       DW_UNSND (attr) = (cu->header.offset.sect_off
14307                          + read_1_byte (abfd, info_ptr));
14308       info_ptr += 1;
14309       break;
14310     case DW_FORM_ref2:
14311       DW_UNSND (attr) = (cu->header.offset.sect_off
14312                          + read_2_bytes (abfd, info_ptr));
14313       info_ptr += 2;
14314       break;
14315     case DW_FORM_ref4:
14316       DW_UNSND (attr) = (cu->header.offset.sect_off
14317                          + read_4_bytes (abfd, info_ptr));
14318       info_ptr += 4;
14319       break;
14320     case DW_FORM_ref8:
14321       DW_UNSND (attr) = (cu->header.offset.sect_off
14322                          + read_8_bytes (abfd, info_ptr));
14323       info_ptr += 8;
14324       break;
14325     case DW_FORM_ref_sig8:
14326       /* Convert the signature to something we can record in DW_UNSND
14327          for later lookup.
14328          NOTE: This is NULL if the type wasn't found.  */
14329       DW_SIGNATURED_TYPE (attr) =
14330         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14331       info_ptr += 8;
14332       break;
14333     case DW_FORM_ref_udata:
14334       DW_UNSND (attr) = (cu->header.offset.sect_off
14335                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14336       info_ptr += bytes_read;
14337       break;
14338     case DW_FORM_indirect:
14339       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14340       info_ptr += bytes_read;
14341       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14342       break;
14343     case DW_FORM_GNU_addr_index:
14344       if (reader->dwo_file == NULL)
14345         {
14346           /* For now flag a hard error.
14347              Later we can turn this into a complaint.  */
14348           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14349                  dwarf_form_name (form),
14350                  bfd_get_filename (abfd));
14351         }
14352       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14353       info_ptr += bytes_read;
14354       break;
14355     case DW_FORM_GNU_str_index:
14356       if (reader->dwo_file == NULL)
14357         {
14358           /* For now flag a hard error.
14359              Later we can turn this into a complaint if warranted.  */
14360           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14361                  dwarf_form_name (form),
14362                  bfd_get_filename (abfd));
14363         }
14364       {
14365         ULONGEST str_index =
14366           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14367
14368         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14369         DW_STRING_IS_CANONICAL (attr) = 0;
14370         info_ptr += bytes_read;
14371       }
14372       break;
14373     default:
14374       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14375              dwarf_form_name (form),
14376              bfd_get_filename (abfd));
14377     }
14378
14379   /* Super hack.  */
14380   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14381     attr->form = DW_FORM_GNU_ref_alt;
14382
14383   /* We have seen instances where the compiler tried to emit a byte
14384      size attribute of -1 which ended up being encoded as an unsigned
14385      0xffffffff.  Although 0xffffffff is technically a valid size value,
14386      an object of this size seems pretty unlikely so we can relatively
14387      safely treat these cases as if the size attribute was invalid and
14388      treat them as zero by default.  */
14389   if (attr->name == DW_AT_byte_size
14390       && form == DW_FORM_data4
14391       && DW_UNSND (attr) >= 0xffffffff)
14392     {
14393       complaint
14394         (&symfile_complaints,
14395          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14396          hex_string (DW_UNSND (attr)));
14397       DW_UNSND (attr) = 0;
14398     }
14399
14400   return info_ptr;
14401 }
14402
14403 /* Read an attribute described by an abbreviated attribute.  */
14404
14405 static const gdb_byte *
14406 read_attribute (const struct die_reader_specs *reader,
14407                 struct attribute *attr, struct attr_abbrev *abbrev,
14408                 const gdb_byte *info_ptr)
14409 {
14410   attr->name = abbrev->name;
14411   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14412 }
14413
14414 /* Read dwarf information from a buffer.  */
14415
14416 static unsigned int
14417 read_1_byte (bfd *abfd, const gdb_byte *buf)
14418 {
14419   return bfd_get_8 (abfd, buf);
14420 }
14421
14422 static int
14423 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14424 {
14425   return bfd_get_signed_8 (abfd, buf);
14426 }
14427
14428 static unsigned int
14429 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14430 {
14431   return bfd_get_16 (abfd, buf);
14432 }
14433
14434 static int
14435 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14436 {
14437   return bfd_get_signed_16 (abfd, buf);
14438 }
14439
14440 static unsigned int
14441 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14442 {
14443   return bfd_get_32 (abfd, buf);
14444 }
14445
14446 static int
14447 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14448 {
14449   return bfd_get_signed_32 (abfd, buf);
14450 }
14451
14452 static ULONGEST
14453 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14454 {
14455   return bfd_get_64 (abfd, buf);
14456 }
14457
14458 static CORE_ADDR
14459 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14460               unsigned int *bytes_read)
14461 {
14462   struct comp_unit_head *cu_header = &cu->header;
14463   CORE_ADDR retval = 0;
14464
14465   if (cu_header->signed_addr_p)
14466     {
14467       switch (cu_header->addr_size)
14468         {
14469         case 2:
14470           retval = bfd_get_signed_16 (abfd, buf);
14471           break;
14472         case 4:
14473           retval = bfd_get_signed_32 (abfd, buf);
14474           break;
14475         case 8:
14476           retval = bfd_get_signed_64 (abfd, buf);
14477           break;
14478         default:
14479           internal_error (__FILE__, __LINE__,
14480                           _("read_address: bad switch, signed [in module %s]"),
14481                           bfd_get_filename (abfd));
14482         }
14483     }
14484   else
14485     {
14486       switch (cu_header->addr_size)
14487         {
14488         case 2:
14489           retval = bfd_get_16 (abfd, buf);
14490           break;
14491         case 4:
14492           retval = bfd_get_32 (abfd, buf);
14493           break;
14494         case 8:
14495           retval = bfd_get_64 (abfd, buf);
14496           break;
14497         default:
14498           internal_error (__FILE__, __LINE__,
14499                           _("read_address: bad switch, "
14500                             "unsigned [in module %s]"),
14501                           bfd_get_filename (abfd));
14502         }
14503     }
14504
14505   *bytes_read = cu_header->addr_size;
14506   return retval;
14507 }
14508
14509 /* Read the initial length from a section.  The (draft) DWARF 3
14510    specification allows the initial length to take up either 4 bytes
14511    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14512    bytes describe the length and all offsets will be 8 bytes in length
14513    instead of 4.
14514
14515    An older, non-standard 64-bit format is also handled by this
14516    function.  The older format in question stores the initial length
14517    as an 8-byte quantity without an escape value.  Lengths greater
14518    than 2^32 aren't very common which means that the initial 4 bytes
14519    is almost always zero.  Since a length value of zero doesn't make
14520    sense for the 32-bit format, this initial zero can be considered to
14521    be an escape value which indicates the presence of the older 64-bit
14522    format.  As written, the code can't detect (old format) lengths
14523    greater than 4GB.  If it becomes necessary to handle lengths
14524    somewhat larger than 4GB, we could allow other small values (such
14525    as the non-sensical values of 1, 2, and 3) to also be used as
14526    escape values indicating the presence of the old format.
14527
14528    The value returned via bytes_read should be used to increment the
14529    relevant pointer after calling read_initial_length().
14530
14531    [ Note:  read_initial_length() and read_offset() are based on the
14532      document entitled "DWARF Debugging Information Format", revision
14533      3, draft 8, dated November 19, 2001.  This document was obtained
14534      from:
14535
14536         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14537
14538      This document is only a draft and is subject to change.  (So beware.)
14539
14540      Details regarding the older, non-standard 64-bit format were
14541      determined empirically by examining 64-bit ELF files produced by
14542      the SGI toolchain on an IRIX 6.5 machine.
14543
14544      - Kevin, July 16, 2002
14545    ] */
14546
14547 static LONGEST
14548 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
14549 {
14550   LONGEST length = bfd_get_32 (abfd, buf);
14551
14552   if (length == 0xffffffff)
14553     {
14554       length = bfd_get_64 (abfd, buf + 4);
14555       *bytes_read = 12;
14556     }
14557   else if (length == 0)
14558     {
14559       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14560       length = bfd_get_64 (abfd, buf);
14561       *bytes_read = 8;
14562     }
14563   else
14564     {
14565       *bytes_read = 4;
14566     }
14567
14568   return length;
14569 }
14570
14571 /* Cover function for read_initial_length.
14572    Returns the length of the object at BUF, and stores the size of the
14573    initial length in *BYTES_READ and stores the size that offsets will be in
14574    *OFFSET_SIZE.
14575    If the initial length size is not equivalent to that specified in
14576    CU_HEADER then issue a complaint.
14577    This is useful when reading non-comp-unit headers.  */
14578
14579 static LONGEST
14580 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
14581                                         const struct comp_unit_head *cu_header,
14582                                         unsigned int *bytes_read,
14583                                         unsigned int *offset_size)
14584 {
14585   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14586
14587   gdb_assert (cu_header->initial_length_size == 4
14588               || cu_header->initial_length_size == 8
14589               || cu_header->initial_length_size == 12);
14590
14591   if (cu_header->initial_length_size != *bytes_read)
14592     complaint (&symfile_complaints,
14593                _("intermixed 32-bit and 64-bit DWARF sections"));
14594
14595   *offset_size = (*bytes_read == 4) ? 4 : 8;
14596   return length;
14597 }
14598
14599 /* Read an offset from the data stream.  The size of the offset is
14600    given by cu_header->offset_size.  */
14601
14602 static LONGEST
14603 read_offset (bfd *abfd, const gdb_byte *buf,
14604              const struct comp_unit_head *cu_header,
14605              unsigned int *bytes_read)
14606 {
14607   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14608
14609   *bytes_read = cu_header->offset_size;
14610   return offset;
14611 }
14612
14613 /* Read an offset from the data stream.  */
14614
14615 static LONGEST
14616 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
14617 {
14618   LONGEST retval = 0;
14619
14620   switch (offset_size)
14621     {
14622     case 4:
14623       retval = bfd_get_32 (abfd, buf);
14624       break;
14625     case 8:
14626       retval = bfd_get_64 (abfd, buf);
14627       break;
14628     default:
14629       internal_error (__FILE__, __LINE__,
14630                       _("read_offset_1: bad switch [in module %s]"),
14631                       bfd_get_filename (abfd));
14632     }
14633
14634   return retval;
14635 }
14636
14637 static const gdb_byte *
14638 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
14639 {
14640   /* If the size of a host char is 8 bits, we can return a pointer
14641      to the buffer, otherwise we have to copy the data to a buffer
14642      allocated on the temporary obstack.  */
14643   gdb_assert (HOST_CHAR_BIT == 8);
14644   return buf;
14645 }
14646
14647 static const char *
14648 read_direct_string (bfd *abfd, const gdb_byte *buf,
14649                     unsigned int *bytes_read_ptr)
14650 {
14651   /* If the size of a host char is 8 bits, we can return a pointer
14652      to the string, otherwise we have to copy the string to a buffer
14653      allocated on the temporary obstack.  */
14654   gdb_assert (HOST_CHAR_BIT == 8);
14655   if (*buf == '\0')
14656     {
14657       *bytes_read_ptr = 1;
14658       return NULL;
14659     }
14660   *bytes_read_ptr = strlen ((const char *) buf) + 1;
14661   return (const char *) buf;
14662 }
14663
14664 static const char *
14665 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14666 {
14667   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14668   if (dwarf2_per_objfile->str.buffer == NULL)
14669     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14670            bfd_get_filename (abfd));
14671   if (str_offset >= dwarf2_per_objfile->str.size)
14672     error (_("DW_FORM_strp pointing outside of "
14673              ".debug_str section [in module %s]"),
14674            bfd_get_filename (abfd));
14675   gdb_assert (HOST_CHAR_BIT == 8);
14676   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14677     return NULL;
14678   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
14679 }
14680
14681 /* Read a string at offset STR_OFFSET in the .debug_str section from
14682    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14683    the string consists of a single NUL byte, return NULL; otherwise
14684    return a pointer to the string.  */
14685
14686 static const char *
14687 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14688 {
14689   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14690
14691   if (dwz->str.buffer == NULL)
14692     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14693              "section [in module %s]"),
14694            bfd_get_filename (dwz->dwz_bfd));
14695   if (str_offset >= dwz->str.size)
14696     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14697              ".debug_str section [in module %s]"),
14698            bfd_get_filename (dwz->dwz_bfd));
14699   gdb_assert (HOST_CHAR_BIT == 8);
14700   if (dwz->str.buffer[str_offset] == '\0')
14701     return NULL;
14702   return (const char *) (dwz->str.buffer + str_offset);
14703 }
14704
14705 static const char *
14706 read_indirect_string (bfd *abfd, const gdb_byte *buf,
14707                       const struct comp_unit_head *cu_header,
14708                       unsigned int *bytes_read_ptr)
14709 {
14710   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14711
14712   return read_indirect_string_at_offset (abfd, str_offset);
14713 }
14714
14715 static ULONGEST
14716 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
14717                       unsigned int *bytes_read_ptr)
14718 {
14719   ULONGEST result;
14720   unsigned int num_read;
14721   int i, shift;
14722   unsigned char byte;
14723
14724   result = 0;
14725   shift = 0;
14726   num_read = 0;
14727   i = 0;
14728   while (1)
14729     {
14730       byte = bfd_get_8 (abfd, buf);
14731       buf++;
14732       num_read++;
14733       result |= ((ULONGEST) (byte & 127) << shift);
14734       if ((byte & 128) == 0)
14735         {
14736           break;
14737         }
14738       shift += 7;
14739     }
14740   *bytes_read_ptr = num_read;
14741   return result;
14742 }
14743
14744 static LONGEST
14745 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
14746                     unsigned int *bytes_read_ptr)
14747 {
14748   LONGEST result;
14749   int i, shift, num_read;
14750   unsigned char byte;
14751
14752   result = 0;
14753   shift = 0;
14754   num_read = 0;
14755   i = 0;
14756   while (1)
14757     {
14758       byte = bfd_get_8 (abfd, buf);
14759       buf++;
14760       num_read++;
14761       result |= ((LONGEST) (byte & 127) << shift);
14762       shift += 7;
14763       if ((byte & 128) == 0)
14764         {
14765           break;
14766         }
14767     }
14768   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14769     result |= -(((LONGEST) 1) << shift);
14770   *bytes_read_ptr = num_read;
14771   return result;
14772 }
14773
14774 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14775    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14776    ADDR_SIZE is the size of addresses from the CU header.  */
14777
14778 static CORE_ADDR
14779 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14780 {
14781   struct objfile *objfile = dwarf2_per_objfile->objfile;
14782   bfd *abfd = objfile->obfd;
14783   const gdb_byte *info_ptr;
14784
14785   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14786   if (dwarf2_per_objfile->addr.buffer == NULL)
14787     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14788            objfile->name);
14789   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14790     error (_("DW_FORM_addr_index pointing outside of "
14791              ".debug_addr section [in module %s]"),
14792            objfile->name);
14793   info_ptr = (dwarf2_per_objfile->addr.buffer
14794               + addr_base + addr_index * addr_size);
14795   if (addr_size == 4)
14796     return bfd_get_32 (abfd, info_ptr);
14797   else
14798     return bfd_get_64 (abfd, info_ptr);
14799 }
14800
14801 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14802
14803 static CORE_ADDR
14804 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14805 {
14806   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14807 }
14808
14809 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14810
14811 static CORE_ADDR
14812 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
14813                              unsigned int *bytes_read)
14814 {
14815   bfd *abfd = cu->objfile->obfd;
14816   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14817
14818   return read_addr_index (cu, addr_index);
14819 }
14820
14821 /* Data structure to pass results from dwarf2_read_addr_index_reader
14822    back to dwarf2_read_addr_index.  */
14823
14824 struct dwarf2_read_addr_index_data
14825 {
14826   ULONGEST addr_base;
14827   int addr_size;
14828 };
14829
14830 /* die_reader_func for dwarf2_read_addr_index.  */
14831
14832 static void
14833 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14834                                const gdb_byte *info_ptr,
14835                                struct die_info *comp_unit_die,
14836                                int has_children,
14837                                void *data)
14838 {
14839   struct dwarf2_cu *cu = reader->cu;
14840   struct dwarf2_read_addr_index_data *aidata =
14841     (struct dwarf2_read_addr_index_data *) data;
14842
14843   aidata->addr_base = cu->addr_base;
14844   aidata->addr_size = cu->header.addr_size;
14845 }
14846
14847 /* Given an index in .debug_addr, fetch the value.
14848    NOTE: This can be called during dwarf expression evaluation,
14849    long after the debug information has been read, and thus per_cu->cu
14850    may no longer exist.  */
14851
14852 CORE_ADDR
14853 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14854                         unsigned int addr_index)
14855 {
14856   struct objfile *objfile = per_cu->objfile;
14857   struct dwarf2_cu *cu = per_cu->cu;
14858   ULONGEST addr_base;
14859   int addr_size;
14860
14861   /* This is intended to be called from outside this file.  */
14862   dw2_setup (objfile);
14863
14864   /* We need addr_base and addr_size.
14865      If we don't have PER_CU->cu, we have to get it.
14866      Nasty, but the alternative is storing the needed info in PER_CU,
14867      which at this point doesn't seem justified: it's not clear how frequently
14868      it would get used and it would increase the size of every PER_CU.
14869      Entry points like dwarf2_per_cu_addr_size do a similar thing
14870      so we're not in uncharted territory here.
14871      Alas we need to be a bit more complicated as addr_base is contained
14872      in the DIE.
14873
14874      We don't need to read the entire CU(/TU).
14875      We just need the header and top level die.
14876
14877      IWBN to use the aging mechanism to let us lazily later discard the CU.
14878      For now we skip this optimization.  */
14879
14880   if (cu != NULL)
14881     {
14882       addr_base = cu->addr_base;
14883       addr_size = cu->header.addr_size;
14884     }
14885   else
14886     {
14887       struct dwarf2_read_addr_index_data aidata;
14888
14889       /* Note: We can't use init_cutu_and_read_dies_simple here,
14890          we need addr_base.  */
14891       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14892                                dwarf2_read_addr_index_reader, &aidata);
14893       addr_base = aidata.addr_base;
14894       addr_size = aidata.addr_size;
14895     }
14896
14897   return read_addr_index_1 (addr_index, addr_base, addr_size);
14898 }
14899
14900 /* Given a DW_AT_str_index, fetch the string.  */
14901
14902 static const char *
14903 read_str_index (const struct die_reader_specs *reader,
14904                 struct dwarf2_cu *cu, ULONGEST str_index)
14905 {
14906   struct objfile *objfile = dwarf2_per_objfile->objfile;
14907   const char *dwo_name = objfile->name;
14908   bfd *abfd = objfile->obfd;
14909   struct dwo_sections *sections = &reader->dwo_file->sections;
14910   const gdb_byte *info_ptr;
14911   ULONGEST str_offset;
14912
14913   dwarf2_read_section (objfile, &sections->str);
14914   dwarf2_read_section (objfile, &sections->str_offsets);
14915   if (sections->str.buffer == NULL)
14916     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14917              " in CU at offset 0x%lx [in module %s]"),
14918            (long) cu->header.offset.sect_off, dwo_name);
14919   if (sections->str_offsets.buffer == NULL)
14920     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14921              " in CU at offset 0x%lx [in module %s]"),
14922            (long) cu->header.offset.sect_off, dwo_name);
14923   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14924     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14925              " section in CU at offset 0x%lx [in module %s]"),
14926            (long) cu->header.offset.sect_off, dwo_name);
14927   info_ptr = (sections->str_offsets.buffer
14928               + str_index * cu->header.offset_size);
14929   if (cu->header.offset_size == 4)
14930     str_offset = bfd_get_32 (abfd, info_ptr);
14931   else
14932     str_offset = bfd_get_64 (abfd, info_ptr);
14933   if (str_offset >= sections->str.size)
14934     error (_("Offset from DW_FORM_str_index pointing outside of"
14935              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14936            (long) cu->header.offset.sect_off, dwo_name);
14937   return (const char *) (sections->str.buffer + str_offset);
14938 }
14939
14940 /* Return the length of an LEB128 number in BUF.  */
14941
14942 static int
14943 leb128_size (const gdb_byte *buf)
14944 {
14945   const gdb_byte *begin = buf;
14946   gdb_byte byte;
14947
14948   while (1)
14949     {
14950       byte = *buf++;
14951       if ((byte & 128) == 0)
14952         return buf - begin;
14953     }
14954 }
14955
14956 static void
14957 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14958 {
14959   switch (lang)
14960     {
14961     case DW_LANG_C89:
14962     case DW_LANG_C99:
14963     case DW_LANG_C:
14964       cu->language = language_c;
14965       break;
14966     case DW_LANG_C_plus_plus:
14967       cu->language = language_cplus;
14968       break;
14969     case DW_LANG_D:
14970       cu->language = language_d;
14971       break;
14972     case DW_LANG_Fortran77:
14973     case DW_LANG_Fortran90:
14974     case DW_LANG_Fortran95:
14975       cu->language = language_fortran;
14976       break;
14977     case DW_LANG_Go:
14978       cu->language = language_go;
14979       break;
14980     case DW_LANG_Mips_Assembler:
14981       cu->language = language_asm;
14982       break;
14983     case DW_LANG_Java:
14984       cu->language = language_java;
14985       break;
14986     case DW_LANG_Ada83:
14987     case DW_LANG_Ada95:
14988       cu->language = language_ada;
14989       break;
14990     case DW_LANG_Modula2:
14991       cu->language = language_m2;
14992       break;
14993     case DW_LANG_Pascal83:
14994       cu->language = language_pascal;
14995       break;
14996     case DW_LANG_ObjC:
14997       cu->language = language_objc;
14998       break;
14999     case DW_LANG_Cobol74:
15000     case DW_LANG_Cobol85:
15001     default:
15002       cu->language = language_minimal;
15003       break;
15004     }
15005   cu->language_defn = language_def (cu->language);
15006 }
15007
15008 /* Return the named attribute or NULL if not there.  */
15009
15010 static struct attribute *
15011 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15012 {
15013   for (;;)
15014     {
15015       unsigned int i;
15016       struct attribute *spec = NULL;
15017
15018       for (i = 0; i < die->num_attrs; ++i)
15019         {
15020           if (die->attrs[i].name == name)
15021             return &die->attrs[i];
15022           if (die->attrs[i].name == DW_AT_specification
15023               || die->attrs[i].name == DW_AT_abstract_origin)
15024             spec = &die->attrs[i];
15025         }
15026
15027       if (!spec)
15028         break;
15029
15030       die = follow_die_ref (die, spec, &cu);
15031     }
15032
15033   return NULL;
15034 }
15035
15036 /* Return the named attribute or NULL if not there,
15037    but do not follow DW_AT_specification, etc.
15038    This is for use in contexts where we're reading .debug_types dies.
15039    Following DW_AT_specification, DW_AT_abstract_origin will take us
15040    back up the chain, and we want to go down.  */
15041
15042 static struct attribute *
15043 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15044 {
15045   unsigned int i;
15046
15047   for (i = 0; i < die->num_attrs; ++i)
15048     if (die->attrs[i].name == name)
15049       return &die->attrs[i];
15050
15051   return NULL;
15052 }
15053
15054 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15055    and holds a non-zero value.  This function should only be used for
15056    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15057
15058 static int
15059 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15060 {
15061   struct attribute *attr = dwarf2_attr (die, name, cu);
15062
15063   return (attr && DW_UNSND (attr));
15064 }
15065
15066 static int
15067 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15068 {
15069   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15070      which value is non-zero.  However, we have to be careful with
15071      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15072      (via dwarf2_flag_true_p) follows this attribute.  So we may
15073      end up accidently finding a declaration attribute that belongs
15074      to a different DIE referenced by the specification attribute,
15075      even though the given DIE does not have a declaration attribute.  */
15076   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15077           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15078 }
15079
15080 /* Return the die giving the specification for DIE, if there is
15081    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15082    containing the return value on output.  If there is no
15083    specification, but there is an abstract origin, that is
15084    returned.  */
15085
15086 static struct die_info *
15087 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15088 {
15089   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15090                                              *spec_cu);
15091
15092   if (spec_attr == NULL)
15093     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15094
15095   if (spec_attr == NULL)
15096     return NULL;
15097   else
15098     return follow_die_ref (die, spec_attr, spec_cu);
15099 }
15100
15101 /* Free the line_header structure *LH, and any arrays and strings it
15102    refers to.
15103    NOTE: This is also used as a "cleanup" function.  */
15104
15105 static void
15106 free_line_header (struct line_header *lh)
15107 {
15108   if (lh->standard_opcode_lengths)
15109     xfree (lh->standard_opcode_lengths);
15110
15111   /* Remember that all the lh->file_names[i].name pointers are
15112      pointers into debug_line_buffer, and don't need to be freed.  */
15113   if (lh->file_names)
15114     xfree (lh->file_names);
15115
15116   /* Similarly for the include directory names.  */
15117   if (lh->include_dirs)
15118     xfree (lh->include_dirs);
15119
15120   xfree (lh);
15121 }
15122
15123 /* Add an entry to LH's include directory table.  */
15124
15125 static void
15126 add_include_dir (struct line_header *lh, const char *include_dir)
15127 {
15128   /* Grow the array if necessary.  */
15129   if (lh->include_dirs_size == 0)
15130     {
15131       lh->include_dirs_size = 1; /* for testing */
15132       lh->include_dirs = xmalloc (lh->include_dirs_size
15133                                   * sizeof (*lh->include_dirs));
15134     }
15135   else if (lh->num_include_dirs >= lh->include_dirs_size)
15136     {
15137       lh->include_dirs_size *= 2;
15138       lh->include_dirs = xrealloc (lh->include_dirs,
15139                                    (lh->include_dirs_size
15140                                     * sizeof (*lh->include_dirs)));
15141     }
15142
15143   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15144 }
15145
15146 /* Add an entry to LH's file name table.  */
15147
15148 static void
15149 add_file_name (struct line_header *lh,
15150                const char *name,
15151                unsigned int dir_index,
15152                unsigned int mod_time,
15153                unsigned int length)
15154 {
15155   struct file_entry *fe;
15156
15157   /* Grow the array if necessary.  */
15158   if (lh->file_names_size == 0)
15159     {
15160       lh->file_names_size = 1; /* for testing */
15161       lh->file_names = xmalloc (lh->file_names_size
15162                                 * sizeof (*lh->file_names));
15163     }
15164   else if (lh->num_file_names >= lh->file_names_size)
15165     {
15166       lh->file_names_size *= 2;
15167       lh->file_names = xrealloc (lh->file_names,
15168                                  (lh->file_names_size
15169                                   * sizeof (*lh->file_names)));
15170     }
15171
15172   fe = &lh->file_names[lh->num_file_names++];
15173   fe->name = name;
15174   fe->dir_index = dir_index;
15175   fe->mod_time = mod_time;
15176   fe->length = length;
15177   fe->included_p = 0;
15178   fe->symtab = NULL;
15179 }
15180
15181 /* A convenience function to find the proper .debug_line section for a
15182    CU.  */
15183
15184 static struct dwarf2_section_info *
15185 get_debug_line_section (struct dwarf2_cu *cu)
15186 {
15187   struct dwarf2_section_info *section;
15188
15189   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15190      DWO file.  */
15191   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15192     section = &cu->dwo_unit->dwo_file->sections.line;
15193   else if (cu->per_cu->is_dwz)
15194     {
15195       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15196
15197       section = &dwz->line;
15198     }
15199   else
15200     section = &dwarf2_per_objfile->line;
15201
15202   return section;
15203 }
15204
15205 /* Read the statement program header starting at OFFSET in
15206    .debug_line, or .debug_line.dwo.  Return a pointer
15207    to a struct line_header, allocated using xmalloc.
15208
15209    NOTE: the strings in the include directory and file name tables of
15210    the returned object point into the dwarf line section buffer,
15211    and must not be freed.  */
15212
15213 static struct line_header *
15214 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15215 {
15216   struct cleanup *back_to;
15217   struct line_header *lh;
15218   const gdb_byte *line_ptr;
15219   unsigned int bytes_read, offset_size;
15220   int i;
15221   const char *cur_dir, *cur_file;
15222   struct dwarf2_section_info *section;
15223   bfd *abfd;
15224
15225   section = get_debug_line_section (cu);
15226   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15227   if (section->buffer == NULL)
15228     {
15229       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15230         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15231       else
15232         complaint (&symfile_complaints, _("missing .debug_line section"));
15233       return 0;
15234     }
15235
15236   /* We can't do this until we know the section is non-empty.
15237      Only then do we know we have such a section.  */
15238   abfd = section->asection->owner;
15239
15240   /* Make sure that at least there's room for the total_length field.
15241      That could be 12 bytes long, but we're just going to fudge that.  */
15242   if (offset + 4 >= section->size)
15243     {
15244       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15245       return 0;
15246     }
15247
15248   lh = xmalloc (sizeof (*lh));
15249   memset (lh, 0, sizeof (*lh));
15250   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15251                           (void *) lh);
15252
15253   line_ptr = section->buffer + offset;
15254
15255   /* Read in the header.  */
15256   lh->total_length =
15257     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15258                                             &bytes_read, &offset_size);
15259   line_ptr += bytes_read;
15260   if (line_ptr + lh->total_length > (section->buffer + section->size))
15261     {
15262       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15263       return 0;
15264     }
15265   lh->statement_program_end = line_ptr + lh->total_length;
15266   lh->version = read_2_bytes (abfd, line_ptr);
15267   line_ptr += 2;
15268   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15269   line_ptr += offset_size;
15270   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15271   line_ptr += 1;
15272   if (lh->version >= 4)
15273     {
15274       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15275       line_ptr += 1;
15276     }
15277   else
15278     lh->maximum_ops_per_instruction = 1;
15279
15280   if (lh->maximum_ops_per_instruction == 0)
15281     {
15282       lh->maximum_ops_per_instruction = 1;
15283       complaint (&symfile_complaints,
15284                  _("invalid maximum_ops_per_instruction "
15285                    "in `.debug_line' section"));
15286     }
15287
15288   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15289   line_ptr += 1;
15290   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15291   line_ptr += 1;
15292   lh->line_range = read_1_byte (abfd, line_ptr);
15293   line_ptr += 1;
15294   lh->opcode_base = read_1_byte (abfd, line_ptr);
15295   line_ptr += 1;
15296   lh->standard_opcode_lengths
15297     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15298
15299   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15300   for (i = 1; i < lh->opcode_base; ++i)
15301     {
15302       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15303       line_ptr += 1;
15304     }
15305
15306   /* Read directory table.  */
15307   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15308     {
15309       line_ptr += bytes_read;
15310       add_include_dir (lh, cur_dir);
15311     }
15312   line_ptr += bytes_read;
15313
15314   /* Read file name table.  */
15315   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15316     {
15317       unsigned int dir_index, mod_time, length;
15318
15319       line_ptr += bytes_read;
15320       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15321       line_ptr += bytes_read;
15322       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15323       line_ptr += bytes_read;
15324       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15325       line_ptr += bytes_read;
15326
15327       add_file_name (lh, cur_file, dir_index, mod_time, length);
15328     }
15329   line_ptr += bytes_read;
15330   lh->statement_program_start = line_ptr;
15331
15332   if (line_ptr > (section->buffer + section->size))
15333     complaint (&symfile_complaints,
15334                _("line number info header doesn't "
15335                  "fit in `.debug_line' section"));
15336
15337   discard_cleanups (back_to);
15338   return lh;
15339 }
15340
15341 /* Subroutine of dwarf_decode_lines to simplify it.
15342    Return the file name of the psymtab for included file FILE_INDEX
15343    in line header LH of PST.
15344    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15345    If space for the result is malloc'd, it will be freed by a cleanup.
15346    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15347
15348    The function creates dangling cleanup registration.  */
15349
15350 static const char *
15351 psymtab_include_file_name (const struct line_header *lh, int file_index,
15352                            const struct partial_symtab *pst,
15353                            const char *comp_dir)
15354 {
15355   const struct file_entry fe = lh->file_names [file_index];
15356   const char *include_name = fe.name;
15357   const char *include_name_to_compare = include_name;
15358   const char *dir_name = NULL;
15359   const char *pst_filename;
15360   char *copied_name = NULL;
15361   int file_is_pst;
15362
15363   if (fe.dir_index)
15364     dir_name = lh->include_dirs[fe.dir_index - 1];
15365
15366   if (!IS_ABSOLUTE_PATH (include_name)
15367       && (dir_name != NULL || comp_dir != NULL))
15368     {
15369       /* Avoid creating a duplicate psymtab for PST.
15370          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15371          Before we do the comparison, however, we need to account
15372          for DIR_NAME and COMP_DIR.
15373          First prepend dir_name (if non-NULL).  If we still don't
15374          have an absolute path prepend comp_dir (if non-NULL).
15375          However, the directory we record in the include-file's
15376          psymtab does not contain COMP_DIR (to match the
15377          corresponding symtab(s)).
15378
15379          Example:
15380
15381          bash$ cd /tmp
15382          bash$ gcc -g ./hello.c
15383          include_name = "hello.c"
15384          dir_name = "."
15385          DW_AT_comp_dir = comp_dir = "/tmp"
15386          DW_AT_name = "./hello.c"  */
15387
15388       if (dir_name != NULL)
15389         {
15390           char *tem = concat (dir_name, SLASH_STRING,
15391                               include_name, (char *)NULL);
15392
15393           make_cleanup (xfree, tem);
15394           include_name = tem;
15395           include_name_to_compare = include_name;
15396         }
15397       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15398         {
15399           char *tem = concat (comp_dir, SLASH_STRING,
15400                               include_name, (char *)NULL);
15401
15402           make_cleanup (xfree, tem);
15403           include_name_to_compare = tem;
15404         }
15405     }
15406
15407   pst_filename = pst->filename;
15408   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15409     {
15410       copied_name = concat (pst->dirname, SLASH_STRING,
15411                             pst_filename, (char *)NULL);
15412       pst_filename = copied_name;
15413     }
15414
15415   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15416
15417   if (copied_name != NULL)
15418     xfree (copied_name);
15419
15420   if (file_is_pst)
15421     return NULL;
15422   return include_name;
15423 }
15424
15425 /* Ignore this record_line request.  */
15426
15427 static void
15428 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15429 {
15430   return;
15431 }
15432
15433 /* Subroutine of dwarf_decode_lines to simplify it.
15434    Process the line number information in LH.  */
15435
15436 static void
15437 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15438                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15439 {
15440   const gdb_byte *line_ptr, *extended_end;
15441   const gdb_byte *line_end;
15442   unsigned int bytes_read, extended_len;
15443   unsigned char op_code, extended_op, adj_opcode;
15444   CORE_ADDR baseaddr;
15445   struct objfile *objfile = cu->objfile;
15446   bfd *abfd = objfile->obfd;
15447   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15448   const int decode_for_pst_p = (pst != NULL);
15449   struct subfile *last_subfile = NULL;
15450   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15451     = record_line;
15452
15453   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15454
15455   line_ptr = lh->statement_program_start;
15456   line_end = lh->statement_program_end;
15457
15458   /* Read the statement sequences until there's nothing left.  */
15459   while (line_ptr < line_end)
15460     {
15461       /* state machine registers  */
15462       CORE_ADDR address = 0;
15463       unsigned int file = 1;
15464       unsigned int line = 1;
15465       unsigned int column = 0;
15466       int is_stmt = lh->default_is_stmt;
15467       int basic_block = 0;
15468       int end_sequence = 0;
15469       CORE_ADDR addr;
15470       unsigned char op_index = 0;
15471
15472       if (!decode_for_pst_p && lh->num_file_names >= file)
15473         {
15474           /* Start a subfile for the current file of the state machine.  */
15475           /* lh->include_dirs and lh->file_names are 0-based, but the
15476              directory and file name numbers in the statement program
15477              are 1-based.  */
15478           struct file_entry *fe = &lh->file_names[file - 1];
15479           const char *dir = NULL;
15480
15481           if (fe->dir_index)
15482             dir = lh->include_dirs[fe->dir_index - 1];
15483
15484           dwarf2_start_subfile (fe->name, dir, comp_dir);
15485         }
15486
15487       /* Decode the table.  */
15488       while (!end_sequence)
15489         {
15490           op_code = read_1_byte (abfd, line_ptr);
15491           line_ptr += 1;
15492           if (line_ptr > line_end)
15493             {
15494               dwarf2_debug_line_missing_end_sequence_complaint ();
15495               break;
15496             }
15497
15498           if (op_code >= lh->opcode_base)
15499             {
15500               /* Special operand.  */
15501               adj_opcode = op_code - lh->opcode_base;
15502               address += (((op_index + (adj_opcode / lh->line_range))
15503                            / lh->maximum_ops_per_instruction)
15504                           * lh->minimum_instruction_length);
15505               op_index = ((op_index + (adj_opcode / lh->line_range))
15506                           % lh->maximum_ops_per_instruction);
15507               line += lh->line_base + (adj_opcode % lh->line_range);
15508               if (lh->num_file_names < file || file == 0)
15509                 dwarf2_debug_line_missing_file_complaint ();
15510               /* For now we ignore lines not starting on an
15511                  instruction boundary.  */
15512               else if (op_index == 0)
15513                 {
15514                   lh->file_names[file - 1].included_p = 1;
15515                   if (!decode_for_pst_p && is_stmt)
15516                     {
15517                       if (last_subfile != current_subfile)
15518                         {
15519                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15520                           if (last_subfile)
15521                             (*p_record_line) (last_subfile, 0, addr);
15522                           last_subfile = current_subfile;
15523                         }
15524                       /* Append row to matrix using current values.  */
15525                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15526                       (*p_record_line) (current_subfile, line, addr);
15527                     }
15528                 }
15529               basic_block = 0;
15530             }
15531           else switch (op_code)
15532             {
15533             case DW_LNS_extended_op:
15534               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15535                                                    &bytes_read);
15536               line_ptr += bytes_read;
15537               extended_end = line_ptr + extended_len;
15538               extended_op = read_1_byte (abfd, line_ptr);
15539               line_ptr += 1;
15540               switch (extended_op)
15541                 {
15542                 case DW_LNE_end_sequence:
15543                   p_record_line = record_line;
15544                   end_sequence = 1;
15545                   break;
15546                 case DW_LNE_set_address:
15547                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15548
15549                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15550                     {
15551                       /* This line table is for a function which has been
15552                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15553
15554                       long line_offset
15555                         = line_ptr - get_debug_line_section (cu)->buffer;
15556
15557                       complaint (&symfile_complaints,
15558                                  _(".debug_line address at offset 0x%lx is 0 "
15559                                    "[in module %s]"),
15560                                  line_offset, objfile->name);
15561                       p_record_line = noop_record_line;
15562                     }
15563
15564                   op_index = 0;
15565                   line_ptr += bytes_read;
15566                   address += baseaddr;
15567                   break;
15568                 case DW_LNE_define_file:
15569                   {
15570                     const char *cur_file;
15571                     unsigned int dir_index, mod_time, length;
15572
15573                     cur_file = read_direct_string (abfd, line_ptr,
15574                                                    &bytes_read);
15575                     line_ptr += bytes_read;
15576                     dir_index =
15577                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15578                     line_ptr += bytes_read;
15579                     mod_time =
15580                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15581                     line_ptr += bytes_read;
15582                     length =
15583                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15584                     line_ptr += bytes_read;
15585                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15586                   }
15587                   break;
15588                 case DW_LNE_set_discriminator:
15589                   /* The discriminator is not interesting to the debugger;
15590                      just ignore it.  */
15591                   line_ptr = extended_end;
15592                   break;
15593                 default:
15594                   complaint (&symfile_complaints,
15595                              _("mangled .debug_line section"));
15596                   return;
15597                 }
15598               /* Make sure that we parsed the extended op correctly.  If e.g.
15599                  we expected a different address size than the producer used,
15600                  we may have read the wrong number of bytes.  */
15601               if (line_ptr != extended_end)
15602                 {
15603                   complaint (&symfile_complaints,
15604                              _("mangled .debug_line section"));
15605                   return;
15606                 }
15607               break;
15608             case DW_LNS_copy:
15609               if (lh->num_file_names < file || file == 0)
15610                 dwarf2_debug_line_missing_file_complaint ();
15611               else
15612                 {
15613                   lh->file_names[file - 1].included_p = 1;
15614                   if (!decode_for_pst_p && is_stmt)
15615                     {
15616                       if (last_subfile != current_subfile)
15617                         {
15618                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15619                           if (last_subfile)
15620                             (*p_record_line) (last_subfile, 0, addr);
15621                           last_subfile = current_subfile;
15622                         }
15623                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15624                       (*p_record_line) (current_subfile, line, addr);
15625                     }
15626                 }
15627               basic_block = 0;
15628               break;
15629             case DW_LNS_advance_pc:
15630               {
15631                 CORE_ADDR adjust
15632                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15633
15634                 address += (((op_index + adjust)
15635                              / lh->maximum_ops_per_instruction)
15636                             * lh->minimum_instruction_length);
15637                 op_index = ((op_index + adjust)
15638                             % lh->maximum_ops_per_instruction);
15639                 line_ptr += bytes_read;
15640               }
15641               break;
15642             case DW_LNS_advance_line:
15643               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15644               line_ptr += bytes_read;
15645               break;
15646             case DW_LNS_set_file:
15647               {
15648                 /* The arrays lh->include_dirs and lh->file_names are
15649                    0-based, but the directory and file name numbers in
15650                    the statement program are 1-based.  */
15651                 struct file_entry *fe;
15652                 const char *dir = NULL;
15653
15654                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15655                 line_ptr += bytes_read;
15656                 if (lh->num_file_names < file || file == 0)
15657                   dwarf2_debug_line_missing_file_complaint ();
15658                 else
15659                   {
15660                     fe = &lh->file_names[file - 1];
15661                     if (fe->dir_index)
15662                       dir = lh->include_dirs[fe->dir_index - 1];
15663                     if (!decode_for_pst_p)
15664                       {
15665                         last_subfile = current_subfile;
15666                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15667                       }
15668                   }
15669               }
15670               break;
15671             case DW_LNS_set_column:
15672               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15673               line_ptr += bytes_read;
15674               break;
15675             case DW_LNS_negate_stmt:
15676               is_stmt = (!is_stmt);
15677               break;
15678             case DW_LNS_set_basic_block:
15679               basic_block = 1;
15680               break;
15681             /* Add to the address register of the state machine the
15682                address increment value corresponding to special opcode
15683                255.  I.e., this value is scaled by the minimum
15684                instruction length since special opcode 255 would have
15685                scaled the increment.  */
15686             case DW_LNS_const_add_pc:
15687               {
15688                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15689
15690                 address += (((op_index + adjust)
15691                              / lh->maximum_ops_per_instruction)
15692                             * lh->minimum_instruction_length);
15693                 op_index = ((op_index + adjust)
15694                             % lh->maximum_ops_per_instruction);
15695               }
15696               break;
15697             case DW_LNS_fixed_advance_pc:
15698               address += read_2_bytes (abfd, line_ptr);
15699               op_index = 0;
15700               line_ptr += 2;
15701               break;
15702             default:
15703               {
15704                 /* Unknown standard opcode, ignore it.  */
15705                 int i;
15706
15707                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15708                   {
15709                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15710                     line_ptr += bytes_read;
15711                   }
15712               }
15713             }
15714         }
15715       if (lh->num_file_names < file || file == 0)
15716         dwarf2_debug_line_missing_file_complaint ();
15717       else
15718         {
15719           lh->file_names[file - 1].included_p = 1;
15720           if (!decode_for_pst_p)
15721             {
15722               addr = gdbarch_addr_bits_remove (gdbarch, address);
15723               (*p_record_line) (current_subfile, 0, addr);
15724             }
15725         }
15726     }
15727 }
15728
15729 /* Decode the Line Number Program (LNP) for the given line_header
15730    structure and CU.  The actual information extracted and the type
15731    of structures created from the LNP depends on the value of PST.
15732
15733    1. If PST is NULL, then this procedure uses the data from the program
15734       to create all necessary symbol tables, and their linetables.
15735
15736    2. If PST is not NULL, this procedure reads the program to determine
15737       the list of files included by the unit represented by PST, and
15738       builds all the associated partial symbol tables.
15739
15740    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15741    It is used for relative paths in the line table.
15742    NOTE: When processing partial symtabs (pst != NULL),
15743    comp_dir == pst->dirname.
15744
15745    NOTE: It is important that psymtabs have the same file name (via strcmp)
15746    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15747    symtab we don't use it in the name of the psymtabs we create.
15748    E.g. expand_line_sal requires this when finding psymtabs to expand.
15749    A good testcase for this is mb-inline.exp.  */
15750
15751 static void
15752 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15753                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15754                     int want_line_info)
15755 {
15756   struct objfile *objfile = cu->objfile;
15757   const int decode_for_pst_p = (pst != NULL);
15758   struct subfile *first_subfile = current_subfile;
15759
15760   if (want_line_info)
15761     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15762
15763   if (decode_for_pst_p)
15764     {
15765       int file_index;
15766
15767       /* Now that we're done scanning the Line Header Program, we can
15768          create the psymtab of each included file.  */
15769       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15770         if (lh->file_names[file_index].included_p == 1)
15771           {
15772             const char *include_name =
15773               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15774             if (include_name != NULL)
15775               dwarf2_create_include_psymtab (include_name, pst, objfile);
15776           }
15777     }
15778   else
15779     {
15780       /* Make sure a symtab is created for every file, even files
15781          which contain only variables (i.e. no code with associated
15782          line numbers).  */
15783       int i;
15784
15785       for (i = 0; i < lh->num_file_names; i++)
15786         {
15787           const char *dir = NULL;
15788           struct file_entry *fe;
15789
15790           fe = &lh->file_names[i];
15791           if (fe->dir_index)
15792             dir = lh->include_dirs[fe->dir_index - 1];
15793           dwarf2_start_subfile (fe->name, dir, comp_dir);
15794
15795           /* Skip the main file; we don't need it, and it must be
15796              allocated last, so that it will show up before the
15797              non-primary symtabs in the objfile's symtab list.  */
15798           if (current_subfile == first_subfile)
15799             continue;
15800
15801           if (current_subfile->symtab == NULL)
15802             current_subfile->symtab = allocate_symtab (current_subfile->name,
15803                                                        objfile);
15804           fe->symtab = current_subfile->symtab;
15805         }
15806     }
15807 }
15808
15809 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15810    DIRNAME the name of the source directory which contains FILENAME
15811    or NULL if not known.  COMP_DIR is the compilation directory for the
15812    linetable's compilation unit or NULL if not known.
15813    This routine tries to keep line numbers from identical absolute and
15814    relative file names in a common subfile.
15815
15816    Using the `list' example from the GDB testsuite, which resides in
15817    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15818    of /srcdir/list0.c yields the following debugging information for list0.c:
15819
15820    DW_AT_name:          /srcdir/list0.c
15821    DW_AT_comp_dir:              /compdir
15822    files.files[0].name: list0.h
15823    files.files[0].dir:  /srcdir
15824    files.files[1].name: list0.c
15825    files.files[1].dir:  /srcdir
15826
15827    The line number information for list0.c has to end up in a single
15828    subfile, so that `break /srcdir/list0.c:1' works as expected.
15829    start_subfile will ensure that this happens provided that we pass the
15830    concatenation of files.files[1].dir and files.files[1].name as the
15831    subfile's name.  */
15832
15833 static void
15834 dwarf2_start_subfile (const char *filename, const char *dirname,
15835                       const char *comp_dir)
15836 {
15837   char *copy = NULL;
15838
15839   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15840      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15841      second argument to start_subfile.  To be consistent, we do the
15842      same here.  In order not to lose the line information directory,
15843      we concatenate it to the filename when it makes sense.
15844      Note that the Dwarf3 standard says (speaking of filenames in line
15845      information): ``The directory index is ignored for file names
15846      that represent full path names''.  Thus ignoring dirname in the
15847      `else' branch below isn't an issue.  */
15848
15849   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15850     {
15851       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15852       filename = copy;
15853     }
15854
15855   start_subfile (filename, comp_dir);
15856
15857   if (copy != NULL)
15858     xfree (copy);
15859 }
15860
15861 /* Start a symtab for DWARF.
15862    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15863
15864 static void
15865 dwarf2_start_symtab (struct dwarf2_cu *cu,
15866                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15867 {
15868   start_symtab (name, comp_dir, low_pc);
15869   record_debugformat ("DWARF 2");
15870   record_producer (cu->producer);
15871
15872   /* We assume that we're processing GCC output.  */
15873   processing_gcc_compilation = 2;
15874
15875   cu->processing_has_namespace_info = 0;
15876 }
15877
15878 static void
15879 var_decode_location (struct attribute *attr, struct symbol *sym,
15880                      struct dwarf2_cu *cu)
15881 {
15882   struct objfile *objfile = cu->objfile;
15883   struct comp_unit_head *cu_header = &cu->header;
15884
15885   /* NOTE drow/2003-01-30: There used to be a comment and some special
15886      code here to turn a symbol with DW_AT_external and a
15887      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15888      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15889      with some versions of binutils) where shared libraries could have
15890      relocations against symbols in their debug information - the
15891      minimal symbol would have the right address, but the debug info
15892      would not.  It's no longer necessary, because we will explicitly
15893      apply relocations when we read in the debug information now.  */
15894
15895   /* A DW_AT_location attribute with no contents indicates that a
15896      variable has been optimized away.  */
15897   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15898     {
15899       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15900       return;
15901     }
15902
15903   /* Handle one degenerate form of location expression specially, to
15904      preserve GDB's previous behavior when section offsets are
15905      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15906      then mark this symbol as LOC_STATIC.  */
15907
15908   if (attr_form_is_block (attr)
15909       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15910            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15911           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15912               && (DW_BLOCK (attr)->size
15913                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15914     {
15915       unsigned int dummy;
15916
15917       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15918         SYMBOL_VALUE_ADDRESS (sym) =
15919           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15920       else
15921         SYMBOL_VALUE_ADDRESS (sym) =
15922           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15923       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
15924       fixup_symbol_section (sym, objfile);
15925       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15926                                               SYMBOL_SECTION (sym));
15927       return;
15928     }
15929
15930   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15931      expression evaluator, and use LOC_COMPUTED only when necessary
15932      (i.e. when the value of a register or memory location is
15933      referenced, or a thread-local block, etc.).  Then again, it might
15934      not be worthwhile.  I'm assuming that it isn't unless performance
15935      or memory numbers show me otherwise.  */
15936
15937   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
15938
15939   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
15940     cu->has_loclist = 1;
15941 }
15942
15943 /* Given a pointer to a DWARF information entry, figure out if we need
15944    to make a symbol table entry for it, and if so, create a new entry
15945    and return a pointer to it.
15946    If TYPE is NULL, determine symbol type from the die, otherwise
15947    used the passed type.
15948    If SPACE is not NULL, use it to hold the new symbol.  If it is
15949    NULL, allocate a new symbol on the objfile's obstack.  */
15950
15951 static struct symbol *
15952 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15953                  struct symbol *space)
15954 {
15955   struct objfile *objfile = cu->objfile;
15956   struct symbol *sym = NULL;
15957   const char *name;
15958   struct attribute *attr = NULL;
15959   struct attribute *attr2 = NULL;
15960   CORE_ADDR baseaddr;
15961   struct pending **list_to_add = NULL;
15962
15963   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15964
15965   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15966
15967   name = dwarf2_name (die, cu);
15968   if (name)
15969     {
15970       const char *linkagename;
15971       int suppress_add = 0;
15972
15973       if (space)
15974         sym = space;
15975       else
15976         sym = allocate_symbol (objfile);
15977       OBJSTAT (objfile, n_syms++);
15978
15979       /* Cache this symbol's name and the name's demangled form (if any).  */
15980       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
15981       linkagename = dwarf2_physname (name, die, cu);
15982       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15983
15984       /* Fortran does not have mangling standard and the mangling does differ
15985          between gfortran, iFort etc.  */
15986       if (cu->language == language_fortran
15987           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15988         symbol_set_demangled_name (&(sym->ginfo),
15989                                    dwarf2_full_name (name, die, cu),
15990                                    NULL);
15991
15992       /* Default assumptions.
15993          Use the passed type or decode it from the die.  */
15994       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15995       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15996       if (type != NULL)
15997         SYMBOL_TYPE (sym) = type;
15998       else
15999         SYMBOL_TYPE (sym) = die_type (die, cu);
16000       attr = dwarf2_attr (die,
16001                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
16002                           cu);
16003       if (attr)
16004         {
16005           SYMBOL_LINE (sym) = DW_UNSND (attr);
16006         }
16007
16008       attr = dwarf2_attr (die,
16009                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16010                           cu);
16011       if (attr)
16012         {
16013           int file_index = DW_UNSND (attr);
16014
16015           if (cu->line_header == NULL
16016               || file_index > cu->line_header->num_file_names)
16017             complaint (&symfile_complaints,
16018                        _("file index out of range"));
16019           else if (file_index > 0)
16020             {
16021               struct file_entry *fe;
16022
16023               fe = &cu->line_header->file_names[file_index - 1];
16024               SYMBOL_SYMTAB (sym) = fe->symtab;
16025             }
16026         }
16027
16028       switch (die->tag)
16029         {
16030         case DW_TAG_label:
16031           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16032           if (attr)
16033             {
16034               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16035             }
16036           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16037           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16038           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16039           add_symbol_to_list (sym, cu->list_in_scope);
16040           break;
16041         case DW_TAG_subprogram:
16042           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16043              finish_block.  */
16044           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16045           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16046           if ((attr2 && (DW_UNSND (attr2) != 0))
16047               || cu->language == language_ada)
16048             {
16049               /* Subprograms marked external are stored as a global symbol.
16050                  Ada subprograms, whether marked external or not, are always
16051                  stored as a global symbol, because we want to be able to
16052                  access them globally.  For instance, we want to be able
16053                  to break on a nested subprogram without having to
16054                  specify the context.  */
16055               list_to_add = &global_symbols;
16056             }
16057           else
16058             {
16059               list_to_add = cu->list_in_scope;
16060             }
16061           break;
16062         case DW_TAG_inlined_subroutine:
16063           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16064              finish_block.  */
16065           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16066           SYMBOL_INLINED (sym) = 1;
16067           list_to_add = cu->list_in_scope;
16068           break;
16069         case DW_TAG_template_value_param:
16070           suppress_add = 1;
16071           /* Fall through.  */
16072         case DW_TAG_constant:
16073         case DW_TAG_variable:
16074         case DW_TAG_member:
16075           /* Compilation with minimal debug info may result in
16076              variables with missing type entries.  Change the
16077              misleading `void' type to something sensible.  */
16078           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16079             SYMBOL_TYPE (sym)
16080               = objfile_type (objfile)->nodebug_data_symbol;
16081
16082           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16083           /* In the case of DW_TAG_member, we should only be called for
16084              static const members.  */
16085           if (die->tag == DW_TAG_member)
16086             {
16087               /* dwarf2_add_field uses die_is_declaration,
16088                  so we do the same.  */
16089               gdb_assert (die_is_declaration (die, cu));
16090               gdb_assert (attr);
16091             }
16092           if (attr)
16093             {
16094               dwarf2_const_value (attr, sym, cu);
16095               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16096               if (!suppress_add)
16097                 {
16098                   if (attr2 && (DW_UNSND (attr2) != 0))
16099                     list_to_add = &global_symbols;
16100                   else
16101                     list_to_add = cu->list_in_scope;
16102                 }
16103               break;
16104             }
16105           attr = dwarf2_attr (die, DW_AT_location, cu);
16106           if (attr)
16107             {
16108               var_decode_location (attr, sym, cu);
16109               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16110
16111               /* Fortran explicitly imports any global symbols to the local
16112                  scope by DW_TAG_common_block.  */
16113               if (cu->language == language_fortran && die->parent
16114                   && die->parent->tag == DW_TAG_common_block)
16115                 attr2 = NULL;
16116
16117               if (SYMBOL_CLASS (sym) == LOC_STATIC
16118                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16119                   && !dwarf2_per_objfile->has_section_at_zero)
16120                 {
16121                   /* When a static variable is eliminated by the linker,
16122                      the corresponding debug information is not stripped
16123                      out, but the variable address is set to null;
16124                      do not add such variables into symbol table.  */
16125                 }
16126               else if (attr2 && (DW_UNSND (attr2) != 0))
16127                 {
16128                   /* Workaround gfortran PR debug/40040 - it uses
16129                      DW_AT_location for variables in -fPIC libraries which may
16130                      get overriden by other libraries/executable and get
16131                      a different address.  Resolve it by the minimal symbol
16132                      which may come from inferior's executable using copy
16133                      relocation.  Make this workaround only for gfortran as for
16134                      other compilers GDB cannot guess the minimal symbol
16135                      Fortran mangling kind.  */
16136                   if (cu->language == language_fortran && die->parent
16137                       && die->parent->tag == DW_TAG_module
16138                       && cu->producer
16139                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16140                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16141
16142                   /* A variable with DW_AT_external is never static,
16143                      but it may be block-scoped.  */
16144                   list_to_add = (cu->list_in_scope == &file_symbols
16145                                  ? &global_symbols : cu->list_in_scope);
16146                 }
16147               else
16148                 list_to_add = cu->list_in_scope;
16149             }
16150           else
16151             {
16152               /* We do not know the address of this symbol.
16153                  If it is an external symbol and we have type information
16154                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16155                  The address of the variable will then be determined from
16156                  the minimal symbol table whenever the variable is
16157                  referenced.  */
16158               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16159
16160               /* Fortran explicitly imports any global symbols to the local
16161                  scope by DW_TAG_common_block.  */
16162               if (cu->language == language_fortran && die->parent
16163                   && die->parent->tag == DW_TAG_common_block)
16164                 {
16165                   /* SYMBOL_CLASS doesn't matter here because
16166                      read_common_block is going to reset it.  */
16167                   if (!suppress_add)
16168                     list_to_add = cu->list_in_scope;
16169                 }
16170               else if (attr2 && (DW_UNSND (attr2) != 0)
16171                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16172                 {
16173                   /* A variable with DW_AT_external is never static, but it
16174                      may be block-scoped.  */
16175                   list_to_add = (cu->list_in_scope == &file_symbols
16176                                  ? &global_symbols : cu->list_in_scope);
16177
16178                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16179                 }
16180               else if (!die_is_declaration (die, cu))
16181                 {
16182                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16183                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16184                   if (!suppress_add)
16185                     list_to_add = cu->list_in_scope;
16186                 }
16187             }
16188           break;
16189         case DW_TAG_formal_parameter:
16190           /* If we are inside a function, mark this as an argument.  If
16191              not, we might be looking at an argument to an inlined function
16192              when we do not have enough information to show inlined frames;
16193              pretend it's a local variable in that case so that the user can
16194              still see it.  */
16195           if (context_stack_depth > 0
16196               && context_stack[context_stack_depth - 1].name != NULL)
16197             SYMBOL_IS_ARGUMENT (sym) = 1;
16198           attr = dwarf2_attr (die, DW_AT_location, cu);
16199           if (attr)
16200             {
16201               var_decode_location (attr, sym, cu);
16202             }
16203           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16204           if (attr)
16205             {
16206               dwarf2_const_value (attr, sym, cu);
16207             }
16208
16209           list_to_add = cu->list_in_scope;
16210           break;
16211         case DW_TAG_unspecified_parameters:
16212           /* From varargs functions; gdb doesn't seem to have any
16213              interest in this information, so just ignore it for now.
16214              (FIXME?) */
16215           break;
16216         case DW_TAG_template_type_param:
16217           suppress_add = 1;
16218           /* Fall through.  */
16219         case DW_TAG_class_type:
16220         case DW_TAG_interface_type:
16221         case DW_TAG_structure_type:
16222         case DW_TAG_union_type:
16223         case DW_TAG_set_type:
16224         case DW_TAG_enumeration_type:
16225           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16226           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16227
16228           {
16229             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16230                really ever be static objects: otherwise, if you try
16231                to, say, break of a class's method and you're in a file
16232                which doesn't mention that class, it won't work unless
16233                the check for all static symbols in lookup_symbol_aux
16234                saves you.  See the OtherFileClass tests in
16235                gdb.c++/namespace.exp.  */
16236
16237             if (!suppress_add)
16238               {
16239                 list_to_add = (cu->list_in_scope == &file_symbols
16240                                && (cu->language == language_cplus
16241                                    || cu->language == language_java)
16242                                ? &global_symbols : cu->list_in_scope);
16243
16244                 /* The semantics of C++ state that "struct foo {
16245                    ... }" also defines a typedef for "foo".  A Java
16246                    class declaration also defines a typedef for the
16247                    class.  */
16248                 if (cu->language == language_cplus
16249                     || cu->language == language_java
16250                     || cu->language == language_ada)
16251                   {
16252                     /* The symbol's name is already allocated along
16253                        with this objfile, so we don't need to
16254                        duplicate it for the type.  */
16255                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16256                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16257                   }
16258               }
16259           }
16260           break;
16261         case DW_TAG_typedef:
16262           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16263           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16264           list_to_add = cu->list_in_scope;
16265           break;
16266         case DW_TAG_base_type:
16267         case DW_TAG_subrange_type:
16268           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16269           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16270           list_to_add = cu->list_in_scope;
16271           break;
16272         case DW_TAG_enumerator:
16273           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16274           if (attr)
16275             {
16276               dwarf2_const_value (attr, sym, cu);
16277             }
16278           {
16279             /* NOTE: carlton/2003-11-10: See comment above in the
16280                DW_TAG_class_type, etc. block.  */
16281
16282             list_to_add = (cu->list_in_scope == &file_symbols
16283                            && (cu->language == language_cplus
16284                                || cu->language == language_java)
16285                            ? &global_symbols : cu->list_in_scope);
16286           }
16287           break;
16288         case DW_TAG_namespace:
16289           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16290           list_to_add = &global_symbols;
16291           break;
16292         case DW_TAG_common_block:
16293           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16294           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16295           add_symbol_to_list (sym, cu->list_in_scope);
16296           break;
16297         default:
16298           /* Not a tag we recognize.  Hopefully we aren't processing
16299              trash data, but since we must specifically ignore things
16300              we don't recognize, there is nothing else we should do at
16301              this point.  */
16302           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16303                      dwarf_tag_name (die->tag));
16304           break;
16305         }
16306
16307       if (suppress_add)
16308         {
16309           sym->hash_next = objfile->template_symbols;
16310           objfile->template_symbols = sym;
16311           list_to_add = NULL;
16312         }
16313
16314       if (list_to_add != NULL)
16315         add_symbol_to_list (sym, list_to_add);
16316
16317       /* For the benefit of old versions of GCC, check for anonymous
16318          namespaces based on the demangled name.  */
16319       if (!cu->processing_has_namespace_info
16320           && cu->language == language_cplus)
16321         cp_scan_for_anonymous_namespaces (sym, objfile);
16322     }
16323   return (sym);
16324 }
16325
16326 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16327
16328 static struct symbol *
16329 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16330 {
16331   return new_symbol_full (die, type, cu, NULL);
16332 }
16333
16334 /* Given an attr with a DW_FORM_dataN value in host byte order,
16335    zero-extend it as appropriate for the symbol's type.  The DWARF
16336    standard (v4) is not entirely clear about the meaning of using
16337    DW_FORM_dataN for a constant with a signed type, where the type is
16338    wider than the data.  The conclusion of a discussion on the DWARF
16339    list was that this is unspecified.  We choose to always zero-extend
16340    because that is the interpretation long in use by GCC.  */
16341
16342 static gdb_byte *
16343 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16344                          const char *name, struct obstack *obstack,
16345                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16346 {
16347   struct objfile *objfile = cu->objfile;
16348   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16349                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16350   LONGEST l = DW_UNSND (attr);
16351
16352   if (bits < sizeof (*value) * 8)
16353     {
16354       l &= ((LONGEST) 1 << bits) - 1;
16355       *value = l;
16356     }
16357   else if (bits == sizeof (*value) * 8)
16358     *value = l;
16359   else
16360     {
16361       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16362       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16363       return bytes;
16364     }
16365
16366   return NULL;
16367 }
16368
16369 /* Read a constant value from an attribute.  Either set *VALUE, or if
16370    the value does not fit in *VALUE, set *BYTES - either already
16371    allocated on the objfile obstack, or newly allocated on OBSTACK,
16372    or, set *BATON, if we translated the constant to a location
16373    expression.  */
16374
16375 static void
16376 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16377                          const char *name, struct obstack *obstack,
16378                          struct dwarf2_cu *cu,
16379                          LONGEST *value, const gdb_byte **bytes,
16380                          struct dwarf2_locexpr_baton **baton)
16381 {
16382   struct objfile *objfile = cu->objfile;
16383   struct comp_unit_head *cu_header = &cu->header;
16384   struct dwarf_block *blk;
16385   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16386                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16387
16388   *value = 0;
16389   *bytes = NULL;
16390   *baton = NULL;
16391
16392   switch (attr->form)
16393     {
16394     case DW_FORM_addr:
16395     case DW_FORM_GNU_addr_index:
16396       {
16397         gdb_byte *data;
16398
16399         if (TYPE_LENGTH (type) != cu_header->addr_size)
16400           dwarf2_const_value_length_mismatch_complaint (name,
16401                                                         cu_header->addr_size,
16402                                                         TYPE_LENGTH (type));
16403         /* Symbols of this form are reasonably rare, so we just
16404            piggyback on the existing location code rather than writing
16405            a new implementation of symbol_computed_ops.  */
16406         *baton = obstack_alloc (&objfile->objfile_obstack,
16407                                 sizeof (struct dwarf2_locexpr_baton));
16408         (*baton)->per_cu = cu->per_cu;
16409         gdb_assert ((*baton)->per_cu);
16410
16411         (*baton)->size = 2 + cu_header->addr_size;
16412         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16413         (*baton)->data = data;
16414
16415         data[0] = DW_OP_addr;
16416         store_unsigned_integer (&data[1], cu_header->addr_size,
16417                                 byte_order, DW_ADDR (attr));
16418         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16419       }
16420       break;
16421     case DW_FORM_string:
16422     case DW_FORM_strp:
16423     case DW_FORM_GNU_str_index:
16424     case DW_FORM_GNU_strp_alt:
16425       /* DW_STRING is already allocated on the objfile obstack, point
16426          directly to it.  */
16427       *bytes = (const gdb_byte *) DW_STRING (attr);
16428       break;
16429     case DW_FORM_block1:
16430     case DW_FORM_block2:
16431     case DW_FORM_block4:
16432     case DW_FORM_block:
16433     case DW_FORM_exprloc:
16434       blk = DW_BLOCK (attr);
16435       if (TYPE_LENGTH (type) != blk->size)
16436         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16437                                                       TYPE_LENGTH (type));
16438       *bytes = blk->data;
16439       break;
16440
16441       /* The DW_AT_const_value attributes are supposed to carry the
16442          symbol's value "represented as it would be on the target
16443          architecture."  By the time we get here, it's already been
16444          converted to host endianness, so we just need to sign- or
16445          zero-extend it as appropriate.  */
16446     case DW_FORM_data1:
16447       *bytes = dwarf2_const_value_data (attr, type, name,
16448                                         obstack, cu, value, 8);
16449       break;
16450     case DW_FORM_data2:
16451       *bytes = dwarf2_const_value_data (attr, type, name,
16452                                         obstack, cu, value, 16);
16453       break;
16454     case DW_FORM_data4:
16455       *bytes = dwarf2_const_value_data (attr, type, name,
16456                                         obstack, cu, value, 32);
16457       break;
16458     case DW_FORM_data8:
16459       *bytes = dwarf2_const_value_data (attr, type, name,
16460                                         obstack, cu, value, 64);
16461       break;
16462
16463     case DW_FORM_sdata:
16464       *value = DW_SND (attr);
16465       break;
16466
16467     case DW_FORM_udata:
16468       *value = DW_UNSND (attr);
16469       break;
16470
16471     default:
16472       complaint (&symfile_complaints,
16473                  _("unsupported const value attribute form: '%s'"),
16474                  dwarf_form_name (attr->form));
16475       *value = 0;
16476       break;
16477     }
16478 }
16479
16480
16481 /* Copy constant value from an attribute to a symbol.  */
16482
16483 static void
16484 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16485                     struct dwarf2_cu *cu)
16486 {
16487   struct objfile *objfile = cu->objfile;
16488   struct comp_unit_head *cu_header = &cu->header;
16489   LONGEST value;
16490   const gdb_byte *bytes;
16491   struct dwarf2_locexpr_baton *baton;
16492
16493   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16494                            SYMBOL_PRINT_NAME (sym),
16495                            &objfile->objfile_obstack, cu,
16496                            &value, &bytes, &baton);
16497
16498   if (baton != NULL)
16499     {
16500       SYMBOL_LOCATION_BATON (sym) = baton;
16501       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16502     }
16503   else if (bytes != NULL)
16504      {
16505       SYMBOL_VALUE_BYTES (sym) = bytes;
16506       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16507     }
16508   else
16509     {
16510       SYMBOL_VALUE (sym) = value;
16511       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16512     }
16513 }
16514
16515 /* Return the type of the die in question using its DW_AT_type attribute.  */
16516
16517 static struct type *
16518 die_type (struct die_info *die, struct dwarf2_cu *cu)
16519 {
16520   struct attribute *type_attr;
16521
16522   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16523   if (!type_attr)
16524     {
16525       /* A missing DW_AT_type represents a void type.  */
16526       return objfile_type (cu->objfile)->builtin_void;
16527     }
16528
16529   return lookup_die_type (die, type_attr, cu);
16530 }
16531
16532 /* True iff CU's producer generates GNAT Ada auxiliary information
16533    that allows to find parallel types through that information instead
16534    of having to do expensive parallel lookups by type name.  */
16535
16536 static int
16537 need_gnat_info (struct dwarf2_cu *cu)
16538 {
16539   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16540      of GNAT produces this auxiliary information, without any indication
16541      that it is produced.  Part of enhancing the FSF version of GNAT
16542      to produce that information will be to put in place an indicator
16543      that we can use in order to determine whether the descriptive type
16544      info is available or not.  One suggestion that has been made is
16545      to use a new attribute, attached to the CU die.  For now, assume
16546      that the descriptive type info is not available.  */
16547   return 0;
16548 }
16549
16550 /* Return the auxiliary type of the die in question using its
16551    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16552    attribute is not present.  */
16553
16554 static struct type *
16555 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16556 {
16557   struct attribute *type_attr;
16558
16559   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16560   if (!type_attr)
16561     return NULL;
16562
16563   return lookup_die_type (die, type_attr, cu);
16564 }
16565
16566 /* If DIE has a descriptive_type attribute, then set the TYPE's
16567    descriptive type accordingly.  */
16568
16569 static void
16570 set_descriptive_type (struct type *type, struct die_info *die,
16571                       struct dwarf2_cu *cu)
16572 {
16573   struct type *descriptive_type = die_descriptive_type (die, cu);
16574
16575   if (descriptive_type)
16576     {
16577       ALLOCATE_GNAT_AUX_TYPE (type);
16578       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16579     }
16580 }
16581
16582 /* Return the containing type of the die in question using its
16583    DW_AT_containing_type attribute.  */
16584
16585 static struct type *
16586 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16587 {
16588   struct attribute *type_attr;
16589
16590   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16591   if (!type_attr)
16592     error (_("Dwarf Error: Problem turning containing type into gdb type "
16593              "[in module %s]"), cu->objfile->name);
16594
16595   return lookup_die_type (die, type_attr, cu);
16596 }
16597
16598 /* Look up the type of DIE in CU using its type attribute ATTR.
16599    If there is no type substitute an error marker.  */
16600
16601 static struct type *
16602 lookup_die_type (struct die_info *die, struct attribute *attr,
16603                  struct dwarf2_cu *cu)
16604 {
16605   struct objfile *objfile = cu->objfile;
16606   struct type *this_type;
16607
16608   /* First see if we have it cached.  */
16609
16610   if (attr->form == DW_FORM_GNU_ref_alt)
16611     {
16612       struct dwarf2_per_cu_data *per_cu;
16613       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16614
16615       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16616       this_type = get_die_type_at_offset (offset, per_cu);
16617     }
16618   else if (is_ref_attr (attr))
16619     {
16620       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16621
16622       this_type = get_die_type_at_offset (offset, cu->per_cu);
16623     }
16624   else if (attr->form == DW_FORM_ref_sig8)
16625     {
16626       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16627
16628       /* sig_type will be NULL if the signatured type is missing from
16629          the debug info.  */
16630       if (sig_type == NULL)
16631         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16632                  "at 0x%x [in module %s]"),
16633                die->offset.sect_off, objfile->name);
16634
16635       gdb_assert (sig_type->per_cu.is_debug_types);
16636       /* If we haven't filled in type_offset_in_section yet, then we
16637          haven't read the type in yet.  */
16638       this_type = NULL;
16639       if (sig_type->type_offset_in_section.sect_off != 0)
16640         {
16641           this_type =
16642             get_die_type_at_offset (sig_type->type_offset_in_section,
16643                                     &sig_type->per_cu);
16644         }
16645     }
16646   else
16647     {
16648       dump_die_for_error (die);
16649       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16650              dwarf_attr_name (attr->name), objfile->name);
16651     }
16652
16653   /* If not cached we need to read it in.  */
16654
16655   if (this_type == NULL)
16656     {
16657       struct die_info *type_die;
16658       struct dwarf2_cu *type_cu = cu;
16659
16660       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16661       /* If we found the type now, it's probably because the type came
16662          from an inter-CU reference and the type's CU got expanded before
16663          ours.  */
16664       this_type = get_die_type (type_die, type_cu);
16665       if (this_type == NULL)
16666         this_type = read_type_die_1 (type_die, type_cu);
16667     }
16668
16669   /* If we still don't have a type use an error marker.  */
16670
16671   if (this_type == NULL)
16672     {
16673       char *message, *saved;
16674
16675       /* read_type_die already issued a complaint.  */
16676       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16677                             objfile->name,
16678                             cu->header.offset.sect_off,
16679                             die->offset.sect_off);
16680       saved = obstack_copy0 (&objfile->objfile_obstack,
16681                              message, strlen (message));
16682       xfree (message);
16683
16684       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16685     }
16686
16687   return this_type;
16688 }
16689
16690 /* Return the type in DIE, CU.
16691    Returns NULL for invalid types.
16692
16693    This first does a lookup in die_type_hash,
16694    and only reads the die in if necessary.
16695
16696    NOTE: This can be called when reading in partial or full symbols.  */
16697
16698 static struct type *
16699 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16700 {
16701   struct type *this_type;
16702
16703   this_type = get_die_type (die, cu);
16704   if (this_type)
16705     return this_type;
16706
16707   return read_type_die_1 (die, cu);
16708 }
16709
16710 /* Read the type in DIE, CU.
16711    Returns NULL for invalid types.  */
16712
16713 static struct type *
16714 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16715 {
16716   struct type *this_type = NULL;
16717
16718   switch (die->tag)
16719     {
16720     case DW_TAG_class_type:
16721     case DW_TAG_interface_type:
16722     case DW_TAG_structure_type:
16723     case DW_TAG_union_type:
16724       this_type = read_structure_type (die, cu);
16725       break;
16726     case DW_TAG_enumeration_type:
16727       this_type = read_enumeration_type (die, cu);
16728       break;
16729     case DW_TAG_subprogram:
16730     case DW_TAG_subroutine_type:
16731     case DW_TAG_inlined_subroutine:
16732       this_type = read_subroutine_type (die, cu);
16733       break;
16734     case DW_TAG_array_type:
16735       this_type = read_array_type (die, cu);
16736       break;
16737     case DW_TAG_set_type:
16738       this_type = read_set_type (die, cu);
16739       break;
16740     case DW_TAG_pointer_type:
16741       this_type = read_tag_pointer_type (die, cu);
16742       break;
16743     case DW_TAG_ptr_to_member_type:
16744       this_type = read_tag_ptr_to_member_type (die, cu);
16745       break;
16746     case DW_TAG_reference_type:
16747       this_type = read_tag_reference_type (die, cu);
16748       break;
16749     case DW_TAG_const_type:
16750       this_type = read_tag_const_type (die, cu);
16751       break;
16752     case DW_TAG_volatile_type:
16753       this_type = read_tag_volatile_type (die, cu);
16754       break;
16755     case DW_TAG_restrict_type:
16756       this_type = read_tag_restrict_type (die, cu);
16757       break;
16758     case DW_TAG_string_type:
16759       this_type = read_tag_string_type (die, cu);
16760       break;
16761     case DW_TAG_typedef:
16762       this_type = read_typedef (die, cu);
16763       break;
16764     case DW_TAG_subrange_type:
16765       this_type = read_subrange_type (die, cu);
16766       break;
16767     case DW_TAG_base_type:
16768       this_type = read_base_type (die, cu);
16769       break;
16770     case DW_TAG_unspecified_type:
16771       this_type = read_unspecified_type (die, cu);
16772       break;
16773     case DW_TAG_namespace:
16774       this_type = read_namespace_type (die, cu);
16775       break;
16776     case DW_TAG_module:
16777       this_type = read_module_type (die, cu);
16778       break;
16779     default:
16780       complaint (&symfile_complaints,
16781                  _("unexpected tag in read_type_die: '%s'"),
16782                  dwarf_tag_name (die->tag));
16783       break;
16784     }
16785
16786   return this_type;
16787 }
16788
16789 /* See if we can figure out if the class lives in a namespace.  We do
16790    this by looking for a member function; its demangled name will
16791    contain namespace info, if there is any.
16792    Return the computed name or NULL.
16793    Space for the result is allocated on the objfile's obstack.
16794    This is the full-die version of guess_partial_die_structure_name.
16795    In this case we know DIE has no useful parent.  */
16796
16797 static char *
16798 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16799 {
16800   struct die_info *spec_die;
16801   struct dwarf2_cu *spec_cu;
16802   struct die_info *child;
16803
16804   spec_cu = cu;
16805   spec_die = die_specification (die, &spec_cu);
16806   if (spec_die != NULL)
16807     {
16808       die = spec_die;
16809       cu = spec_cu;
16810     }
16811
16812   for (child = die->child;
16813        child != NULL;
16814        child = child->sibling)
16815     {
16816       if (child->tag == DW_TAG_subprogram)
16817         {
16818           struct attribute *attr;
16819
16820           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16821           if (attr == NULL)
16822             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16823           if (attr != NULL)
16824             {
16825               char *actual_name
16826                 = language_class_name_from_physname (cu->language_defn,
16827                                                      DW_STRING (attr));
16828               char *name = NULL;
16829
16830               if (actual_name != NULL)
16831                 {
16832                   const char *die_name = dwarf2_name (die, cu);
16833
16834                   if (die_name != NULL
16835                       && strcmp (die_name, actual_name) != 0)
16836                     {
16837                       /* Strip off the class name from the full name.
16838                          We want the prefix.  */
16839                       int die_name_len = strlen (die_name);
16840                       int actual_name_len = strlen (actual_name);
16841
16842                       /* Test for '::' as a sanity check.  */
16843                       if (actual_name_len > die_name_len + 2
16844                           && actual_name[actual_name_len
16845                                          - die_name_len - 1] == ':')
16846                         name =
16847                           obstack_copy0 (&cu->objfile->objfile_obstack,
16848                                          actual_name,
16849                                          actual_name_len - die_name_len - 2);
16850                     }
16851                 }
16852               xfree (actual_name);
16853               return name;
16854             }
16855         }
16856     }
16857
16858   return NULL;
16859 }
16860
16861 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16862    prefix part in such case.  See
16863    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16864
16865 static char *
16866 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16867 {
16868   struct attribute *attr;
16869   char *base;
16870
16871   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16872       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16873     return NULL;
16874
16875   attr = dwarf2_attr (die, DW_AT_name, cu);
16876   if (attr != NULL && DW_STRING (attr) != NULL)
16877     return NULL;
16878
16879   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16880   if (attr == NULL)
16881     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16882   if (attr == NULL || DW_STRING (attr) == NULL)
16883     return NULL;
16884
16885   /* dwarf2_name had to be already called.  */
16886   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16887
16888   /* Strip the base name, keep any leading namespaces/classes.  */
16889   base = strrchr (DW_STRING (attr), ':');
16890   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16891     return "";
16892
16893   return obstack_copy0 (&cu->objfile->objfile_obstack,
16894                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16895 }
16896
16897 /* Return the name of the namespace/class that DIE is defined within,
16898    or "" if we can't tell.  The caller should not xfree the result.
16899
16900    For example, if we're within the method foo() in the following
16901    code:
16902
16903    namespace N {
16904      class C {
16905        void foo () {
16906        }
16907      };
16908    }
16909
16910    then determine_prefix on foo's die will return "N::C".  */
16911
16912 static const char *
16913 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16914 {
16915   struct die_info *parent, *spec_die;
16916   struct dwarf2_cu *spec_cu;
16917   struct type *parent_type;
16918   char *retval;
16919
16920   if (cu->language != language_cplus && cu->language != language_java
16921       && cu->language != language_fortran)
16922     return "";
16923
16924   retval = anonymous_struct_prefix (die, cu);
16925   if (retval)
16926     return retval;
16927
16928   /* We have to be careful in the presence of DW_AT_specification.
16929      For example, with GCC 3.4, given the code
16930
16931      namespace N {
16932        void foo() {
16933          // Definition of N::foo.
16934        }
16935      }
16936
16937      then we'll have a tree of DIEs like this:
16938
16939      1: DW_TAG_compile_unit
16940        2: DW_TAG_namespace        // N
16941          3: DW_TAG_subprogram     // declaration of N::foo
16942        4: DW_TAG_subprogram       // definition of N::foo
16943             DW_AT_specification   // refers to die #3
16944
16945      Thus, when processing die #4, we have to pretend that we're in
16946      the context of its DW_AT_specification, namely the contex of die
16947      #3.  */
16948   spec_cu = cu;
16949   spec_die = die_specification (die, &spec_cu);
16950   if (spec_die == NULL)
16951     parent = die->parent;
16952   else
16953     {
16954       parent = spec_die->parent;
16955       cu = spec_cu;
16956     }
16957
16958   if (parent == NULL)
16959     return "";
16960   else if (parent->building_fullname)
16961     {
16962       const char *name;
16963       const char *parent_name;
16964
16965       /* It has been seen on RealView 2.2 built binaries,
16966          DW_TAG_template_type_param types actually _defined_ as
16967          children of the parent class:
16968
16969          enum E {};
16970          template class <class Enum> Class{};
16971          Class<enum E> class_e;
16972
16973          1: DW_TAG_class_type (Class)
16974            2: DW_TAG_enumeration_type (E)
16975              3: DW_TAG_enumerator (enum1:0)
16976              3: DW_TAG_enumerator (enum2:1)
16977              ...
16978            2: DW_TAG_template_type_param
16979               DW_AT_type  DW_FORM_ref_udata (E)
16980
16981          Besides being broken debug info, it can put GDB into an
16982          infinite loop.  Consider:
16983
16984          When we're building the full name for Class<E>, we'll start
16985          at Class, and go look over its template type parameters,
16986          finding E.  We'll then try to build the full name of E, and
16987          reach here.  We're now trying to build the full name of E,
16988          and look over the parent DIE for containing scope.  In the
16989          broken case, if we followed the parent DIE of E, we'd again
16990          find Class, and once again go look at its template type
16991          arguments, etc., etc.  Simply don't consider such parent die
16992          as source-level parent of this die (it can't be, the language
16993          doesn't allow it), and break the loop here.  */
16994       name = dwarf2_name (die, cu);
16995       parent_name = dwarf2_name (parent, cu);
16996       complaint (&symfile_complaints,
16997                  _("template param type '%s' defined within parent '%s'"),
16998                  name ? name : "<unknown>",
16999                  parent_name ? parent_name : "<unknown>");
17000       return "";
17001     }
17002   else
17003     switch (parent->tag)
17004       {
17005       case DW_TAG_namespace:
17006         parent_type = read_type_die (parent, cu);
17007         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17008            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17009            Work around this problem here.  */
17010         if (cu->language == language_cplus
17011             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17012           return "";
17013         /* We give a name to even anonymous namespaces.  */
17014         return TYPE_TAG_NAME (parent_type);
17015       case DW_TAG_class_type:
17016       case DW_TAG_interface_type:
17017       case DW_TAG_structure_type:
17018       case DW_TAG_union_type:
17019       case DW_TAG_module:
17020         parent_type = read_type_die (parent, cu);
17021         if (TYPE_TAG_NAME (parent_type) != NULL)
17022           return TYPE_TAG_NAME (parent_type);
17023         else
17024           /* An anonymous structure is only allowed non-static data
17025              members; no typedefs, no member functions, et cetera.
17026              So it does not need a prefix.  */
17027           return "";
17028       case DW_TAG_compile_unit:
17029       case DW_TAG_partial_unit:
17030         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17031         if (cu->language == language_cplus
17032             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17033             && die->child != NULL
17034             && (die->tag == DW_TAG_class_type
17035                 || die->tag == DW_TAG_structure_type
17036                 || die->tag == DW_TAG_union_type))
17037           {
17038             char *name = guess_full_die_structure_name (die, cu);
17039             if (name != NULL)
17040               return name;
17041           }
17042         return "";
17043       default:
17044         return determine_prefix (parent, cu);
17045       }
17046 }
17047
17048 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17049    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17050    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17051    an obconcat, otherwise allocate storage for the result.  The CU argument is
17052    used to determine the language and hence, the appropriate separator.  */
17053
17054 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17055
17056 static char *
17057 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17058                  int physname, struct dwarf2_cu *cu)
17059 {
17060   const char *lead = "";
17061   const char *sep;
17062
17063   if (suffix == NULL || suffix[0] == '\0'
17064       || prefix == NULL || prefix[0] == '\0')
17065     sep = "";
17066   else if (cu->language == language_java)
17067     sep = ".";
17068   else if (cu->language == language_fortran && physname)
17069     {
17070       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17071          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17072
17073       lead = "__";
17074       sep = "_MOD_";
17075     }
17076   else
17077     sep = "::";
17078
17079   if (prefix == NULL)
17080     prefix = "";
17081   if (suffix == NULL)
17082     suffix = "";
17083
17084   if (obs == NULL)
17085     {
17086       char *retval
17087         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17088
17089       strcpy (retval, lead);
17090       strcat (retval, prefix);
17091       strcat (retval, sep);
17092       strcat (retval, suffix);
17093       return retval;
17094     }
17095   else
17096     {
17097       /* We have an obstack.  */
17098       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17099     }
17100 }
17101
17102 /* Return sibling of die, NULL if no sibling.  */
17103
17104 static struct die_info *
17105 sibling_die (struct die_info *die)
17106 {
17107   return die->sibling;
17108 }
17109
17110 /* Get name of a die, return NULL if not found.  */
17111
17112 static const char *
17113 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17114                           struct obstack *obstack)
17115 {
17116   if (name && cu->language == language_cplus)
17117     {
17118       char *canon_name = cp_canonicalize_string (name);
17119
17120       if (canon_name != NULL)
17121         {
17122           if (strcmp (canon_name, name) != 0)
17123             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17124           xfree (canon_name);
17125         }
17126     }
17127
17128   return name;
17129 }
17130
17131 /* Get name of a die, return NULL if not found.  */
17132
17133 static const char *
17134 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17135 {
17136   struct attribute *attr;
17137
17138   attr = dwarf2_attr (die, DW_AT_name, cu);
17139   if ((!attr || !DW_STRING (attr))
17140       && die->tag != DW_TAG_class_type
17141       && die->tag != DW_TAG_interface_type
17142       && die->tag != DW_TAG_structure_type
17143       && die->tag != DW_TAG_union_type)
17144     return NULL;
17145
17146   switch (die->tag)
17147     {
17148     case DW_TAG_compile_unit:
17149     case DW_TAG_partial_unit:
17150       /* Compilation units have a DW_AT_name that is a filename, not
17151          a source language identifier.  */
17152     case DW_TAG_enumeration_type:
17153     case DW_TAG_enumerator:
17154       /* These tags always have simple identifiers already; no need
17155          to canonicalize them.  */
17156       return DW_STRING (attr);
17157
17158     case DW_TAG_subprogram:
17159       /* Java constructors will all be named "<init>", so return
17160          the class name when we see this special case.  */
17161       if (cu->language == language_java
17162           && DW_STRING (attr) != NULL
17163           && strcmp (DW_STRING (attr), "<init>") == 0)
17164         {
17165           struct dwarf2_cu *spec_cu = cu;
17166           struct die_info *spec_die;
17167
17168           /* GCJ will output '<init>' for Java constructor names.
17169              For this special case, return the name of the parent class.  */
17170
17171           /* GCJ may output suprogram DIEs with AT_specification set.
17172              If so, use the name of the specified DIE.  */
17173           spec_die = die_specification (die, &spec_cu);
17174           if (spec_die != NULL)
17175             return dwarf2_name (spec_die, spec_cu);
17176
17177           do
17178             {
17179               die = die->parent;
17180               if (die->tag == DW_TAG_class_type)
17181                 return dwarf2_name (die, cu);
17182             }
17183           while (die->tag != DW_TAG_compile_unit
17184                  && die->tag != DW_TAG_partial_unit);
17185         }
17186       break;
17187
17188     case DW_TAG_class_type:
17189     case DW_TAG_interface_type:
17190     case DW_TAG_structure_type:
17191     case DW_TAG_union_type:
17192       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17193          structures or unions.  These were of the form "._%d" in GCC 4.1,
17194          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17195          and GCC 4.4.  We work around this problem by ignoring these.  */
17196       if (attr && DW_STRING (attr)
17197           && (strncmp (DW_STRING (attr), "._", 2) == 0
17198               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17199         return NULL;
17200
17201       /* GCC might emit a nameless typedef that has a linkage name.  See
17202          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17203       if (!attr || DW_STRING (attr) == NULL)
17204         {
17205           char *demangled = NULL;
17206
17207           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17208           if (attr == NULL)
17209             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17210
17211           if (attr == NULL || DW_STRING (attr) == NULL)
17212             return NULL;
17213
17214           /* Avoid demangling DW_STRING (attr) the second time on a second
17215              call for the same DIE.  */
17216           if (!DW_STRING_IS_CANONICAL (attr))
17217             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17218
17219           if (demangled)
17220             {
17221               char *base;
17222
17223               /* FIXME: we already did this for the partial symbol... */
17224               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17225                                                 demangled, strlen (demangled));
17226               DW_STRING_IS_CANONICAL (attr) = 1;
17227               xfree (demangled);
17228
17229               /* Strip any leading namespaces/classes, keep only the base name.
17230                  DW_AT_name for named DIEs does not contain the prefixes.  */
17231               base = strrchr (DW_STRING (attr), ':');
17232               if (base && base > DW_STRING (attr) && base[-1] == ':')
17233                 return &base[1];
17234               else
17235                 return DW_STRING (attr);
17236             }
17237         }
17238       break;
17239
17240     default:
17241       break;
17242     }
17243
17244   if (!DW_STRING_IS_CANONICAL (attr))
17245     {
17246       DW_STRING (attr)
17247         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17248                                     &cu->objfile->objfile_obstack);
17249       DW_STRING_IS_CANONICAL (attr) = 1;
17250     }
17251   return DW_STRING (attr);
17252 }
17253
17254 /* Return the die that this die in an extension of, or NULL if there
17255    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17256    containing the return value on output.  */
17257
17258 static struct die_info *
17259 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17260 {
17261   struct attribute *attr;
17262
17263   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17264   if (attr == NULL)
17265     return NULL;
17266
17267   return follow_die_ref (die, attr, ext_cu);
17268 }
17269
17270 /* Convert a DIE tag into its string name.  */
17271
17272 static const char *
17273 dwarf_tag_name (unsigned tag)
17274 {
17275   const char *name = get_DW_TAG_name (tag);
17276
17277   if (name == NULL)
17278     return "DW_TAG_<unknown>";
17279
17280   return name;
17281 }
17282
17283 /* Convert a DWARF attribute code into its string name.  */
17284
17285 static const char *
17286 dwarf_attr_name (unsigned attr)
17287 {
17288   const char *name;
17289
17290 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17291   if (attr == DW_AT_MIPS_fde)
17292     return "DW_AT_MIPS_fde";
17293 #else
17294   if (attr == DW_AT_HP_block_index)
17295     return "DW_AT_HP_block_index";
17296 #endif
17297
17298   name = get_DW_AT_name (attr);
17299
17300   if (name == NULL)
17301     return "DW_AT_<unknown>";
17302
17303   return name;
17304 }
17305
17306 /* Convert a DWARF value form code into its string name.  */
17307
17308 static const char *
17309 dwarf_form_name (unsigned form)
17310 {
17311   const char *name = get_DW_FORM_name (form);
17312
17313   if (name == NULL)
17314     return "DW_FORM_<unknown>";
17315
17316   return name;
17317 }
17318
17319 static char *
17320 dwarf_bool_name (unsigned mybool)
17321 {
17322   if (mybool)
17323     return "TRUE";
17324   else
17325     return "FALSE";
17326 }
17327
17328 /* Convert a DWARF type code into its string name.  */
17329
17330 static const char *
17331 dwarf_type_encoding_name (unsigned enc)
17332 {
17333   const char *name = get_DW_ATE_name (enc);
17334
17335   if (name == NULL)
17336     return "DW_ATE_<unknown>";
17337
17338   return name;
17339 }
17340
17341 static void
17342 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17343 {
17344   unsigned int i;
17345
17346   print_spaces (indent, f);
17347   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17348            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17349
17350   if (die->parent != NULL)
17351     {
17352       print_spaces (indent, f);
17353       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17354                           die->parent->offset.sect_off);
17355     }
17356
17357   print_spaces (indent, f);
17358   fprintf_unfiltered (f, "  has children: %s\n",
17359            dwarf_bool_name (die->child != NULL));
17360
17361   print_spaces (indent, f);
17362   fprintf_unfiltered (f, "  attributes:\n");
17363
17364   for (i = 0; i < die->num_attrs; ++i)
17365     {
17366       print_spaces (indent, f);
17367       fprintf_unfiltered (f, "    %s (%s) ",
17368                dwarf_attr_name (die->attrs[i].name),
17369                dwarf_form_name (die->attrs[i].form));
17370
17371       switch (die->attrs[i].form)
17372         {
17373         case DW_FORM_addr:
17374         case DW_FORM_GNU_addr_index:
17375           fprintf_unfiltered (f, "address: ");
17376           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17377           break;
17378         case DW_FORM_block2:
17379         case DW_FORM_block4:
17380         case DW_FORM_block:
17381         case DW_FORM_block1:
17382           fprintf_unfiltered (f, "block: size %s",
17383                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17384           break;
17385         case DW_FORM_exprloc:
17386           fprintf_unfiltered (f, "expression: size %s",
17387                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17388           break;
17389         case DW_FORM_ref_addr:
17390           fprintf_unfiltered (f, "ref address: ");
17391           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17392           break;
17393         case DW_FORM_GNU_ref_alt:
17394           fprintf_unfiltered (f, "alt ref address: ");
17395           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17396           break;
17397         case DW_FORM_ref1:
17398         case DW_FORM_ref2:
17399         case DW_FORM_ref4:
17400         case DW_FORM_ref8:
17401         case DW_FORM_ref_udata:
17402           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17403                               (long) (DW_UNSND (&die->attrs[i])));
17404           break;
17405         case DW_FORM_data1:
17406         case DW_FORM_data2:
17407         case DW_FORM_data4:
17408         case DW_FORM_data8:
17409         case DW_FORM_udata:
17410         case DW_FORM_sdata:
17411           fprintf_unfiltered (f, "constant: %s",
17412                               pulongest (DW_UNSND (&die->attrs[i])));
17413           break;
17414         case DW_FORM_sec_offset:
17415           fprintf_unfiltered (f, "section offset: %s",
17416                               pulongest (DW_UNSND (&die->attrs[i])));
17417           break;
17418         case DW_FORM_ref_sig8:
17419           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17420             {
17421               struct signatured_type *sig_type =
17422                 DW_SIGNATURED_TYPE (&die->attrs[i]);
17423
17424               fprintf_unfiltered (f, "signatured type: 0x%s, offset 0x%x",
17425                                   hex_string (sig_type->signature),
17426                                   sig_type->per_cu.offset.sect_off);
17427             }
17428           else
17429             fprintf_unfiltered (f, "signatured type, unknown");
17430           break;
17431         case DW_FORM_string:
17432         case DW_FORM_strp:
17433         case DW_FORM_GNU_str_index:
17434         case DW_FORM_GNU_strp_alt:
17435           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17436                    DW_STRING (&die->attrs[i])
17437                    ? DW_STRING (&die->attrs[i]) : "",
17438                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17439           break;
17440         case DW_FORM_flag:
17441           if (DW_UNSND (&die->attrs[i]))
17442             fprintf_unfiltered (f, "flag: TRUE");
17443           else
17444             fprintf_unfiltered (f, "flag: FALSE");
17445           break;
17446         case DW_FORM_flag_present:
17447           fprintf_unfiltered (f, "flag: TRUE");
17448           break;
17449         case DW_FORM_indirect:
17450           /* The reader will have reduced the indirect form to
17451              the "base form" so this form should not occur.  */
17452           fprintf_unfiltered (f, 
17453                               "unexpected attribute form: DW_FORM_indirect");
17454           break;
17455         default:
17456           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17457                    die->attrs[i].form);
17458           break;
17459         }
17460       fprintf_unfiltered (f, "\n");
17461     }
17462 }
17463
17464 static void
17465 dump_die_for_error (struct die_info *die)
17466 {
17467   dump_die_shallow (gdb_stderr, 0, die);
17468 }
17469
17470 static void
17471 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17472 {
17473   int indent = level * 4;
17474
17475   gdb_assert (die != NULL);
17476
17477   if (level >= max_level)
17478     return;
17479
17480   dump_die_shallow (f, indent, die);
17481
17482   if (die->child != NULL)
17483     {
17484       print_spaces (indent, f);
17485       fprintf_unfiltered (f, "  Children:");
17486       if (level + 1 < max_level)
17487         {
17488           fprintf_unfiltered (f, "\n");
17489           dump_die_1 (f, level + 1, max_level, die->child);
17490         }
17491       else
17492         {
17493           fprintf_unfiltered (f,
17494                               " [not printed, max nesting level reached]\n");
17495         }
17496     }
17497
17498   if (die->sibling != NULL && level > 0)
17499     {
17500       dump_die_1 (f, level, max_level, die->sibling);
17501     }
17502 }
17503
17504 /* This is called from the pdie macro in gdbinit.in.
17505    It's not static so gcc will keep a copy callable from gdb.  */
17506
17507 void
17508 dump_die (struct die_info *die, int max_level)
17509 {
17510   dump_die_1 (gdb_stdlog, 0, max_level, die);
17511 }
17512
17513 static void
17514 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17515 {
17516   void **slot;
17517
17518   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17519                                    INSERT);
17520
17521   *slot = die;
17522 }
17523
17524 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17525    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17526
17527 static int
17528 is_ref_attr (struct attribute *attr)
17529 {
17530   switch (attr->form)
17531     {
17532     case DW_FORM_ref_addr:
17533     case DW_FORM_ref1:
17534     case DW_FORM_ref2:
17535     case DW_FORM_ref4:
17536     case DW_FORM_ref8:
17537     case DW_FORM_ref_udata:
17538     case DW_FORM_GNU_ref_alt:
17539       return 1;
17540     default:
17541       return 0;
17542     }
17543 }
17544
17545 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17546    required kind.  */
17547
17548 static sect_offset
17549 dwarf2_get_ref_die_offset (struct attribute *attr)
17550 {
17551   sect_offset retval = { DW_UNSND (attr) };
17552
17553   if (is_ref_attr (attr))
17554     return retval;
17555
17556   retval.sect_off = 0;
17557   complaint (&symfile_complaints,
17558              _("unsupported die ref attribute form: '%s'"),
17559              dwarf_form_name (attr->form));
17560   return retval;
17561 }
17562
17563 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17564  * the value held by the attribute is not constant.  */
17565
17566 static LONGEST
17567 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17568 {
17569   if (attr->form == DW_FORM_sdata)
17570     return DW_SND (attr);
17571   else if (attr->form == DW_FORM_udata
17572            || attr->form == DW_FORM_data1
17573            || attr->form == DW_FORM_data2
17574            || attr->form == DW_FORM_data4
17575            || attr->form == DW_FORM_data8)
17576     return DW_UNSND (attr);
17577   else
17578     {
17579       complaint (&symfile_complaints,
17580                  _("Attribute value is not a constant (%s)"),
17581                  dwarf_form_name (attr->form));
17582       return default_value;
17583     }
17584 }
17585
17586 /* Follow reference or signature attribute ATTR of SRC_DIE.
17587    On entry *REF_CU is the CU of SRC_DIE.
17588    On exit *REF_CU is the CU of the result.  */
17589
17590 static struct die_info *
17591 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17592                        struct dwarf2_cu **ref_cu)
17593 {
17594   struct die_info *die;
17595
17596   if (is_ref_attr (attr))
17597     die = follow_die_ref (src_die, attr, ref_cu);
17598   else if (attr->form == DW_FORM_ref_sig8)
17599     die = follow_die_sig (src_die, attr, ref_cu);
17600   else
17601     {
17602       dump_die_for_error (src_die);
17603       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17604              (*ref_cu)->objfile->name);
17605     }
17606
17607   return die;
17608 }
17609
17610 /* Follow reference OFFSET.
17611    On entry *REF_CU is the CU of the source die referencing OFFSET.
17612    On exit *REF_CU is the CU of the result.
17613    Returns NULL if OFFSET is invalid.  */
17614
17615 static struct die_info *
17616 follow_die_offset (sect_offset offset, int offset_in_dwz,
17617                    struct dwarf2_cu **ref_cu)
17618 {
17619   struct die_info temp_die;
17620   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17621
17622   gdb_assert (cu->per_cu != NULL);
17623
17624   target_cu = cu;
17625
17626   if (cu->per_cu->is_debug_types)
17627     {
17628       /* .debug_types CUs cannot reference anything outside their CU.
17629          If they need to, they have to reference a signatured type via
17630          DW_FORM_ref_sig8.  */
17631       if (! offset_in_cu_p (&cu->header, offset))
17632         return NULL;
17633     }
17634   else if (offset_in_dwz != cu->per_cu->is_dwz
17635            || ! offset_in_cu_p (&cu->header, offset))
17636     {
17637       struct dwarf2_per_cu_data *per_cu;
17638
17639       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17640                                                  cu->objfile);
17641
17642       /* If necessary, add it to the queue and load its DIEs.  */
17643       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17644         load_full_comp_unit (per_cu, cu->language);
17645
17646       target_cu = per_cu->cu;
17647     }
17648   else if (cu->dies == NULL)
17649     {
17650       /* We're loading full DIEs during partial symbol reading.  */
17651       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17652       load_full_comp_unit (cu->per_cu, language_minimal);
17653     }
17654
17655   *ref_cu = target_cu;
17656   temp_die.offset = offset;
17657   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17658 }
17659
17660 /* Follow reference attribute ATTR of SRC_DIE.
17661    On entry *REF_CU is the CU of SRC_DIE.
17662    On exit *REF_CU is the CU of the result.  */
17663
17664 static struct die_info *
17665 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17666                 struct dwarf2_cu **ref_cu)
17667 {
17668   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17669   struct dwarf2_cu *cu = *ref_cu;
17670   struct die_info *die;
17671
17672   die = follow_die_offset (offset,
17673                            (attr->form == DW_FORM_GNU_ref_alt
17674                             || cu->per_cu->is_dwz),
17675                            ref_cu);
17676   if (!die)
17677     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17678            "at 0x%x [in module %s]"),
17679            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17680
17681   return die;
17682 }
17683
17684 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17685    Returned value is intended for DW_OP_call*.  Returned
17686    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17687
17688 struct dwarf2_locexpr_baton
17689 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17690                                struct dwarf2_per_cu_data *per_cu,
17691                                CORE_ADDR (*get_frame_pc) (void *baton),
17692                                void *baton)
17693 {
17694   struct dwarf2_cu *cu;
17695   struct die_info *die;
17696   struct attribute *attr;
17697   struct dwarf2_locexpr_baton retval;
17698
17699   dw2_setup (per_cu->objfile);
17700
17701   if (per_cu->cu == NULL)
17702     load_cu (per_cu);
17703   cu = per_cu->cu;
17704
17705   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17706   if (!die)
17707     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17708            offset.sect_off, per_cu->objfile->name);
17709
17710   attr = dwarf2_attr (die, DW_AT_location, cu);
17711   if (!attr)
17712     {
17713       /* DWARF: "If there is no such attribute, then there is no effect.".
17714          DATA is ignored if SIZE is 0.  */
17715
17716       retval.data = NULL;
17717       retval.size = 0;
17718     }
17719   else if (attr_form_is_section_offset (attr))
17720     {
17721       struct dwarf2_loclist_baton loclist_baton;
17722       CORE_ADDR pc = (*get_frame_pc) (baton);
17723       size_t size;
17724
17725       fill_in_loclist_baton (cu, &loclist_baton, attr);
17726
17727       retval.data = dwarf2_find_location_expression (&loclist_baton,
17728                                                      &size, pc);
17729       retval.size = size;
17730     }
17731   else
17732     {
17733       if (!attr_form_is_block (attr))
17734         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17735                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17736                offset.sect_off, per_cu->objfile->name);
17737
17738       retval.data = DW_BLOCK (attr)->data;
17739       retval.size = DW_BLOCK (attr)->size;
17740     }
17741   retval.per_cu = cu->per_cu;
17742
17743   age_cached_comp_units ();
17744
17745   return retval;
17746 }
17747
17748 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17749    offset.  */
17750
17751 struct dwarf2_locexpr_baton
17752 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17753                              struct dwarf2_per_cu_data *per_cu,
17754                              CORE_ADDR (*get_frame_pc) (void *baton),
17755                              void *baton)
17756 {
17757   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17758
17759   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17760 }
17761
17762 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17763    PER_CU.  */
17764
17765 struct type *
17766 dwarf2_get_die_type (cu_offset die_offset,
17767                      struct dwarf2_per_cu_data *per_cu)
17768 {
17769   sect_offset die_offset_sect;
17770
17771   dw2_setup (per_cu->objfile);
17772
17773   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17774   return get_die_type_at_offset (die_offset_sect, per_cu);
17775 }
17776
17777 /* Follow the signature attribute ATTR in SRC_DIE.
17778    On entry *REF_CU is the CU of SRC_DIE.
17779    On exit *REF_CU is the CU of the result.  */
17780
17781 static struct die_info *
17782 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17783                 struct dwarf2_cu **ref_cu)
17784 {
17785   struct objfile *objfile = (*ref_cu)->objfile;
17786   struct die_info temp_die;
17787   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17788   struct dwarf2_cu *sig_cu;
17789   struct die_info *die;
17790
17791   /* sig_type will be NULL if the signatured type is missing from
17792      the debug info.  */
17793   if (sig_type == NULL)
17794     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17795              "at 0x%x [in module %s]"),
17796            src_die->offset.sect_off, objfile->name);
17797
17798   /* If necessary, add it to the queue and load its DIEs.  */
17799
17800   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17801     read_signatured_type (sig_type);
17802
17803   gdb_assert (sig_type->per_cu.cu != NULL);
17804
17805   sig_cu = sig_type->per_cu.cu;
17806   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17807   temp_die.offset = sig_type->type_offset_in_section;
17808   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17809                              temp_die.offset.sect_off);
17810   if (die)
17811     {
17812       /* For .gdb_index version 7 keep track of included TUs.
17813          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17814       if (dwarf2_per_objfile->index_table != NULL
17815           && dwarf2_per_objfile->index_table->version <= 7)
17816         {
17817           VEC_safe_push (dwarf2_per_cu_ptr,
17818                          (*ref_cu)->per_cu->imported_symtabs,
17819                          sig_cu->per_cu);
17820         }
17821
17822       *ref_cu = sig_cu;
17823       return die;
17824     }
17825
17826   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17827          "from DIE at 0x%x [in module %s]"),
17828          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17829 }
17830
17831 /* Load the DIEs associated with type unit PER_CU into memory.  */
17832
17833 static void
17834 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17835 {
17836   struct signatured_type *sig_type;
17837
17838   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17839   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17840
17841   /* We have the per_cu, but we need the signatured_type.
17842      Fortunately this is an easy translation.  */
17843   gdb_assert (per_cu->is_debug_types);
17844   sig_type = (struct signatured_type *) per_cu;
17845
17846   gdb_assert (per_cu->cu == NULL);
17847
17848   read_signatured_type (sig_type);
17849
17850   gdb_assert (per_cu->cu != NULL);
17851 }
17852
17853 /* die_reader_func for read_signatured_type.
17854    This is identical to load_full_comp_unit_reader,
17855    but is kept separate for now.  */
17856
17857 static void
17858 read_signatured_type_reader (const struct die_reader_specs *reader,
17859                              const gdb_byte *info_ptr,
17860                              struct die_info *comp_unit_die,
17861                              int has_children,
17862                              void *data)
17863 {
17864   struct dwarf2_cu *cu = reader->cu;
17865
17866   gdb_assert (cu->die_hash == NULL);
17867   cu->die_hash =
17868     htab_create_alloc_ex (cu->header.length / 12,
17869                           die_hash,
17870                           die_eq,
17871                           NULL,
17872                           &cu->comp_unit_obstack,
17873                           hashtab_obstack_allocate,
17874                           dummy_obstack_deallocate);
17875
17876   if (has_children)
17877     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17878                                                   &info_ptr, comp_unit_die);
17879   cu->dies = comp_unit_die;
17880   /* comp_unit_die is not stored in die_hash, no need.  */
17881
17882   /* We try not to read any attributes in this function, because not
17883      all CUs needed for references have been loaded yet, and symbol
17884      table processing isn't initialized.  But we have to set the CU language,
17885      or we won't be able to build types correctly.
17886      Similarly, if we do not read the producer, we can not apply
17887      producer-specific interpretation.  */
17888   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17889 }
17890
17891 /* Read in a signatured type and build its CU and DIEs.
17892    If the type is a stub for the real type in a DWO file,
17893    read in the real type from the DWO file as well.  */
17894
17895 static void
17896 read_signatured_type (struct signatured_type *sig_type)
17897 {
17898   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17899
17900   gdb_assert (per_cu->is_debug_types);
17901   gdb_assert (per_cu->cu == NULL);
17902
17903   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17904                            read_signatured_type_reader, NULL);
17905 }
17906
17907 /* Decode simple location descriptions.
17908    Given a pointer to a dwarf block that defines a location, compute
17909    the location and return the value.
17910
17911    NOTE drow/2003-11-18: This function is called in two situations
17912    now: for the address of static or global variables (partial symbols
17913    only) and for offsets into structures which are expected to be
17914    (more or less) constant.  The partial symbol case should go away,
17915    and only the constant case should remain.  That will let this
17916    function complain more accurately.  A few special modes are allowed
17917    without complaint for global variables (for instance, global
17918    register values and thread-local values).
17919
17920    A location description containing no operations indicates that the
17921    object is optimized out.  The return value is 0 for that case.
17922    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17923    callers will only want a very basic result and this can become a
17924    complaint.
17925
17926    Note that stack[0] is unused except as a default error return.  */
17927
17928 static CORE_ADDR
17929 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17930 {
17931   struct objfile *objfile = cu->objfile;
17932   size_t i;
17933   size_t size = blk->size;
17934   const gdb_byte *data = blk->data;
17935   CORE_ADDR stack[64];
17936   int stacki;
17937   unsigned int bytes_read, unsnd;
17938   gdb_byte op;
17939
17940   i = 0;
17941   stacki = 0;
17942   stack[stacki] = 0;
17943   stack[++stacki] = 0;
17944
17945   while (i < size)
17946     {
17947       op = data[i++];
17948       switch (op)
17949         {
17950         case DW_OP_lit0:
17951         case DW_OP_lit1:
17952         case DW_OP_lit2:
17953         case DW_OP_lit3:
17954         case DW_OP_lit4:
17955         case DW_OP_lit5:
17956         case DW_OP_lit6:
17957         case DW_OP_lit7:
17958         case DW_OP_lit8:
17959         case DW_OP_lit9:
17960         case DW_OP_lit10:
17961         case DW_OP_lit11:
17962         case DW_OP_lit12:
17963         case DW_OP_lit13:
17964         case DW_OP_lit14:
17965         case DW_OP_lit15:
17966         case DW_OP_lit16:
17967         case DW_OP_lit17:
17968         case DW_OP_lit18:
17969         case DW_OP_lit19:
17970         case DW_OP_lit20:
17971         case DW_OP_lit21:
17972         case DW_OP_lit22:
17973         case DW_OP_lit23:
17974         case DW_OP_lit24:
17975         case DW_OP_lit25:
17976         case DW_OP_lit26:
17977         case DW_OP_lit27:
17978         case DW_OP_lit28:
17979         case DW_OP_lit29:
17980         case DW_OP_lit30:
17981         case DW_OP_lit31:
17982           stack[++stacki] = op - DW_OP_lit0;
17983           break;
17984
17985         case DW_OP_reg0:
17986         case DW_OP_reg1:
17987         case DW_OP_reg2:
17988         case DW_OP_reg3:
17989         case DW_OP_reg4:
17990         case DW_OP_reg5:
17991         case DW_OP_reg6:
17992         case DW_OP_reg7:
17993         case DW_OP_reg8:
17994         case DW_OP_reg9:
17995         case DW_OP_reg10:
17996         case DW_OP_reg11:
17997         case DW_OP_reg12:
17998         case DW_OP_reg13:
17999         case DW_OP_reg14:
18000         case DW_OP_reg15:
18001         case DW_OP_reg16:
18002         case DW_OP_reg17:
18003         case DW_OP_reg18:
18004         case DW_OP_reg19:
18005         case DW_OP_reg20:
18006         case DW_OP_reg21:
18007         case DW_OP_reg22:
18008         case DW_OP_reg23:
18009         case DW_OP_reg24:
18010         case DW_OP_reg25:
18011         case DW_OP_reg26:
18012         case DW_OP_reg27:
18013         case DW_OP_reg28:
18014         case DW_OP_reg29:
18015         case DW_OP_reg30:
18016         case DW_OP_reg31:
18017           stack[++stacki] = op - DW_OP_reg0;
18018           if (i < size)
18019             dwarf2_complex_location_expr_complaint ();
18020           break;
18021
18022         case DW_OP_regx:
18023           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18024           i += bytes_read;
18025           stack[++stacki] = unsnd;
18026           if (i < size)
18027             dwarf2_complex_location_expr_complaint ();
18028           break;
18029
18030         case DW_OP_addr:
18031           stack[++stacki] = read_address (objfile->obfd, &data[i],
18032                                           cu, &bytes_read);
18033           i += bytes_read;
18034           break;
18035
18036         case DW_OP_const1u:
18037           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18038           i += 1;
18039           break;
18040
18041         case DW_OP_const1s:
18042           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18043           i += 1;
18044           break;
18045
18046         case DW_OP_const2u:
18047           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18048           i += 2;
18049           break;
18050
18051         case DW_OP_const2s:
18052           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18053           i += 2;
18054           break;
18055
18056         case DW_OP_const4u:
18057           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18058           i += 4;
18059           break;
18060
18061         case DW_OP_const4s:
18062           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18063           i += 4;
18064           break;
18065
18066         case DW_OP_const8u:
18067           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18068           i += 8;
18069           break;
18070
18071         case DW_OP_constu:
18072           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18073                                                   &bytes_read);
18074           i += bytes_read;
18075           break;
18076
18077         case DW_OP_consts:
18078           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18079           i += bytes_read;
18080           break;
18081
18082         case DW_OP_dup:
18083           stack[stacki + 1] = stack[stacki];
18084           stacki++;
18085           break;
18086
18087         case DW_OP_plus:
18088           stack[stacki - 1] += stack[stacki];
18089           stacki--;
18090           break;
18091
18092         case DW_OP_plus_uconst:
18093           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18094                                                  &bytes_read);
18095           i += bytes_read;
18096           break;
18097
18098         case DW_OP_minus:
18099           stack[stacki - 1] -= stack[stacki];
18100           stacki--;
18101           break;
18102
18103         case DW_OP_deref:
18104           /* If we're not the last op, then we definitely can't encode
18105              this using GDB's address_class enum.  This is valid for partial
18106              global symbols, although the variable's address will be bogus
18107              in the psymtab.  */
18108           if (i < size)
18109             dwarf2_complex_location_expr_complaint ();
18110           break;
18111
18112         case DW_OP_GNU_push_tls_address:
18113           /* The top of the stack has the offset from the beginning
18114              of the thread control block at which the variable is located.  */
18115           /* Nothing should follow this operator, so the top of stack would
18116              be returned.  */
18117           /* This is valid for partial global symbols, but the variable's
18118              address will be bogus in the psymtab.  Make it always at least
18119              non-zero to not look as a variable garbage collected by linker
18120              which have DW_OP_addr 0.  */
18121           if (i < size)
18122             dwarf2_complex_location_expr_complaint ();
18123           stack[stacki]++;
18124           break;
18125
18126         case DW_OP_GNU_uninit:
18127           break;
18128
18129         case DW_OP_GNU_addr_index:
18130         case DW_OP_GNU_const_index:
18131           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18132                                                          &bytes_read);
18133           i += bytes_read;
18134           break;
18135
18136         default:
18137           {
18138             const char *name = get_DW_OP_name (op);
18139
18140             if (name)
18141               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18142                          name);
18143             else
18144               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18145                          op);
18146           }
18147
18148           return (stack[stacki]);
18149         }
18150
18151       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18152          outside of the allocated space.  Also enforce minimum>0.  */
18153       if (stacki >= ARRAY_SIZE (stack) - 1)
18154         {
18155           complaint (&symfile_complaints,
18156                      _("location description stack overflow"));
18157           return 0;
18158         }
18159
18160       if (stacki <= 0)
18161         {
18162           complaint (&symfile_complaints,
18163                      _("location description stack underflow"));
18164           return 0;
18165         }
18166     }
18167   return (stack[stacki]);
18168 }
18169
18170 /* memory allocation interface */
18171
18172 static struct dwarf_block *
18173 dwarf_alloc_block (struct dwarf2_cu *cu)
18174 {
18175   struct dwarf_block *blk;
18176
18177   blk = (struct dwarf_block *)
18178     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18179   return (blk);
18180 }
18181
18182 static struct die_info *
18183 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18184 {
18185   struct die_info *die;
18186   size_t size = sizeof (struct die_info);
18187
18188   if (num_attrs > 1)
18189     size += (num_attrs - 1) * sizeof (struct attribute);
18190
18191   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18192   memset (die, 0, sizeof (struct die_info));
18193   return (die);
18194 }
18195
18196 \f
18197 /* Macro support.  */
18198
18199 /* Return file name relative to the compilation directory of file number I in
18200    *LH's file name table.  The result is allocated using xmalloc; the caller is
18201    responsible for freeing it.  */
18202
18203 static char *
18204 file_file_name (int file, struct line_header *lh)
18205 {
18206   /* Is the file number a valid index into the line header's file name
18207      table?  Remember that file numbers start with one, not zero.  */
18208   if (1 <= file && file <= lh->num_file_names)
18209     {
18210       struct file_entry *fe = &lh->file_names[file - 1];
18211
18212       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18213         return xstrdup (fe->name);
18214       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18215                      fe->name, NULL);
18216     }
18217   else
18218     {
18219       /* The compiler produced a bogus file number.  We can at least
18220          record the macro definitions made in the file, even if we
18221          won't be able to find the file by name.  */
18222       char fake_name[80];
18223
18224       xsnprintf (fake_name, sizeof (fake_name),
18225                  "<bad macro file number %d>", file);
18226
18227       complaint (&symfile_complaints,
18228                  _("bad file number in macro information (%d)"),
18229                  file);
18230
18231       return xstrdup (fake_name);
18232     }
18233 }
18234
18235 /* Return the full name of file number I in *LH's file name table.
18236    Use COMP_DIR as the name of the current directory of the
18237    compilation.  The result is allocated using xmalloc; the caller is
18238    responsible for freeing it.  */
18239 static char *
18240 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18241 {
18242   /* Is the file number a valid index into the line header's file name
18243      table?  Remember that file numbers start with one, not zero.  */
18244   if (1 <= file && file <= lh->num_file_names)
18245     {
18246       char *relative = file_file_name (file, lh);
18247
18248       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18249         return relative;
18250       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18251     }
18252   else
18253     return file_file_name (file, lh);
18254 }
18255
18256
18257 static struct macro_source_file *
18258 macro_start_file (int file, int line,
18259                   struct macro_source_file *current_file,
18260                   const char *comp_dir,
18261                   struct line_header *lh, struct objfile *objfile)
18262 {
18263   /* File name relative to the compilation directory of this source file.  */
18264   char *file_name = file_file_name (file, lh);
18265
18266   /* We don't create a macro table for this compilation unit
18267      at all until we actually get a filename.  */
18268   if (! pending_macros)
18269     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18270                                       objfile->per_bfd->macro_cache,
18271                                       comp_dir);
18272
18273   if (! current_file)
18274     {
18275       /* If we have no current file, then this must be the start_file
18276          directive for the compilation unit's main source file.  */
18277       current_file = macro_set_main (pending_macros, file_name);
18278       macro_define_special (pending_macros);
18279     }
18280   else
18281     current_file = macro_include (current_file, line, file_name);
18282
18283   xfree (file_name);
18284
18285   return current_file;
18286 }
18287
18288
18289 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18290    followed by a null byte.  */
18291 static char *
18292 copy_string (const char *buf, int len)
18293 {
18294   char *s = xmalloc (len + 1);
18295
18296   memcpy (s, buf, len);
18297   s[len] = '\0';
18298   return s;
18299 }
18300
18301
18302 static const char *
18303 consume_improper_spaces (const char *p, const char *body)
18304 {
18305   if (*p == ' ')
18306     {
18307       complaint (&symfile_complaints,
18308                  _("macro definition contains spaces "
18309                    "in formal argument list:\n`%s'"),
18310                  body);
18311
18312       while (*p == ' ')
18313         p++;
18314     }
18315
18316   return p;
18317 }
18318
18319
18320 static void
18321 parse_macro_definition (struct macro_source_file *file, int line,
18322                         const char *body)
18323 {
18324   const char *p;
18325
18326   /* The body string takes one of two forms.  For object-like macro
18327      definitions, it should be:
18328
18329         <macro name> " " <definition>
18330
18331      For function-like macro definitions, it should be:
18332
18333         <macro name> "() " <definition>
18334      or
18335         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18336
18337      Spaces may appear only where explicitly indicated, and in the
18338      <definition>.
18339
18340      The Dwarf 2 spec says that an object-like macro's name is always
18341      followed by a space, but versions of GCC around March 2002 omit
18342      the space when the macro's definition is the empty string.
18343
18344      The Dwarf 2 spec says that there should be no spaces between the
18345      formal arguments in a function-like macro's formal argument list,
18346      but versions of GCC around March 2002 include spaces after the
18347      commas.  */
18348
18349
18350   /* Find the extent of the macro name.  The macro name is terminated
18351      by either a space or null character (for an object-like macro) or
18352      an opening paren (for a function-like macro).  */
18353   for (p = body; *p; p++)
18354     if (*p == ' ' || *p == '(')
18355       break;
18356
18357   if (*p == ' ' || *p == '\0')
18358     {
18359       /* It's an object-like macro.  */
18360       int name_len = p - body;
18361       char *name = copy_string (body, name_len);
18362       const char *replacement;
18363
18364       if (*p == ' ')
18365         replacement = body + name_len + 1;
18366       else
18367         {
18368           dwarf2_macro_malformed_definition_complaint (body);
18369           replacement = body + name_len;
18370         }
18371
18372       macro_define_object (file, line, name, replacement);
18373
18374       xfree (name);
18375     }
18376   else if (*p == '(')
18377     {
18378       /* It's a function-like macro.  */
18379       char *name = copy_string (body, p - body);
18380       int argc = 0;
18381       int argv_size = 1;
18382       char **argv = xmalloc (argv_size * sizeof (*argv));
18383
18384       p++;
18385
18386       p = consume_improper_spaces (p, body);
18387
18388       /* Parse the formal argument list.  */
18389       while (*p && *p != ')')
18390         {
18391           /* Find the extent of the current argument name.  */
18392           const char *arg_start = p;
18393
18394           while (*p && *p != ',' && *p != ')' && *p != ' ')
18395             p++;
18396
18397           if (! *p || p == arg_start)
18398             dwarf2_macro_malformed_definition_complaint (body);
18399           else
18400             {
18401               /* Make sure argv has room for the new argument.  */
18402               if (argc >= argv_size)
18403                 {
18404                   argv_size *= 2;
18405                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18406                 }
18407
18408               argv[argc++] = copy_string (arg_start, p - arg_start);
18409             }
18410
18411           p = consume_improper_spaces (p, body);
18412
18413           /* Consume the comma, if present.  */
18414           if (*p == ',')
18415             {
18416               p++;
18417
18418               p = consume_improper_spaces (p, body);
18419             }
18420         }
18421
18422       if (*p == ')')
18423         {
18424           p++;
18425
18426           if (*p == ' ')
18427             /* Perfectly formed definition, no complaints.  */
18428             macro_define_function (file, line, name,
18429                                    argc, (const char **) argv,
18430                                    p + 1);
18431           else if (*p == '\0')
18432             {
18433               /* Complain, but do define it.  */
18434               dwarf2_macro_malformed_definition_complaint (body);
18435               macro_define_function (file, line, name,
18436                                      argc, (const char **) argv,
18437                                      p);
18438             }
18439           else
18440             /* Just complain.  */
18441             dwarf2_macro_malformed_definition_complaint (body);
18442         }
18443       else
18444         /* Just complain.  */
18445         dwarf2_macro_malformed_definition_complaint (body);
18446
18447       xfree (name);
18448       {
18449         int i;
18450
18451         for (i = 0; i < argc; i++)
18452           xfree (argv[i]);
18453       }
18454       xfree (argv);
18455     }
18456   else
18457     dwarf2_macro_malformed_definition_complaint (body);
18458 }
18459
18460 /* Skip some bytes from BYTES according to the form given in FORM.
18461    Returns the new pointer.  */
18462
18463 static const gdb_byte *
18464 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
18465                  enum dwarf_form form,
18466                  unsigned int offset_size,
18467                  struct dwarf2_section_info *section)
18468 {
18469   unsigned int bytes_read;
18470
18471   switch (form)
18472     {
18473     case DW_FORM_data1:
18474     case DW_FORM_flag:
18475       ++bytes;
18476       break;
18477
18478     case DW_FORM_data2:
18479       bytes += 2;
18480       break;
18481
18482     case DW_FORM_data4:
18483       bytes += 4;
18484       break;
18485
18486     case DW_FORM_data8:
18487       bytes += 8;
18488       break;
18489
18490     case DW_FORM_string:
18491       read_direct_string (abfd, bytes, &bytes_read);
18492       bytes += bytes_read;
18493       break;
18494
18495     case DW_FORM_sec_offset:
18496     case DW_FORM_strp:
18497     case DW_FORM_GNU_strp_alt:
18498       bytes += offset_size;
18499       break;
18500
18501     case DW_FORM_block:
18502       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18503       bytes += bytes_read;
18504       break;
18505
18506     case DW_FORM_block1:
18507       bytes += 1 + read_1_byte (abfd, bytes);
18508       break;
18509     case DW_FORM_block2:
18510       bytes += 2 + read_2_bytes (abfd, bytes);
18511       break;
18512     case DW_FORM_block4:
18513       bytes += 4 + read_4_bytes (abfd, bytes);
18514       break;
18515
18516     case DW_FORM_sdata:
18517     case DW_FORM_udata:
18518     case DW_FORM_GNU_addr_index:
18519     case DW_FORM_GNU_str_index:
18520       bytes = gdb_skip_leb128 (bytes, buffer_end);
18521       if (bytes == NULL)
18522         {
18523           dwarf2_section_buffer_overflow_complaint (section);
18524           return NULL;
18525         }
18526       break;
18527
18528     default:
18529       {
18530       complain:
18531         complaint (&symfile_complaints,
18532                    _("invalid form 0x%x in `%s'"),
18533                    form,
18534                    section->asection->name);
18535         return NULL;
18536       }
18537     }
18538
18539   return bytes;
18540 }
18541
18542 /* A helper for dwarf_decode_macros that handles skipping an unknown
18543    opcode.  Returns an updated pointer to the macro data buffer; or,
18544    on error, issues a complaint and returns NULL.  */
18545
18546 static const gdb_byte *
18547 skip_unknown_opcode (unsigned int opcode,
18548                      const gdb_byte **opcode_definitions,
18549                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
18550                      bfd *abfd,
18551                      unsigned int offset_size,
18552                      struct dwarf2_section_info *section)
18553 {
18554   unsigned int bytes_read, i;
18555   unsigned long arg;
18556   const gdb_byte *defn;
18557
18558   if (opcode_definitions[opcode] == NULL)
18559     {
18560       complaint (&symfile_complaints,
18561                  _("unrecognized DW_MACFINO opcode 0x%x"),
18562                  opcode);
18563       return NULL;
18564     }
18565
18566   defn = opcode_definitions[opcode];
18567   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18568   defn += bytes_read;
18569
18570   for (i = 0; i < arg; ++i)
18571     {
18572       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18573                                  section);
18574       if (mac_ptr == NULL)
18575         {
18576           /* skip_form_bytes already issued the complaint.  */
18577           return NULL;
18578         }
18579     }
18580
18581   return mac_ptr;
18582 }
18583
18584 /* A helper function which parses the header of a macro section.
18585    If the macro section is the extended (for now called "GNU") type,
18586    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18587    the header, or issues a complaint and returns NULL on error.  */
18588
18589 static const gdb_byte *
18590 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
18591                           bfd *abfd,
18592                           const gdb_byte *mac_ptr,
18593                           unsigned int *offset_size,
18594                           int section_is_gnu)
18595 {
18596   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18597
18598   if (section_is_gnu)
18599     {
18600       unsigned int version, flags;
18601
18602       version = read_2_bytes (abfd, mac_ptr);
18603       if (version != 4)
18604         {
18605           complaint (&symfile_complaints,
18606                      _("unrecognized version `%d' in .debug_macro section"),
18607                      version);
18608           return NULL;
18609         }
18610       mac_ptr += 2;
18611
18612       flags = read_1_byte (abfd, mac_ptr);
18613       ++mac_ptr;
18614       *offset_size = (flags & 1) ? 8 : 4;
18615
18616       if ((flags & 2) != 0)
18617         /* We don't need the line table offset.  */
18618         mac_ptr += *offset_size;
18619
18620       /* Vendor opcode descriptions.  */
18621       if ((flags & 4) != 0)
18622         {
18623           unsigned int i, count;
18624
18625           count = read_1_byte (abfd, mac_ptr);
18626           ++mac_ptr;
18627           for (i = 0; i < count; ++i)
18628             {
18629               unsigned int opcode, bytes_read;
18630               unsigned long arg;
18631
18632               opcode = read_1_byte (abfd, mac_ptr);
18633               ++mac_ptr;
18634               opcode_definitions[opcode] = mac_ptr;
18635               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18636               mac_ptr += bytes_read;
18637               mac_ptr += arg;
18638             }
18639         }
18640     }
18641
18642   return mac_ptr;
18643 }
18644
18645 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18646    including DW_MACRO_GNU_transparent_include.  */
18647
18648 static void
18649 dwarf_decode_macro_bytes (bfd *abfd,
18650                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
18651                           struct macro_source_file *current_file,
18652                           struct line_header *lh, const char *comp_dir,
18653                           struct dwarf2_section_info *section,
18654                           int section_is_gnu, int section_is_dwz,
18655                           unsigned int offset_size,
18656                           struct objfile *objfile,
18657                           htab_t include_hash)
18658 {
18659   enum dwarf_macro_record_type macinfo_type;
18660   int at_commandline;
18661   const gdb_byte *opcode_definitions[256];
18662
18663   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18664                                       &offset_size, section_is_gnu);
18665   if (mac_ptr == NULL)
18666     {
18667       /* We already issued a complaint.  */
18668       return;
18669     }
18670
18671   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18672      GDB is still reading the definitions from command line.  First
18673      DW_MACINFO_start_file will need to be ignored as it was already executed
18674      to create CURRENT_FILE for the main source holding also the command line
18675      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18676      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18677
18678   at_commandline = 1;
18679
18680   do
18681     {
18682       /* Do we at least have room for a macinfo type byte?  */
18683       if (mac_ptr >= mac_end)
18684         {
18685           dwarf2_section_buffer_overflow_complaint (section);
18686           break;
18687         }
18688
18689       macinfo_type = read_1_byte (abfd, mac_ptr);
18690       mac_ptr++;
18691
18692       /* Note that we rely on the fact that the corresponding GNU and
18693          DWARF constants are the same.  */
18694       switch (macinfo_type)
18695         {
18696           /* A zero macinfo type indicates the end of the macro
18697              information.  */
18698         case 0:
18699           break;
18700
18701         case DW_MACRO_GNU_define:
18702         case DW_MACRO_GNU_undef:
18703         case DW_MACRO_GNU_define_indirect:
18704         case DW_MACRO_GNU_undef_indirect:
18705         case DW_MACRO_GNU_define_indirect_alt:
18706         case DW_MACRO_GNU_undef_indirect_alt:
18707           {
18708             unsigned int bytes_read;
18709             int line;
18710             const char *body;
18711             int is_define;
18712
18713             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18714             mac_ptr += bytes_read;
18715
18716             if (macinfo_type == DW_MACRO_GNU_define
18717                 || macinfo_type == DW_MACRO_GNU_undef)
18718               {
18719                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18720                 mac_ptr += bytes_read;
18721               }
18722             else
18723               {
18724                 LONGEST str_offset;
18725
18726                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18727                 mac_ptr += offset_size;
18728
18729                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18730                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18731                     || section_is_dwz)
18732                   {
18733                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18734
18735                     body = read_indirect_string_from_dwz (dwz, str_offset);
18736                   }
18737                 else
18738                   body = read_indirect_string_at_offset (abfd, str_offset);
18739               }
18740
18741             is_define = (macinfo_type == DW_MACRO_GNU_define
18742                          || macinfo_type == DW_MACRO_GNU_define_indirect
18743                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18744             if (! current_file)
18745               {
18746                 /* DWARF violation as no main source is present.  */
18747                 complaint (&symfile_complaints,
18748                            _("debug info with no main source gives macro %s "
18749                              "on line %d: %s"),
18750                            is_define ? _("definition") : _("undefinition"),
18751                            line, body);
18752                 break;
18753               }
18754             if ((line == 0 && !at_commandline)
18755                 || (line != 0 && at_commandline))
18756               complaint (&symfile_complaints,
18757                          _("debug info gives %s macro %s with %s line %d: %s"),
18758                          at_commandline ? _("command-line") : _("in-file"),
18759                          is_define ? _("definition") : _("undefinition"),
18760                          line == 0 ? _("zero") : _("non-zero"), line, body);
18761
18762             if (is_define)
18763               parse_macro_definition (current_file, line, body);
18764             else
18765               {
18766                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18767                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18768                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18769                 macro_undef (current_file, line, body);
18770               }
18771           }
18772           break;
18773
18774         case DW_MACRO_GNU_start_file:
18775           {
18776             unsigned int bytes_read;
18777             int line, file;
18778
18779             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18780             mac_ptr += bytes_read;
18781             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18782             mac_ptr += bytes_read;
18783
18784             if ((line == 0 && !at_commandline)
18785                 || (line != 0 && at_commandline))
18786               complaint (&symfile_complaints,
18787                          _("debug info gives source %d included "
18788                            "from %s at %s line %d"),
18789                          file, at_commandline ? _("command-line") : _("file"),
18790                          line == 0 ? _("zero") : _("non-zero"), line);
18791
18792             if (at_commandline)
18793               {
18794                 /* This DW_MACRO_GNU_start_file was executed in the
18795                    pass one.  */
18796                 at_commandline = 0;
18797               }
18798             else
18799               current_file = macro_start_file (file, line,
18800                                                current_file, comp_dir,
18801                                                lh, objfile);
18802           }
18803           break;
18804
18805         case DW_MACRO_GNU_end_file:
18806           if (! current_file)
18807             complaint (&symfile_complaints,
18808                        _("macro debug info has an unmatched "
18809                          "`close_file' directive"));
18810           else
18811             {
18812               current_file = current_file->included_by;
18813               if (! current_file)
18814                 {
18815                   enum dwarf_macro_record_type next_type;
18816
18817                   /* GCC circa March 2002 doesn't produce the zero
18818                      type byte marking the end of the compilation
18819                      unit.  Complain if it's not there, but exit no
18820                      matter what.  */
18821
18822                   /* Do we at least have room for a macinfo type byte?  */
18823                   if (mac_ptr >= mac_end)
18824                     {
18825                       dwarf2_section_buffer_overflow_complaint (section);
18826                       return;
18827                     }
18828
18829                   /* We don't increment mac_ptr here, so this is just
18830                      a look-ahead.  */
18831                   next_type = read_1_byte (abfd, mac_ptr);
18832                   if (next_type != 0)
18833                     complaint (&symfile_complaints,
18834                                _("no terminating 0-type entry for "
18835                                  "macros in `.debug_macinfo' section"));
18836
18837                   return;
18838                 }
18839             }
18840           break;
18841
18842         case DW_MACRO_GNU_transparent_include:
18843         case DW_MACRO_GNU_transparent_include_alt:
18844           {
18845             LONGEST offset;
18846             void **slot;
18847             bfd *include_bfd = abfd;
18848             struct dwarf2_section_info *include_section = section;
18849             struct dwarf2_section_info alt_section;
18850             const gdb_byte *include_mac_end = mac_end;
18851             int is_dwz = section_is_dwz;
18852             const gdb_byte *new_mac_ptr;
18853
18854             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18855             mac_ptr += offset_size;
18856
18857             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18858               {
18859                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18860
18861                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18862                                      &dwz->macro);
18863
18864                 include_bfd = dwz->macro.asection->owner;
18865                 include_section = &dwz->macro;
18866                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18867                 is_dwz = 1;
18868               }
18869
18870             new_mac_ptr = include_section->buffer + offset;
18871             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18872
18873             if (*slot != NULL)
18874               {
18875                 /* This has actually happened; see
18876                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18877                 complaint (&symfile_complaints,
18878                            _("recursive DW_MACRO_GNU_transparent_include in "
18879                              ".debug_macro section"));
18880               }
18881             else
18882               {
18883                 *slot = (void *) new_mac_ptr;
18884
18885                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18886                                           include_mac_end, current_file,
18887                                           lh, comp_dir,
18888                                           section, section_is_gnu, is_dwz,
18889                                           offset_size, objfile, include_hash);
18890
18891                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
18892               }
18893           }
18894           break;
18895
18896         case DW_MACINFO_vendor_ext:
18897           if (!section_is_gnu)
18898             {
18899               unsigned int bytes_read;
18900               int constant;
18901
18902               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18903               mac_ptr += bytes_read;
18904               read_direct_string (abfd, mac_ptr, &bytes_read);
18905               mac_ptr += bytes_read;
18906
18907               /* We don't recognize any vendor extensions.  */
18908               break;
18909             }
18910           /* FALLTHROUGH */
18911
18912         default:
18913           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18914                                          mac_ptr, mac_end, abfd, offset_size,
18915                                          section);
18916           if (mac_ptr == NULL)
18917             return;
18918           break;
18919         }
18920     } while (macinfo_type != 0);
18921 }
18922
18923 static void
18924 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18925                      const char *comp_dir, int section_is_gnu)
18926 {
18927   struct objfile *objfile = dwarf2_per_objfile->objfile;
18928   struct line_header *lh = cu->line_header;
18929   bfd *abfd;
18930   const gdb_byte *mac_ptr, *mac_end;
18931   struct macro_source_file *current_file = 0;
18932   enum dwarf_macro_record_type macinfo_type;
18933   unsigned int offset_size = cu->header.offset_size;
18934   const gdb_byte *opcode_definitions[256];
18935   struct cleanup *cleanup;
18936   htab_t include_hash;
18937   void **slot;
18938   struct dwarf2_section_info *section;
18939   const char *section_name;
18940
18941   if (cu->dwo_unit != NULL)
18942     {
18943       if (section_is_gnu)
18944         {
18945           section = &cu->dwo_unit->dwo_file->sections.macro;
18946           section_name = ".debug_macro.dwo";
18947         }
18948       else
18949         {
18950           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18951           section_name = ".debug_macinfo.dwo";
18952         }
18953     }
18954   else
18955     {
18956       if (section_is_gnu)
18957         {
18958           section = &dwarf2_per_objfile->macro;
18959           section_name = ".debug_macro";
18960         }
18961       else
18962         {
18963           section = &dwarf2_per_objfile->macinfo;
18964           section_name = ".debug_macinfo";
18965         }
18966     }
18967
18968   dwarf2_read_section (objfile, section);
18969   if (section->buffer == NULL)
18970     {
18971       complaint (&symfile_complaints, _("missing %s section"), section_name);
18972       return;
18973     }
18974   abfd = section->asection->owner;
18975
18976   /* First pass: Find the name of the base filename.
18977      This filename is needed in order to process all macros whose definition
18978      (or undefinition) comes from the command line.  These macros are defined
18979      before the first DW_MACINFO_start_file entry, and yet still need to be
18980      associated to the base file.
18981
18982      To determine the base file name, we scan the macro definitions until we
18983      reach the first DW_MACINFO_start_file entry.  We then initialize
18984      CURRENT_FILE accordingly so that any macro definition found before the
18985      first DW_MACINFO_start_file can still be associated to the base file.  */
18986
18987   mac_ptr = section->buffer + offset;
18988   mac_end = section->buffer + section->size;
18989
18990   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18991                                       &offset_size, section_is_gnu);
18992   if (mac_ptr == NULL)
18993     {
18994       /* We already issued a complaint.  */
18995       return;
18996     }
18997
18998   do
18999     {
19000       /* Do we at least have room for a macinfo type byte?  */
19001       if (mac_ptr >= mac_end)
19002         {
19003           /* Complaint is printed during the second pass as GDB will probably
19004              stop the first pass earlier upon finding
19005              DW_MACINFO_start_file.  */
19006           break;
19007         }
19008
19009       macinfo_type = read_1_byte (abfd, mac_ptr);
19010       mac_ptr++;
19011
19012       /* Note that we rely on the fact that the corresponding GNU and
19013          DWARF constants are the same.  */
19014       switch (macinfo_type)
19015         {
19016           /* A zero macinfo type indicates the end of the macro
19017              information.  */
19018         case 0:
19019           break;
19020
19021         case DW_MACRO_GNU_define:
19022         case DW_MACRO_GNU_undef:
19023           /* Only skip the data by MAC_PTR.  */
19024           {
19025             unsigned int bytes_read;
19026
19027             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19028             mac_ptr += bytes_read;
19029             read_direct_string (abfd, mac_ptr, &bytes_read);
19030             mac_ptr += bytes_read;
19031           }
19032           break;
19033
19034         case DW_MACRO_GNU_start_file:
19035           {
19036             unsigned int bytes_read;
19037             int line, file;
19038
19039             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19040             mac_ptr += bytes_read;
19041             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19042             mac_ptr += bytes_read;
19043
19044             current_file = macro_start_file (file, line, current_file,
19045                                              comp_dir, lh, objfile);
19046           }
19047           break;
19048
19049         case DW_MACRO_GNU_end_file:
19050           /* No data to skip by MAC_PTR.  */
19051           break;
19052
19053         case DW_MACRO_GNU_define_indirect:
19054         case DW_MACRO_GNU_undef_indirect:
19055         case DW_MACRO_GNU_define_indirect_alt:
19056         case DW_MACRO_GNU_undef_indirect_alt:
19057           {
19058             unsigned int bytes_read;
19059
19060             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19061             mac_ptr += bytes_read;
19062             mac_ptr += offset_size;
19063           }
19064           break;
19065
19066         case DW_MACRO_GNU_transparent_include:
19067         case DW_MACRO_GNU_transparent_include_alt:
19068           /* Note that, according to the spec, a transparent include
19069              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19070              skip this opcode.  */
19071           mac_ptr += offset_size;
19072           break;
19073
19074         case DW_MACINFO_vendor_ext:
19075           /* Only skip the data by MAC_PTR.  */
19076           if (!section_is_gnu)
19077             {
19078               unsigned int bytes_read;
19079
19080               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19081               mac_ptr += bytes_read;
19082               read_direct_string (abfd, mac_ptr, &bytes_read);
19083               mac_ptr += bytes_read;
19084             }
19085           /* FALLTHROUGH */
19086
19087         default:
19088           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19089                                          mac_ptr, mac_end, abfd, offset_size,
19090                                          section);
19091           if (mac_ptr == NULL)
19092             return;
19093           break;
19094         }
19095     } while (macinfo_type != 0 && current_file == NULL);
19096
19097   /* Second pass: Process all entries.
19098
19099      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19100      command-line macro definitions/undefinitions.  This flag is unset when we
19101      reach the first DW_MACINFO_start_file entry.  */
19102
19103   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19104                                     NULL, xcalloc, xfree);
19105   cleanup = make_cleanup_htab_delete (include_hash);
19106   mac_ptr = section->buffer + offset;
19107   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19108   *slot = (void *) mac_ptr;
19109   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19110                             current_file, lh, comp_dir, section,
19111                             section_is_gnu, 0,
19112                             offset_size, objfile, include_hash);
19113   do_cleanups (cleanup);
19114 }
19115
19116 /* Check if the attribute's form is a DW_FORM_block*
19117    if so return true else false.  */
19118
19119 static int
19120 attr_form_is_block (struct attribute *attr)
19121 {
19122   return (attr == NULL ? 0 :
19123       attr->form == DW_FORM_block1
19124       || attr->form == DW_FORM_block2
19125       || attr->form == DW_FORM_block4
19126       || attr->form == DW_FORM_block
19127       || attr->form == DW_FORM_exprloc);
19128 }
19129
19130 /* Return non-zero if ATTR's value is a section offset --- classes
19131    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19132    You may use DW_UNSND (attr) to retrieve such offsets.
19133
19134    Section 7.5.4, "Attribute Encodings", explains that no attribute
19135    may have a value that belongs to more than one of these classes; it
19136    would be ambiguous if we did, because we use the same forms for all
19137    of them.  */
19138
19139 static int
19140 attr_form_is_section_offset (struct attribute *attr)
19141 {
19142   return (attr->form == DW_FORM_data4
19143           || attr->form == DW_FORM_data8
19144           || attr->form == DW_FORM_sec_offset);
19145 }
19146
19147 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19148    zero otherwise.  When this function returns true, you can apply
19149    dwarf2_get_attr_constant_value to it.
19150
19151    However, note that for some attributes you must check
19152    attr_form_is_section_offset before using this test.  DW_FORM_data4
19153    and DW_FORM_data8 are members of both the constant class, and of
19154    the classes that contain offsets into other debug sections
19155    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19156    that, if an attribute's can be either a constant or one of the
19157    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19158    taken as section offsets, not constants.  */
19159
19160 static int
19161 attr_form_is_constant (struct attribute *attr)
19162 {
19163   switch (attr->form)
19164     {
19165     case DW_FORM_sdata:
19166     case DW_FORM_udata:
19167     case DW_FORM_data1:
19168     case DW_FORM_data2:
19169     case DW_FORM_data4:
19170     case DW_FORM_data8:
19171       return 1;
19172     default:
19173       return 0;
19174     }
19175 }
19176
19177 /* Return the .debug_loc section to use for CU.
19178    For DWO files use .debug_loc.dwo.  */
19179
19180 static struct dwarf2_section_info *
19181 cu_debug_loc_section (struct dwarf2_cu *cu)
19182 {
19183   if (cu->dwo_unit)
19184     return &cu->dwo_unit->dwo_file->sections.loc;
19185   return &dwarf2_per_objfile->loc;
19186 }
19187
19188 /* A helper function that fills in a dwarf2_loclist_baton.  */
19189
19190 static void
19191 fill_in_loclist_baton (struct dwarf2_cu *cu,
19192                        struct dwarf2_loclist_baton *baton,
19193                        struct attribute *attr)
19194 {
19195   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19196
19197   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19198
19199   baton->per_cu = cu->per_cu;
19200   gdb_assert (baton->per_cu);
19201   /* We don't know how long the location list is, but make sure we
19202      don't run off the edge of the section.  */
19203   baton->size = section->size - DW_UNSND (attr);
19204   baton->data = section->buffer + DW_UNSND (attr);
19205   baton->base_address = cu->base_address;
19206   baton->from_dwo = cu->dwo_unit != NULL;
19207 }
19208
19209 static void
19210 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19211                              struct dwarf2_cu *cu, int is_block)
19212 {
19213   struct objfile *objfile = dwarf2_per_objfile->objfile;
19214   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19215
19216   if (attr_form_is_section_offset (attr)
19217       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19218          the section.  If so, fall through to the complaint in the
19219          other branch.  */
19220       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19221     {
19222       struct dwarf2_loclist_baton *baton;
19223
19224       baton = obstack_alloc (&objfile->objfile_obstack,
19225                              sizeof (struct dwarf2_loclist_baton));
19226
19227       fill_in_loclist_baton (cu, baton, attr);
19228
19229       if (cu->base_known == 0)
19230         complaint (&symfile_complaints,
19231                    _("Location list used without "
19232                      "specifying the CU base address."));
19233
19234       SYMBOL_ACLASS_INDEX (sym) = (is_block
19235                                    ? dwarf2_loclist_block_index
19236                                    : dwarf2_loclist_index);
19237       SYMBOL_LOCATION_BATON (sym) = baton;
19238     }
19239   else
19240     {
19241       struct dwarf2_locexpr_baton *baton;
19242
19243       baton = obstack_alloc (&objfile->objfile_obstack,
19244                              sizeof (struct dwarf2_locexpr_baton));
19245       baton->per_cu = cu->per_cu;
19246       gdb_assert (baton->per_cu);
19247
19248       if (attr_form_is_block (attr))
19249         {
19250           /* Note that we're just copying the block's data pointer
19251              here, not the actual data.  We're still pointing into the
19252              info_buffer for SYM's objfile; right now we never release
19253              that buffer, but when we do clean up properly this may
19254              need to change.  */
19255           baton->size = DW_BLOCK (attr)->size;
19256           baton->data = DW_BLOCK (attr)->data;
19257         }
19258       else
19259         {
19260           dwarf2_invalid_attrib_class_complaint ("location description",
19261                                                  SYMBOL_NATURAL_NAME (sym));
19262           baton->size = 0;
19263         }
19264
19265       SYMBOL_ACLASS_INDEX (sym) = (is_block
19266                                    ? dwarf2_locexpr_block_index
19267                                    : dwarf2_locexpr_index);
19268       SYMBOL_LOCATION_BATON (sym) = baton;
19269     }
19270 }
19271
19272 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19273    came from a separate debuginfo file, then the master objfile is
19274    returned.  */
19275
19276 struct objfile *
19277 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19278 {
19279   struct objfile *objfile = per_cu->objfile;
19280
19281   /* Return the master objfile, so that we can report and look up the
19282      correct file containing this variable.  */
19283   if (objfile->separate_debug_objfile_backlink)
19284     objfile = objfile->separate_debug_objfile_backlink;
19285
19286   return objfile;
19287 }
19288
19289 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19290    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19291    CU_HEADERP first.  */
19292
19293 static const struct comp_unit_head *
19294 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19295                        struct dwarf2_per_cu_data *per_cu)
19296 {
19297   const gdb_byte *info_ptr;
19298
19299   if (per_cu->cu)
19300     return &per_cu->cu->header;
19301
19302   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19303
19304   memset (cu_headerp, 0, sizeof (*cu_headerp));
19305   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19306
19307   return cu_headerp;
19308 }
19309
19310 /* Return the address size given in the compilation unit header for CU.  */
19311
19312 int
19313 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19314 {
19315   struct comp_unit_head cu_header_local;
19316   const struct comp_unit_head *cu_headerp;
19317
19318   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19319
19320   return cu_headerp->addr_size;
19321 }
19322
19323 /* Return the offset size given in the compilation unit header for CU.  */
19324
19325 int
19326 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19327 {
19328   struct comp_unit_head cu_header_local;
19329   const struct comp_unit_head *cu_headerp;
19330
19331   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19332
19333   return cu_headerp->offset_size;
19334 }
19335
19336 /* See its dwarf2loc.h declaration.  */
19337
19338 int
19339 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19340 {
19341   struct comp_unit_head cu_header_local;
19342   const struct comp_unit_head *cu_headerp;
19343
19344   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19345
19346   if (cu_headerp->version == 2)
19347     return cu_headerp->addr_size;
19348   else
19349     return cu_headerp->offset_size;
19350 }
19351
19352 /* Return the text offset of the CU.  The returned offset comes from
19353    this CU's objfile.  If this objfile came from a separate debuginfo
19354    file, then the offset may be different from the corresponding
19355    offset in the parent objfile.  */
19356
19357 CORE_ADDR
19358 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19359 {
19360   struct objfile *objfile = per_cu->objfile;
19361
19362   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19363 }
19364
19365 /* Locate the .debug_info compilation unit from CU's objfile which contains
19366    the DIE at OFFSET.  Raises an error on failure.  */
19367
19368 static struct dwarf2_per_cu_data *
19369 dwarf2_find_containing_comp_unit (sect_offset offset,
19370                                   unsigned int offset_in_dwz,
19371                                   struct objfile *objfile)
19372 {
19373   struct dwarf2_per_cu_data *this_cu;
19374   int low, high;
19375   const sect_offset *cu_off;
19376
19377   low = 0;
19378   high = dwarf2_per_objfile->n_comp_units - 1;
19379   while (high > low)
19380     {
19381       struct dwarf2_per_cu_data *mid_cu;
19382       int mid = low + (high - low) / 2;
19383
19384       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19385       cu_off = &mid_cu->offset;
19386       if (mid_cu->is_dwz > offset_in_dwz
19387           || (mid_cu->is_dwz == offset_in_dwz
19388               && cu_off->sect_off >= offset.sect_off))
19389         high = mid;
19390       else
19391         low = mid + 1;
19392     }
19393   gdb_assert (low == high);
19394   this_cu = dwarf2_per_objfile->all_comp_units[low];
19395   cu_off = &this_cu->offset;
19396   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19397     {
19398       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19399         error (_("Dwarf Error: could not find partial DIE containing "
19400                "offset 0x%lx [in module %s]"),
19401                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19402
19403       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19404                   <= offset.sect_off);
19405       return dwarf2_per_objfile->all_comp_units[low-1];
19406     }
19407   else
19408     {
19409       this_cu = dwarf2_per_objfile->all_comp_units[low];
19410       if (low == dwarf2_per_objfile->n_comp_units - 1
19411           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19412         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19413       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19414       return this_cu;
19415     }
19416 }
19417
19418 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19419
19420 static void
19421 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19422 {
19423   memset (cu, 0, sizeof (*cu));
19424   per_cu->cu = cu;
19425   cu->per_cu = per_cu;
19426   cu->objfile = per_cu->objfile;
19427   obstack_init (&cu->comp_unit_obstack);
19428 }
19429
19430 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19431
19432 static void
19433 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19434                        enum language pretend_language)
19435 {
19436   struct attribute *attr;
19437
19438   /* Set the language we're debugging.  */
19439   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19440   if (attr)
19441     set_cu_language (DW_UNSND (attr), cu);
19442   else
19443     {
19444       cu->language = pretend_language;
19445       cu->language_defn = language_def (cu->language);
19446     }
19447
19448   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19449   if (attr)
19450     cu->producer = DW_STRING (attr);
19451 }
19452
19453 /* Release one cached compilation unit, CU.  We unlink it from the tree
19454    of compilation units, but we don't remove it from the read_in_chain;
19455    the caller is responsible for that.
19456    NOTE: DATA is a void * because this function is also used as a
19457    cleanup routine.  */
19458
19459 static void
19460 free_heap_comp_unit (void *data)
19461 {
19462   struct dwarf2_cu *cu = data;
19463
19464   gdb_assert (cu->per_cu != NULL);
19465   cu->per_cu->cu = NULL;
19466   cu->per_cu = NULL;
19467
19468   obstack_free (&cu->comp_unit_obstack, NULL);
19469
19470   xfree (cu);
19471 }
19472
19473 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19474    when we're finished with it.  We can't free the pointer itself, but be
19475    sure to unlink it from the cache.  Also release any associated storage.  */
19476
19477 static void
19478 free_stack_comp_unit (void *data)
19479 {
19480   struct dwarf2_cu *cu = data;
19481
19482   gdb_assert (cu->per_cu != NULL);
19483   cu->per_cu->cu = NULL;
19484   cu->per_cu = NULL;
19485
19486   obstack_free (&cu->comp_unit_obstack, NULL);
19487   cu->partial_dies = NULL;
19488 }
19489
19490 /* Free all cached compilation units.  */
19491
19492 static void
19493 free_cached_comp_units (void *data)
19494 {
19495   struct dwarf2_per_cu_data *per_cu, **last_chain;
19496
19497   per_cu = dwarf2_per_objfile->read_in_chain;
19498   last_chain = &dwarf2_per_objfile->read_in_chain;
19499   while (per_cu != NULL)
19500     {
19501       struct dwarf2_per_cu_data *next_cu;
19502
19503       next_cu = per_cu->cu->read_in_chain;
19504
19505       free_heap_comp_unit (per_cu->cu);
19506       *last_chain = next_cu;
19507
19508       per_cu = next_cu;
19509     }
19510 }
19511
19512 /* Increase the age counter on each cached compilation unit, and free
19513    any that are too old.  */
19514
19515 static void
19516 age_cached_comp_units (void)
19517 {
19518   struct dwarf2_per_cu_data *per_cu, **last_chain;
19519
19520   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19521   per_cu = dwarf2_per_objfile->read_in_chain;
19522   while (per_cu != NULL)
19523     {
19524       per_cu->cu->last_used ++;
19525       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19526         dwarf2_mark (per_cu->cu);
19527       per_cu = per_cu->cu->read_in_chain;
19528     }
19529
19530   per_cu = dwarf2_per_objfile->read_in_chain;
19531   last_chain = &dwarf2_per_objfile->read_in_chain;
19532   while (per_cu != NULL)
19533     {
19534       struct dwarf2_per_cu_data *next_cu;
19535
19536       next_cu = per_cu->cu->read_in_chain;
19537
19538       if (!per_cu->cu->mark)
19539         {
19540           free_heap_comp_unit (per_cu->cu);
19541           *last_chain = next_cu;
19542         }
19543       else
19544         last_chain = &per_cu->cu->read_in_chain;
19545
19546       per_cu = next_cu;
19547     }
19548 }
19549
19550 /* Remove a single compilation unit from the cache.  */
19551
19552 static void
19553 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19554 {
19555   struct dwarf2_per_cu_data *per_cu, **last_chain;
19556
19557   per_cu = dwarf2_per_objfile->read_in_chain;
19558   last_chain = &dwarf2_per_objfile->read_in_chain;
19559   while (per_cu != NULL)
19560     {
19561       struct dwarf2_per_cu_data *next_cu;
19562
19563       next_cu = per_cu->cu->read_in_chain;
19564
19565       if (per_cu == target_per_cu)
19566         {
19567           free_heap_comp_unit (per_cu->cu);
19568           per_cu->cu = NULL;
19569           *last_chain = next_cu;
19570           break;
19571         }
19572       else
19573         last_chain = &per_cu->cu->read_in_chain;
19574
19575       per_cu = next_cu;
19576     }
19577 }
19578
19579 /* Release all extra memory associated with OBJFILE.  */
19580
19581 void
19582 dwarf2_free_objfile (struct objfile *objfile)
19583 {
19584   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19585
19586   if (dwarf2_per_objfile == NULL)
19587     return;
19588
19589   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19590   free_cached_comp_units (NULL);
19591
19592   if (dwarf2_per_objfile->quick_file_names_table)
19593     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19594
19595   /* Everything else should be on the objfile obstack.  */
19596 }
19597
19598 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19599    We store these in a hash table separate from the DIEs, and preserve them
19600    when the DIEs are flushed out of cache.
19601
19602    The CU "per_cu" pointer is needed because offset alone is not enough to
19603    uniquely identify the type.  A file may have multiple .debug_types sections,
19604    or the type may come from a DWO file.  Furthermore, while it's more logical
19605    to use per_cu->section+offset, with Fission the section with the data is in
19606    the DWO file but we don't know that section at the point we need it.
19607    We have to use something in dwarf2_per_cu_data (or the pointer to it)
19608    because we can enter the lookup routine, get_die_type_at_offset, from
19609    outside this file, and thus won't necessarily have PER_CU->cu.
19610    Fortunately, PER_CU is stable for the life of the objfile.  */
19611
19612 struct dwarf2_per_cu_offset_and_type
19613 {
19614   const struct dwarf2_per_cu_data *per_cu;
19615   sect_offset offset;
19616   struct type *type;
19617 };
19618
19619 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19620
19621 static hashval_t
19622 per_cu_offset_and_type_hash (const void *item)
19623 {
19624   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19625
19626   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19627 }
19628
19629 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19630
19631 static int
19632 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19633 {
19634   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19635   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19636
19637   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19638           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19639 }
19640
19641 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19642    table if necessary.  For convenience, return TYPE.
19643
19644    The DIEs reading must have careful ordering to:
19645     * Not cause infite loops trying to read in DIEs as a prerequisite for
19646       reading current DIE.
19647     * Not trying to dereference contents of still incompletely read in types
19648       while reading in other DIEs.
19649     * Enable referencing still incompletely read in types just by a pointer to
19650       the type without accessing its fields.
19651
19652    Therefore caller should follow these rules:
19653      * Try to fetch any prerequisite types we may need to build this DIE type
19654        before building the type and calling set_die_type.
19655      * After building type call set_die_type for current DIE as soon as
19656        possible before fetching more types to complete the current type.
19657      * Make the type as complete as possible before fetching more types.  */
19658
19659 static struct type *
19660 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19661 {
19662   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19663   struct objfile *objfile = cu->objfile;
19664
19665   /* For Ada types, make sure that the gnat-specific data is always
19666      initialized (if not already set).  There are a few types where
19667      we should not be doing so, because the type-specific area is
19668      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19669      where the type-specific area is used to store the floatformat).
19670      But this is not a problem, because the gnat-specific information
19671      is actually not needed for these types.  */
19672   if (need_gnat_info (cu)
19673       && TYPE_CODE (type) != TYPE_CODE_FUNC
19674       && TYPE_CODE (type) != TYPE_CODE_FLT
19675       && !HAVE_GNAT_AUX_INFO (type))
19676     INIT_GNAT_SPECIFIC (type);
19677
19678   if (dwarf2_per_objfile->die_type_hash == NULL)
19679     {
19680       dwarf2_per_objfile->die_type_hash =
19681         htab_create_alloc_ex (127,
19682                               per_cu_offset_and_type_hash,
19683                               per_cu_offset_and_type_eq,
19684                               NULL,
19685                               &objfile->objfile_obstack,
19686                               hashtab_obstack_allocate,
19687                               dummy_obstack_deallocate);
19688     }
19689
19690   ofs.per_cu = cu->per_cu;
19691   ofs.offset = die->offset;
19692   ofs.type = type;
19693   slot = (struct dwarf2_per_cu_offset_and_type **)
19694     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19695   if (*slot)
19696     complaint (&symfile_complaints,
19697                _("A problem internal to GDB: DIE 0x%x has type already set"),
19698                die->offset.sect_off);
19699   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19700   **slot = ofs;
19701   return type;
19702 }
19703
19704 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
19705    or return NULL if the die does not have a saved type.  */
19706
19707 static struct type *
19708 get_die_type_at_offset (sect_offset offset,
19709                         struct dwarf2_per_cu_data *per_cu)
19710 {
19711   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19712
19713   if (dwarf2_per_objfile->die_type_hash == NULL)
19714     return NULL;
19715
19716   ofs.per_cu = per_cu;
19717   ofs.offset = offset;
19718   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19719   if (slot)
19720     return slot->type;
19721   else
19722     return NULL;
19723 }
19724
19725 /* Look up the type for DIE in CU in die_type_hash,
19726    or return NULL if DIE does not have a saved type.  */
19727
19728 static struct type *
19729 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19730 {
19731   return get_die_type_at_offset (die->offset, cu->per_cu);
19732 }
19733
19734 /* Add a dependence relationship from CU to REF_PER_CU.  */
19735
19736 static void
19737 dwarf2_add_dependence (struct dwarf2_cu *cu,
19738                        struct dwarf2_per_cu_data *ref_per_cu)
19739 {
19740   void **slot;
19741
19742   if (cu->dependencies == NULL)
19743     cu->dependencies
19744       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19745                               NULL, &cu->comp_unit_obstack,
19746                               hashtab_obstack_allocate,
19747                               dummy_obstack_deallocate);
19748
19749   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19750   if (*slot == NULL)
19751     *slot = ref_per_cu;
19752 }
19753
19754 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19755    Set the mark field in every compilation unit in the
19756    cache that we must keep because we are keeping CU.  */
19757
19758 static int
19759 dwarf2_mark_helper (void **slot, void *data)
19760 {
19761   struct dwarf2_per_cu_data *per_cu;
19762
19763   per_cu = (struct dwarf2_per_cu_data *) *slot;
19764
19765   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19766      reading of the chain.  As such dependencies remain valid it is not much
19767      useful to track and undo them during QUIT cleanups.  */
19768   if (per_cu->cu == NULL)
19769     return 1;
19770
19771   if (per_cu->cu->mark)
19772     return 1;
19773   per_cu->cu->mark = 1;
19774
19775   if (per_cu->cu->dependencies != NULL)
19776     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19777
19778   return 1;
19779 }
19780
19781 /* Set the mark field in CU and in every other compilation unit in the
19782    cache that we must keep because we are keeping CU.  */
19783
19784 static void
19785 dwarf2_mark (struct dwarf2_cu *cu)
19786 {
19787   if (cu->mark)
19788     return;
19789   cu->mark = 1;
19790   if (cu->dependencies != NULL)
19791     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19792 }
19793
19794 static void
19795 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19796 {
19797   while (per_cu)
19798     {
19799       per_cu->cu->mark = 0;
19800       per_cu = per_cu->cu->read_in_chain;
19801     }
19802 }
19803
19804 /* Trivial hash function for partial_die_info: the hash value of a DIE
19805    is its offset in .debug_info for this objfile.  */
19806
19807 static hashval_t
19808 partial_die_hash (const void *item)
19809 {
19810   const struct partial_die_info *part_die = item;
19811
19812   return part_die->offset.sect_off;
19813 }
19814
19815 /* Trivial comparison function for partial_die_info structures: two DIEs
19816    are equal if they have the same offset.  */
19817
19818 static int
19819 partial_die_eq (const void *item_lhs, const void *item_rhs)
19820 {
19821   const struct partial_die_info *part_die_lhs = item_lhs;
19822   const struct partial_die_info *part_die_rhs = item_rhs;
19823
19824   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19825 }
19826
19827 static struct cmd_list_element *set_dwarf2_cmdlist;
19828 static struct cmd_list_element *show_dwarf2_cmdlist;
19829
19830 static void
19831 set_dwarf2_cmd (char *args, int from_tty)
19832 {
19833   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19834 }
19835
19836 static void
19837 show_dwarf2_cmd (char *args, int from_tty)
19838 {
19839   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19840 }
19841
19842 /* Free data associated with OBJFILE, if necessary.  */
19843
19844 static void
19845 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19846 {
19847   struct dwarf2_per_objfile *data = d;
19848   int ix;
19849
19850   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19851     VEC_free (dwarf2_per_cu_ptr,
19852               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19853
19854   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19855     VEC_free (dwarf2_per_cu_ptr,
19856               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19857
19858   VEC_free (dwarf2_section_info_def, data->types);
19859
19860   if (data->dwo_files)
19861     free_dwo_files (data->dwo_files, objfile);
19862   if (data->dwp_file)
19863     gdb_bfd_unref (data->dwp_file->dbfd);
19864
19865   if (data->dwz_file && data->dwz_file->dwz_bfd)
19866     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19867 }
19868
19869 \f
19870 /* The "save gdb-index" command.  */
19871
19872 /* The contents of the hash table we create when building the string
19873    table.  */
19874 struct strtab_entry
19875 {
19876   offset_type offset;
19877   const char *str;
19878 };
19879
19880 /* Hash function for a strtab_entry.
19881
19882    Function is used only during write_hash_table so no index format backward
19883    compatibility is needed.  */
19884
19885 static hashval_t
19886 hash_strtab_entry (const void *e)
19887 {
19888   const struct strtab_entry *entry = e;
19889   return mapped_index_string_hash (INT_MAX, entry->str);
19890 }
19891
19892 /* Equality function for a strtab_entry.  */
19893
19894 static int
19895 eq_strtab_entry (const void *a, const void *b)
19896 {
19897   const struct strtab_entry *ea = a;
19898   const struct strtab_entry *eb = b;
19899   return !strcmp (ea->str, eb->str);
19900 }
19901
19902 /* Create a strtab_entry hash table.  */
19903
19904 static htab_t
19905 create_strtab (void)
19906 {
19907   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19908                             xfree, xcalloc, xfree);
19909 }
19910
19911 /* Add a string to the constant pool.  Return the string's offset in
19912    host order.  */
19913
19914 static offset_type
19915 add_string (htab_t table, struct obstack *cpool, const char *str)
19916 {
19917   void **slot;
19918   struct strtab_entry entry;
19919   struct strtab_entry *result;
19920
19921   entry.str = str;
19922   slot = htab_find_slot (table, &entry, INSERT);
19923   if (*slot)
19924     result = *slot;
19925   else
19926     {
19927       result = XNEW (struct strtab_entry);
19928       result->offset = obstack_object_size (cpool);
19929       result->str = str;
19930       obstack_grow_str0 (cpool, str);
19931       *slot = result;
19932     }
19933   return result->offset;
19934 }
19935
19936 /* An entry in the symbol table.  */
19937 struct symtab_index_entry
19938 {
19939   /* The name of the symbol.  */
19940   const char *name;
19941   /* The offset of the name in the constant pool.  */
19942   offset_type index_offset;
19943   /* A sorted vector of the indices of all the CUs that hold an object
19944      of this name.  */
19945   VEC (offset_type) *cu_indices;
19946 };
19947
19948 /* The symbol table.  This is a power-of-2-sized hash table.  */
19949 struct mapped_symtab
19950 {
19951   offset_type n_elements;
19952   offset_type size;
19953   struct symtab_index_entry **data;
19954 };
19955
19956 /* Hash function for a symtab_index_entry.  */
19957
19958 static hashval_t
19959 hash_symtab_entry (const void *e)
19960 {
19961   const struct symtab_index_entry *entry = e;
19962   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19963                          sizeof (offset_type) * VEC_length (offset_type,
19964                                                             entry->cu_indices),
19965                          0);
19966 }
19967
19968 /* Equality function for a symtab_index_entry.  */
19969
19970 static int
19971 eq_symtab_entry (const void *a, const void *b)
19972 {
19973   const struct symtab_index_entry *ea = a;
19974   const struct symtab_index_entry *eb = b;
19975   int len = VEC_length (offset_type, ea->cu_indices);
19976   if (len != VEC_length (offset_type, eb->cu_indices))
19977     return 0;
19978   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19979                   VEC_address (offset_type, eb->cu_indices),
19980                   sizeof (offset_type) * len);
19981 }
19982
19983 /* Destroy a symtab_index_entry.  */
19984
19985 static void
19986 delete_symtab_entry (void *p)
19987 {
19988   struct symtab_index_entry *entry = p;
19989   VEC_free (offset_type, entry->cu_indices);
19990   xfree (entry);
19991 }
19992
19993 /* Create a hash table holding symtab_index_entry objects.  */
19994
19995 static htab_t
19996 create_symbol_hash_table (void)
19997 {
19998   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19999                             delete_symtab_entry, xcalloc, xfree);
20000 }
20001
20002 /* Create a new mapped symtab object.  */
20003
20004 static struct mapped_symtab *
20005 create_mapped_symtab (void)
20006 {
20007   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20008   symtab->n_elements = 0;
20009   symtab->size = 1024;
20010   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20011   return symtab;
20012 }
20013
20014 /* Destroy a mapped_symtab.  */
20015
20016 static void
20017 cleanup_mapped_symtab (void *p)
20018 {
20019   struct mapped_symtab *symtab = p;
20020   /* The contents of the array are freed when the other hash table is
20021      destroyed.  */
20022   xfree (symtab->data);
20023   xfree (symtab);
20024 }
20025
20026 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20027    the slot.
20028    
20029    Function is used only during write_hash_table so no index format backward
20030    compatibility is needed.  */
20031
20032 static struct symtab_index_entry **
20033 find_slot (struct mapped_symtab *symtab, const char *name)
20034 {
20035   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20036
20037   index = hash & (symtab->size - 1);
20038   step = ((hash * 17) & (symtab->size - 1)) | 1;
20039
20040   for (;;)
20041     {
20042       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20043         return &symtab->data[index];
20044       index = (index + step) & (symtab->size - 1);
20045     }
20046 }
20047
20048 /* Expand SYMTAB's hash table.  */
20049
20050 static void
20051 hash_expand (struct mapped_symtab *symtab)
20052 {
20053   offset_type old_size = symtab->size;
20054   offset_type i;
20055   struct symtab_index_entry **old_entries = symtab->data;
20056
20057   symtab->size *= 2;
20058   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20059
20060   for (i = 0; i < old_size; ++i)
20061     {
20062       if (old_entries[i])
20063         {
20064           struct symtab_index_entry **slot = find_slot (symtab,
20065                                                         old_entries[i]->name);
20066           *slot = old_entries[i];
20067         }
20068     }
20069
20070   xfree (old_entries);
20071 }
20072
20073 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20074    CU_INDEX is the index of the CU in which the symbol appears.
20075    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20076
20077 static void
20078 add_index_entry (struct mapped_symtab *symtab, const char *name,
20079                  int is_static, gdb_index_symbol_kind kind,
20080                  offset_type cu_index)
20081 {
20082   struct symtab_index_entry **slot;
20083   offset_type cu_index_and_attrs;
20084
20085   ++symtab->n_elements;
20086   if (4 * symtab->n_elements / 3 >= symtab->size)
20087     hash_expand (symtab);
20088
20089   slot = find_slot (symtab, name);
20090   if (!*slot)
20091     {
20092       *slot = XNEW (struct symtab_index_entry);
20093       (*slot)->name = name;
20094       /* index_offset is set later.  */
20095       (*slot)->cu_indices = NULL;
20096     }
20097
20098   cu_index_and_attrs = 0;
20099   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20100   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20101   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20102
20103   /* We don't want to record an index value twice as we want to avoid the
20104      duplication.
20105      We process all global symbols and then all static symbols
20106      (which would allow us to avoid the duplication by only having to check
20107      the last entry pushed), but a symbol could have multiple kinds in one CU.
20108      To keep things simple we don't worry about the duplication here and
20109      sort and uniqufy the list after we've processed all symbols.  */
20110   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20111 }
20112
20113 /* qsort helper routine for uniquify_cu_indices.  */
20114
20115 static int
20116 offset_type_compare (const void *ap, const void *bp)
20117 {
20118   offset_type a = *(offset_type *) ap;
20119   offset_type b = *(offset_type *) bp;
20120
20121   return (a > b) - (b > a);
20122 }
20123
20124 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20125
20126 static void
20127 uniquify_cu_indices (struct mapped_symtab *symtab)
20128 {
20129   int i;
20130
20131   for (i = 0; i < symtab->size; ++i)
20132     {
20133       struct symtab_index_entry *entry = symtab->data[i];
20134
20135       if (entry
20136           && entry->cu_indices != NULL)
20137         {
20138           unsigned int next_to_insert, next_to_check;
20139           offset_type last_value;
20140
20141           qsort (VEC_address (offset_type, entry->cu_indices),
20142                  VEC_length (offset_type, entry->cu_indices),
20143                  sizeof (offset_type), offset_type_compare);
20144
20145           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20146           next_to_insert = 1;
20147           for (next_to_check = 1;
20148                next_to_check < VEC_length (offset_type, entry->cu_indices);
20149                ++next_to_check)
20150             {
20151               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20152                   != last_value)
20153                 {
20154                   last_value = VEC_index (offset_type, entry->cu_indices,
20155                                           next_to_check);
20156                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20157                                last_value);
20158                   ++next_to_insert;
20159                 }
20160             }
20161           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20162         }
20163     }
20164 }
20165
20166 /* Add a vector of indices to the constant pool.  */
20167
20168 static offset_type
20169 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20170                       struct symtab_index_entry *entry)
20171 {
20172   void **slot;
20173
20174   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20175   if (!*slot)
20176     {
20177       offset_type len = VEC_length (offset_type, entry->cu_indices);
20178       offset_type val = MAYBE_SWAP (len);
20179       offset_type iter;
20180       int i;
20181
20182       *slot = entry;
20183       entry->index_offset = obstack_object_size (cpool);
20184
20185       obstack_grow (cpool, &val, sizeof (val));
20186       for (i = 0;
20187            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20188            ++i)
20189         {
20190           val = MAYBE_SWAP (iter);
20191           obstack_grow (cpool, &val, sizeof (val));
20192         }
20193     }
20194   else
20195     {
20196       struct symtab_index_entry *old_entry = *slot;
20197       entry->index_offset = old_entry->index_offset;
20198       entry = old_entry;
20199     }
20200   return entry->index_offset;
20201 }
20202
20203 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20204    constant pool entries going into the obstack CPOOL.  */
20205
20206 static void
20207 write_hash_table (struct mapped_symtab *symtab,
20208                   struct obstack *output, struct obstack *cpool)
20209 {
20210   offset_type i;
20211   htab_t symbol_hash_table;
20212   htab_t str_table;
20213
20214   symbol_hash_table = create_symbol_hash_table ();
20215   str_table = create_strtab ();
20216
20217   /* We add all the index vectors to the constant pool first, to
20218      ensure alignment is ok.  */
20219   for (i = 0; i < symtab->size; ++i)
20220     {
20221       if (symtab->data[i])
20222         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20223     }
20224
20225   /* Now write out the hash table.  */
20226   for (i = 0; i < symtab->size; ++i)
20227     {
20228       offset_type str_off, vec_off;
20229
20230       if (symtab->data[i])
20231         {
20232           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20233           vec_off = symtab->data[i]->index_offset;
20234         }
20235       else
20236         {
20237           /* While 0 is a valid constant pool index, it is not valid
20238              to have 0 for both offsets.  */
20239           str_off = 0;
20240           vec_off = 0;
20241         }
20242
20243       str_off = MAYBE_SWAP (str_off);
20244       vec_off = MAYBE_SWAP (vec_off);
20245
20246       obstack_grow (output, &str_off, sizeof (str_off));
20247       obstack_grow (output, &vec_off, sizeof (vec_off));
20248     }
20249
20250   htab_delete (str_table);
20251   htab_delete (symbol_hash_table);
20252 }
20253
20254 /* Struct to map psymtab to CU index in the index file.  */
20255 struct psymtab_cu_index_map
20256 {
20257   struct partial_symtab *psymtab;
20258   unsigned int cu_index;
20259 };
20260
20261 static hashval_t
20262 hash_psymtab_cu_index (const void *item)
20263 {
20264   const struct psymtab_cu_index_map *map = item;
20265
20266   return htab_hash_pointer (map->psymtab);
20267 }
20268
20269 static int
20270 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20271 {
20272   const struct psymtab_cu_index_map *lhs = item_lhs;
20273   const struct psymtab_cu_index_map *rhs = item_rhs;
20274
20275   return lhs->psymtab == rhs->psymtab;
20276 }
20277
20278 /* Helper struct for building the address table.  */
20279 struct addrmap_index_data
20280 {
20281   struct objfile *objfile;
20282   struct obstack *addr_obstack;
20283   htab_t cu_index_htab;
20284
20285   /* Non-zero if the previous_* fields are valid.
20286      We can't write an entry until we see the next entry (since it is only then
20287      that we know the end of the entry).  */
20288   int previous_valid;
20289   /* Index of the CU in the table of all CUs in the index file.  */
20290   unsigned int previous_cu_index;
20291   /* Start address of the CU.  */
20292   CORE_ADDR previous_cu_start;
20293 };
20294
20295 /* Write an address entry to OBSTACK.  */
20296
20297 static void
20298 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20299                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20300 {
20301   offset_type cu_index_to_write;
20302   char addr[8];
20303   CORE_ADDR baseaddr;
20304
20305   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20306
20307   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20308   obstack_grow (obstack, addr, 8);
20309   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20310   obstack_grow (obstack, addr, 8);
20311   cu_index_to_write = MAYBE_SWAP (cu_index);
20312   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20313 }
20314
20315 /* Worker function for traversing an addrmap to build the address table.  */
20316
20317 static int
20318 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20319 {
20320   struct addrmap_index_data *data = datap;
20321   struct partial_symtab *pst = obj;
20322
20323   if (data->previous_valid)
20324     add_address_entry (data->objfile, data->addr_obstack,
20325                        data->previous_cu_start, start_addr,
20326                        data->previous_cu_index);
20327
20328   data->previous_cu_start = start_addr;
20329   if (pst != NULL)
20330     {
20331       struct psymtab_cu_index_map find_map, *map;
20332       find_map.psymtab = pst;
20333       map = htab_find (data->cu_index_htab, &find_map);
20334       gdb_assert (map != NULL);
20335       data->previous_cu_index = map->cu_index;
20336       data->previous_valid = 1;
20337     }
20338   else
20339       data->previous_valid = 0;
20340
20341   return 0;
20342 }
20343
20344 /* Write OBJFILE's address map to OBSTACK.
20345    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20346    in the index file.  */
20347
20348 static void
20349 write_address_map (struct objfile *objfile, struct obstack *obstack,
20350                    htab_t cu_index_htab)
20351 {
20352   struct addrmap_index_data addrmap_index_data;
20353
20354   /* When writing the address table, we have to cope with the fact that
20355      the addrmap iterator only provides the start of a region; we have to
20356      wait until the next invocation to get the start of the next region.  */
20357
20358   addrmap_index_data.objfile = objfile;
20359   addrmap_index_data.addr_obstack = obstack;
20360   addrmap_index_data.cu_index_htab = cu_index_htab;
20361   addrmap_index_data.previous_valid = 0;
20362
20363   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20364                    &addrmap_index_data);
20365
20366   /* It's highly unlikely the last entry (end address = 0xff...ff)
20367      is valid, but we should still handle it.
20368      The end address is recorded as the start of the next region, but that
20369      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20370      anyway.  */
20371   if (addrmap_index_data.previous_valid)
20372     add_address_entry (objfile, obstack,
20373                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20374                        addrmap_index_data.previous_cu_index);
20375 }
20376
20377 /* Return the symbol kind of PSYM.  */
20378
20379 static gdb_index_symbol_kind
20380 symbol_kind (struct partial_symbol *psym)
20381 {
20382   domain_enum domain = PSYMBOL_DOMAIN (psym);
20383   enum address_class aclass = PSYMBOL_CLASS (psym);
20384
20385   switch (domain)
20386     {
20387     case VAR_DOMAIN:
20388       switch (aclass)
20389         {
20390         case LOC_BLOCK:
20391           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20392         case LOC_TYPEDEF:
20393           return GDB_INDEX_SYMBOL_KIND_TYPE;
20394         case LOC_COMPUTED:
20395         case LOC_CONST_BYTES:
20396         case LOC_OPTIMIZED_OUT:
20397         case LOC_STATIC:
20398           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20399         case LOC_CONST:
20400           /* Note: It's currently impossible to recognize psyms as enum values
20401              short of reading the type info.  For now punt.  */
20402           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20403         default:
20404           /* There are other LOC_FOO values that one might want to classify
20405              as variables, but dwarf2read.c doesn't currently use them.  */
20406           return GDB_INDEX_SYMBOL_KIND_OTHER;
20407         }
20408     case STRUCT_DOMAIN:
20409       return GDB_INDEX_SYMBOL_KIND_TYPE;
20410     default:
20411       return GDB_INDEX_SYMBOL_KIND_OTHER;
20412     }
20413 }
20414
20415 /* Add a list of partial symbols to SYMTAB.  */
20416
20417 static void
20418 write_psymbols (struct mapped_symtab *symtab,
20419                 htab_t psyms_seen,
20420                 struct partial_symbol **psymp,
20421                 int count,
20422                 offset_type cu_index,
20423                 int is_static)
20424 {
20425   for (; count-- > 0; ++psymp)
20426     {
20427       struct partial_symbol *psym = *psymp;
20428       void **slot;
20429
20430       if (SYMBOL_LANGUAGE (psym) == language_ada)
20431         error (_("Ada is not currently supported by the index"));
20432
20433       /* Only add a given psymbol once.  */
20434       slot = htab_find_slot (psyms_seen, psym, INSERT);
20435       if (!*slot)
20436         {
20437           gdb_index_symbol_kind kind = symbol_kind (psym);
20438
20439           *slot = psym;
20440           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20441                            is_static, kind, cu_index);
20442         }
20443     }
20444 }
20445
20446 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20447    exception if there is an error.  */
20448
20449 static void
20450 write_obstack (FILE *file, struct obstack *obstack)
20451 {
20452   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20453               file)
20454       != obstack_object_size (obstack))
20455     error (_("couldn't data write to file"));
20456 }
20457
20458 /* Unlink a file if the argument is not NULL.  */
20459
20460 static void
20461 unlink_if_set (void *p)
20462 {
20463   char **filename = p;
20464   if (*filename)
20465     unlink (*filename);
20466 }
20467
20468 /* A helper struct used when iterating over debug_types.  */
20469 struct signatured_type_index_data
20470 {
20471   struct objfile *objfile;
20472   struct mapped_symtab *symtab;
20473   struct obstack *types_list;
20474   htab_t psyms_seen;
20475   int cu_index;
20476 };
20477
20478 /* A helper function that writes a single signatured_type to an
20479    obstack.  */
20480
20481 static int
20482 write_one_signatured_type (void **slot, void *d)
20483 {
20484   struct signatured_type_index_data *info = d;
20485   struct signatured_type *entry = (struct signatured_type *) *slot;
20486   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
20487   gdb_byte val[8];
20488
20489   write_psymbols (info->symtab,
20490                   info->psyms_seen,
20491                   info->objfile->global_psymbols.list
20492                   + psymtab->globals_offset,
20493                   psymtab->n_global_syms, info->cu_index,
20494                   0);
20495   write_psymbols (info->symtab,
20496                   info->psyms_seen,
20497                   info->objfile->static_psymbols.list
20498                   + psymtab->statics_offset,
20499                   psymtab->n_static_syms, info->cu_index,
20500                   1);
20501
20502   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20503                           entry->per_cu.offset.sect_off);
20504   obstack_grow (info->types_list, val, 8);
20505   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20506                           entry->type_offset_in_tu.cu_off);
20507   obstack_grow (info->types_list, val, 8);
20508   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20509   obstack_grow (info->types_list, val, 8);
20510
20511   ++info->cu_index;
20512
20513   return 1;
20514 }
20515
20516 /* Recurse into all "included" dependencies and write their symbols as
20517    if they appeared in this psymtab.  */
20518
20519 static void
20520 recursively_write_psymbols (struct objfile *objfile,
20521                             struct partial_symtab *psymtab,
20522                             struct mapped_symtab *symtab,
20523                             htab_t psyms_seen,
20524                             offset_type cu_index)
20525 {
20526   int i;
20527
20528   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20529     if (psymtab->dependencies[i]->user != NULL)
20530       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20531                                   symtab, psyms_seen, cu_index);
20532
20533   write_psymbols (symtab,
20534                   psyms_seen,
20535                   objfile->global_psymbols.list + psymtab->globals_offset,
20536                   psymtab->n_global_syms, cu_index,
20537                   0);
20538   write_psymbols (symtab,
20539                   psyms_seen,
20540                   objfile->static_psymbols.list + psymtab->statics_offset,
20541                   psymtab->n_static_syms, cu_index,
20542                   1);
20543 }
20544
20545 /* Create an index file for OBJFILE in the directory DIR.  */
20546
20547 static void
20548 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20549 {
20550   struct cleanup *cleanup;
20551   char *filename, *cleanup_filename;
20552   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20553   struct obstack cu_list, types_cu_list;
20554   int i;
20555   FILE *out_file;
20556   struct mapped_symtab *symtab;
20557   offset_type val, size_of_contents, total_len;
20558   struct stat st;
20559   htab_t psyms_seen;
20560   htab_t cu_index_htab;
20561   struct psymtab_cu_index_map *psymtab_cu_index_map;
20562
20563   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20564     return;
20565
20566   if (dwarf2_per_objfile->using_index)
20567     error (_("Cannot use an index to create the index"));
20568
20569   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20570     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20571
20572   if (stat (objfile->name, &st) < 0)
20573     perror_with_name (objfile->name);
20574
20575   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20576                      INDEX_SUFFIX, (char *) NULL);
20577   cleanup = make_cleanup (xfree, filename);
20578
20579   out_file = fopen (filename, "wb");
20580   if (!out_file)
20581     error (_("Can't open `%s' for writing"), filename);
20582
20583   cleanup_filename = filename;
20584   make_cleanup (unlink_if_set, &cleanup_filename);
20585
20586   symtab = create_mapped_symtab ();
20587   make_cleanup (cleanup_mapped_symtab, symtab);
20588
20589   obstack_init (&addr_obstack);
20590   make_cleanup_obstack_free (&addr_obstack);
20591
20592   obstack_init (&cu_list);
20593   make_cleanup_obstack_free (&cu_list);
20594
20595   obstack_init (&types_cu_list);
20596   make_cleanup_obstack_free (&types_cu_list);
20597
20598   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20599                                   NULL, xcalloc, xfree);
20600   make_cleanup_htab_delete (psyms_seen);
20601
20602   /* While we're scanning CU's create a table that maps a psymtab pointer
20603      (which is what addrmap records) to its index (which is what is recorded
20604      in the index file).  This will later be needed to write the address
20605      table.  */
20606   cu_index_htab = htab_create_alloc (100,
20607                                      hash_psymtab_cu_index,
20608                                      eq_psymtab_cu_index,
20609                                      NULL, xcalloc, xfree);
20610   make_cleanup_htab_delete (cu_index_htab);
20611   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20612     xmalloc (sizeof (struct psymtab_cu_index_map)
20613              * dwarf2_per_objfile->n_comp_units);
20614   make_cleanup (xfree, psymtab_cu_index_map);
20615
20616   /* The CU list is already sorted, so we don't need to do additional
20617      work here.  Also, the debug_types entries do not appear in
20618      all_comp_units, but only in their own hash table.  */
20619   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20620     {
20621       struct dwarf2_per_cu_data *per_cu
20622         = dwarf2_per_objfile->all_comp_units[i];
20623       struct partial_symtab *psymtab = per_cu->v.psymtab;
20624       gdb_byte val[8];
20625       struct psymtab_cu_index_map *map;
20626       void **slot;
20627
20628       if (psymtab->user == NULL)
20629         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20630
20631       map = &psymtab_cu_index_map[i];
20632       map->psymtab = psymtab;
20633       map->cu_index = i;
20634       slot = htab_find_slot (cu_index_htab, map, INSERT);
20635       gdb_assert (slot != NULL);
20636       gdb_assert (*slot == NULL);
20637       *slot = map;
20638
20639       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20640                               per_cu->offset.sect_off);
20641       obstack_grow (&cu_list, val, 8);
20642       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20643       obstack_grow (&cu_list, val, 8);
20644     }
20645
20646   /* Dump the address map.  */
20647   write_address_map (objfile, &addr_obstack, cu_index_htab);
20648
20649   /* Write out the .debug_type entries, if any.  */
20650   if (dwarf2_per_objfile->signatured_types)
20651     {
20652       struct signatured_type_index_data sig_data;
20653
20654       sig_data.objfile = objfile;
20655       sig_data.symtab = symtab;
20656       sig_data.types_list = &types_cu_list;
20657       sig_data.psyms_seen = psyms_seen;
20658       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20659       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20660                               write_one_signatured_type, &sig_data);
20661     }
20662
20663   /* Now that we've processed all symbols we can shrink their cu_indices
20664      lists.  */
20665   uniquify_cu_indices (symtab);
20666
20667   obstack_init (&constant_pool);
20668   make_cleanup_obstack_free (&constant_pool);
20669   obstack_init (&symtab_obstack);
20670   make_cleanup_obstack_free (&symtab_obstack);
20671   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20672
20673   obstack_init (&contents);
20674   make_cleanup_obstack_free (&contents);
20675   size_of_contents = 6 * sizeof (offset_type);
20676   total_len = size_of_contents;
20677
20678   /* The version number.  */
20679   val = MAYBE_SWAP (8);
20680   obstack_grow (&contents, &val, sizeof (val));
20681
20682   /* The offset of the CU list from the start of the file.  */
20683   val = MAYBE_SWAP (total_len);
20684   obstack_grow (&contents, &val, sizeof (val));
20685   total_len += obstack_object_size (&cu_list);
20686
20687   /* The offset of the types CU list from the start of the file.  */
20688   val = MAYBE_SWAP (total_len);
20689   obstack_grow (&contents, &val, sizeof (val));
20690   total_len += obstack_object_size (&types_cu_list);
20691
20692   /* The offset of the address table from the start of the file.  */
20693   val = MAYBE_SWAP (total_len);
20694   obstack_grow (&contents, &val, sizeof (val));
20695   total_len += obstack_object_size (&addr_obstack);
20696
20697   /* The offset of the symbol table from the start of the file.  */
20698   val = MAYBE_SWAP (total_len);
20699   obstack_grow (&contents, &val, sizeof (val));
20700   total_len += obstack_object_size (&symtab_obstack);
20701
20702   /* The offset of the constant pool from the start of the file.  */
20703   val = MAYBE_SWAP (total_len);
20704   obstack_grow (&contents, &val, sizeof (val));
20705   total_len += obstack_object_size (&constant_pool);
20706
20707   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20708
20709   write_obstack (out_file, &contents);
20710   write_obstack (out_file, &cu_list);
20711   write_obstack (out_file, &types_cu_list);
20712   write_obstack (out_file, &addr_obstack);
20713   write_obstack (out_file, &symtab_obstack);
20714   write_obstack (out_file, &constant_pool);
20715
20716   fclose (out_file);
20717
20718   /* We want to keep the file, so we set cleanup_filename to NULL
20719      here.  See unlink_if_set.  */
20720   cleanup_filename = NULL;
20721
20722   do_cleanups (cleanup);
20723 }
20724
20725 /* Implementation of the `save gdb-index' command.
20726    
20727    Note that the file format used by this command is documented in the
20728    GDB manual.  Any changes here must be documented there.  */
20729
20730 static void
20731 save_gdb_index_command (char *arg, int from_tty)
20732 {
20733   struct objfile *objfile;
20734
20735   if (!arg || !*arg)
20736     error (_("usage: save gdb-index DIRECTORY"));
20737
20738   ALL_OBJFILES (objfile)
20739   {
20740     struct stat st;
20741
20742     /* If the objfile does not correspond to an actual file, skip it.  */
20743     if (stat (objfile->name, &st) < 0)
20744       continue;
20745
20746     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20747     if (dwarf2_per_objfile)
20748       {
20749         volatile struct gdb_exception except;
20750
20751         TRY_CATCH (except, RETURN_MASK_ERROR)
20752           {
20753             write_psymtabs_to_index (objfile, arg);
20754           }
20755         if (except.reason < 0)
20756           exception_fprintf (gdb_stderr, except,
20757                              _("Error while writing index for `%s': "),
20758                              objfile->name);
20759       }
20760   }
20761 }
20762
20763 \f
20764
20765 int dwarf2_always_disassemble;
20766
20767 static void
20768 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20769                                 struct cmd_list_element *c, const char *value)
20770 {
20771   fprintf_filtered (file,
20772                     _("Whether to always disassemble "
20773                       "DWARF expressions is %s.\n"),
20774                     value);
20775 }
20776
20777 static void
20778 show_check_physname (struct ui_file *file, int from_tty,
20779                      struct cmd_list_element *c, const char *value)
20780 {
20781   fprintf_filtered (file,
20782                     _("Whether to check \"physname\" is %s.\n"),
20783                     value);
20784 }
20785
20786 void _initialize_dwarf2_read (void);
20787
20788 void
20789 _initialize_dwarf2_read (void)
20790 {
20791   struct cmd_list_element *c;
20792
20793   dwarf2_objfile_data_key
20794     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20795
20796   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20797 Set DWARF 2 specific variables.\n\
20798 Configure DWARF 2 variables such as the cache size"),
20799                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20800                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20801
20802   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20803 Show DWARF 2 specific variables\n\
20804 Show DWARF 2 variables such as the cache size"),
20805                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20806                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20807
20808   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20809                             &dwarf2_max_cache_age, _("\
20810 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20811 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20812 A higher limit means that cached compilation units will be stored\n\
20813 in memory longer, and more total memory will be used.  Zero disables\n\
20814 caching, which can slow down startup."),
20815                             NULL,
20816                             show_dwarf2_max_cache_age,
20817                             &set_dwarf2_cmdlist,
20818                             &show_dwarf2_cmdlist);
20819
20820   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20821                            &dwarf2_always_disassemble, _("\
20822 Set whether `info address' always disassembles DWARF expressions."), _("\
20823 Show whether `info address' always disassembles DWARF expressions."), _("\
20824 When enabled, DWARF expressions are always printed in an assembly-like\n\
20825 syntax.  When disabled, expressions will be printed in a more\n\
20826 conversational style, when possible."),
20827                            NULL,
20828                            show_dwarf2_always_disassemble,
20829                            &set_dwarf2_cmdlist,
20830                            &show_dwarf2_cmdlist);
20831
20832   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20833 Set debugging of the dwarf2 reader."), _("\
20834 Show debugging of the dwarf2 reader."), _("\
20835 When enabled, debugging messages are printed during dwarf2 reading\n\
20836 and symtab expansion."),
20837                             NULL,
20838                             NULL,
20839                             &setdebuglist, &showdebuglist);
20840
20841   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20842 Set debugging of the dwarf2 DIE reader."), _("\
20843 Show debugging of the dwarf2 DIE reader."), _("\
20844 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20845 The value is the maximum depth to print."),
20846                              NULL,
20847                              NULL,
20848                              &setdebuglist, &showdebuglist);
20849
20850   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20851 Set cross-checking of \"physname\" code against demangler."), _("\
20852 Show cross-checking of \"physname\" code against demangler."), _("\
20853 When enabled, GDB's internal \"physname\" code is checked against\n\
20854 the demangler."),
20855                            NULL, show_check_physname,
20856                            &setdebuglist, &showdebuglist);
20857
20858   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20859                            no_class, &use_deprecated_index_sections, _("\
20860 Set whether to use deprecated gdb_index sections."), _("\
20861 Show whether to use deprecated gdb_index sections."), _("\
20862 When enabled, deprecated .gdb_index sections are used anyway.\n\
20863 Normally they are ignored either because of a missing feature or\n\
20864 performance issue.\n\
20865 Warning: This option must be enabled before gdb reads the file."),
20866                            NULL,
20867                            NULL,
20868                            &setlist, &showlist);
20869
20870   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20871                _("\
20872 Save a gdb-index file.\n\
20873 Usage: save gdb-index DIRECTORY"),
20874                &save_cmdlist);
20875   set_cmd_completer (c, filename_completer);
20876
20877   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
20878                                                         &dwarf2_locexpr_funcs);
20879   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
20880                                                         &dwarf2_loclist_funcs);
20881
20882   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
20883                                         &dwarf2_block_frame_base_locexpr_funcs);
20884   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
20885                                         &dwarf2_block_frame_base_loclist_funcs);
20886 }