* dwarf2read.c (create_debug_types_hash_table): Use hex_string
[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 %s"),
4321                          offset.sect_off, dup_offset.sect_off,
4322                          hex_string (signature));
4323             }
4324           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4325
4326           if (dwarf2_read_debug)
4327             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4328                                 offset.sect_off,
4329                                 hex_string (signature));
4330
4331           info_ptr += length;
4332         }
4333     }
4334
4335   return types_htab;
4336 }
4337
4338 /* Create the hash table of all entries in the .debug_types section,
4339    and initialize all_type_units.
4340    The result is zero if there is an error (e.g. missing .debug_types section),
4341    otherwise non-zero.  */
4342
4343 static int
4344 create_all_type_units (struct objfile *objfile)
4345 {
4346   htab_t types_htab;
4347   struct signatured_type **iter;
4348
4349   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4350   if (types_htab == NULL)
4351     {
4352       dwarf2_per_objfile->signatured_types = NULL;
4353       return 0;
4354     }
4355
4356   dwarf2_per_objfile->signatured_types = types_htab;
4357
4358   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4359   dwarf2_per_objfile->all_type_units
4360     = 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, hex_string (signature),
4638              this_cu->objfile->name);
4639     }
4640
4641   return dwo_unit;
4642 }
4643
4644 /* Initialize a CU (or TU) and read its DIEs.
4645    If the CU defers to a DWO file, read the DWO file as well.
4646
4647    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4648    Otherwise the table specified in the comp unit header is read in and used.
4649    This is an optimization for when we already have the abbrev table.
4650
4651    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4652    Otherwise, a new CU is allocated with xmalloc.
4653
4654    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4655    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4656
4657    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4658    linker) then DIE_READER_FUNC will not get called.  */
4659
4660 static void
4661 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4662                          struct abbrev_table *abbrev_table,
4663                          int use_existing_cu, int keep,
4664                          die_reader_func_ftype *die_reader_func,
4665                          void *data)
4666 {
4667   struct objfile *objfile = dwarf2_per_objfile->objfile;
4668   struct dwarf2_section_info *section = this_cu->section;
4669   bfd *abfd = section->asection->owner;
4670   struct dwarf2_cu *cu;
4671   const gdb_byte *begin_info_ptr, *info_ptr;
4672   struct die_reader_specs reader;
4673   struct die_info *comp_unit_die;
4674   int has_children;
4675   struct attribute *attr;
4676   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4677   struct signatured_type *sig_type = NULL;
4678   struct dwarf2_section_info *abbrev_section;
4679   /* Non-zero if CU currently points to a DWO file and we need to
4680      reread it.  When this happens we need to reread the skeleton die
4681      before we can reread the DWO file.  */
4682   int rereading_dwo_cu = 0;
4683
4684   if (dwarf2_die_debug)
4685     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4686                         this_cu->is_debug_types ? "type" : "comp",
4687                         this_cu->offset.sect_off);
4688
4689   if (use_existing_cu)
4690     gdb_assert (keep);
4691
4692   cleanups = make_cleanup (null_cleanup, NULL);
4693
4694   /* This is cheap if the section is already read in.  */
4695   dwarf2_read_section (objfile, section);
4696
4697   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4698
4699   abbrev_section = get_abbrev_section_for_cu (this_cu);
4700
4701   if (use_existing_cu && this_cu->cu != NULL)
4702     {
4703       cu = this_cu->cu;
4704
4705       /* If this CU is from a DWO file we need to start over, we need to
4706          refetch the attributes from the skeleton CU.
4707          This could be optimized by retrieving those attributes from when we
4708          were here the first time: the previous comp_unit_die was stored in
4709          comp_unit_obstack.  But there's no data yet that we need this
4710          optimization.  */
4711       if (cu->dwo_unit != NULL)
4712         rereading_dwo_cu = 1;
4713     }
4714   else
4715     {
4716       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4717       gdb_assert (this_cu->cu == NULL);
4718
4719       cu = xmalloc (sizeof (*cu));
4720       init_one_comp_unit (cu, this_cu);
4721
4722       /* If an error occurs while loading, release our storage.  */
4723       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4724     }
4725
4726   /* Get the header.  */
4727   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4728     {
4729       /* We already have the header, there's no need to read it in again.  */
4730       info_ptr += cu->header.first_die_offset.cu_off;
4731     }
4732   else
4733     {
4734       if (this_cu->is_debug_types)
4735         {
4736           ULONGEST signature;
4737           cu_offset type_offset_in_tu;
4738
4739           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4740                                                     abbrev_section, info_ptr,
4741                                                     &signature,
4742                                                     &type_offset_in_tu);
4743
4744           /* Since per_cu is the first member of struct signatured_type,
4745              we can go from a pointer to one to a pointer to the other.  */
4746           sig_type = (struct signatured_type *) this_cu;
4747           gdb_assert (sig_type->signature == signature);
4748           gdb_assert (sig_type->type_offset_in_tu.cu_off
4749                       == type_offset_in_tu.cu_off);
4750           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4751
4752           /* LENGTH has not been set yet for type units if we're
4753              using .gdb_index.  */
4754           this_cu->length = get_cu_length (&cu->header);
4755
4756           /* Establish the type offset that can be used to lookup the type.  */
4757           sig_type->type_offset_in_section.sect_off =
4758             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4759         }
4760       else
4761         {
4762           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4763                                                     abbrev_section,
4764                                                     info_ptr, 0);
4765
4766           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4767           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4768         }
4769     }
4770
4771   /* Skip dummy compilation units.  */
4772   if (info_ptr >= begin_info_ptr + this_cu->length
4773       || peek_abbrev_code (abfd, info_ptr) == 0)
4774     {
4775       do_cleanups (cleanups);
4776       return;
4777     }
4778
4779   /* If we don't have them yet, read the abbrevs for this compilation unit.
4780      And if we need to read them now, make sure they're freed when we're
4781      done.  Note that it's important that if the CU had an abbrev table
4782      on entry we don't free it when we're done: Somewhere up the call stack
4783      it may be in use.  */
4784   if (abbrev_table != NULL)
4785     {
4786       gdb_assert (cu->abbrev_table == NULL);
4787       gdb_assert (cu->header.abbrev_offset.sect_off
4788                   == abbrev_table->offset.sect_off);
4789       cu->abbrev_table = abbrev_table;
4790     }
4791   else if (cu->abbrev_table == NULL)
4792     {
4793       dwarf2_read_abbrevs (cu, abbrev_section);
4794       make_cleanup (dwarf2_free_abbrev_table, cu);
4795     }
4796   else if (rereading_dwo_cu)
4797     {
4798       dwarf2_free_abbrev_table (cu);
4799       dwarf2_read_abbrevs (cu, abbrev_section);
4800     }
4801
4802   /* Read the top level CU/TU die.  */
4803   init_cu_die_reader (&reader, cu, section, NULL);
4804   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4805
4806   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
4807      from the DWO file.
4808      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
4809      DWO CU, that this test will fail (the attribute will not be present).  */
4810   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4811   if (attr)
4812     {
4813       struct dwo_unit *dwo_unit;
4814       struct die_info *dwo_comp_unit_die;
4815
4816       if (has_children)
4817         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4818                  " has children (offset 0x%x) [in module %s]"),
4819                this_cu->offset.sect_off, bfd_get_filename (abfd));
4820       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
4821       if (read_cutu_die_from_dwo (this_cu, dwo_unit,
4822                                   abbrev_table != NULL,
4823                                   comp_unit_die,
4824                                   &reader, &info_ptr,
4825                                   &dwo_comp_unit_die, &has_children) == 0)
4826         {
4827           /* Dummy die.  */
4828           do_cleanups (cleanups);
4829           return;
4830         }
4831       comp_unit_die = dwo_comp_unit_die;
4832     }
4833
4834   /* All of the above is setup for this call.  Yikes.  */
4835   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4836
4837   /* Done, clean up.  */
4838   if (free_cu_cleanup != NULL)
4839     {
4840       if (keep)
4841         {
4842           /* We've successfully allocated this compilation unit.  Let our
4843              caller clean it up when finished with it.  */
4844           discard_cleanups (free_cu_cleanup);
4845
4846           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4847              So we have to manually free the abbrev table.  */
4848           dwarf2_free_abbrev_table (cu);
4849
4850           /* Link this CU into read_in_chain.  */
4851           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4852           dwarf2_per_objfile->read_in_chain = this_cu;
4853         }
4854       else
4855         do_cleanups (free_cu_cleanup);
4856     }
4857
4858   do_cleanups (cleanups);
4859 }
4860
4861 /* Read CU/TU THIS_CU in section SECTION,
4862    but do not follow DW_AT_GNU_dwo_name if present.
4863    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4864    to have already done the lookup to find the DWO/DWP file).
4865
4866    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4867    THIS_CU->is_debug_types, but nothing else.
4868
4869    We fill in THIS_CU->length.
4870
4871    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4872    linker) then DIE_READER_FUNC will not get called.
4873
4874    THIS_CU->cu is always freed when done.
4875    This is done in order to not leave THIS_CU->cu in a state where we have
4876    to care whether it refers to the "main" CU or the DWO CU.  */
4877
4878 static void
4879 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4880                                    struct dwarf2_section_info *abbrev_section,
4881                                    struct dwo_file *dwo_file,
4882                                    die_reader_func_ftype *die_reader_func,
4883                                    void *data)
4884 {
4885   struct objfile *objfile = dwarf2_per_objfile->objfile;
4886   struct dwarf2_section_info *section = this_cu->section;
4887   bfd *abfd = section->asection->owner;
4888   struct dwarf2_cu cu;
4889   const gdb_byte *begin_info_ptr, *info_ptr;
4890   struct die_reader_specs reader;
4891   struct cleanup *cleanups;
4892   struct die_info *comp_unit_die;
4893   int has_children;
4894
4895   if (dwarf2_die_debug)
4896     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4897                         this_cu->is_debug_types ? "type" : "comp",
4898                         this_cu->offset.sect_off);
4899
4900   gdb_assert (this_cu->cu == NULL);
4901
4902   /* This is cheap if the section is already read in.  */
4903   dwarf2_read_section (objfile, section);
4904
4905   init_one_comp_unit (&cu, this_cu);
4906
4907   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4908
4909   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4910   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4911                                             abbrev_section, info_ptr,
4912                                             this_cu->is_debug_types);
4913
4914   this_cu->length = get_cu_length (&cu.header);
4915
4916   /* Skip dummy compilation units.  */
4917   if (info_ptr >= begin_info_ptr + this_cu->length
4918       || peek_abbrev_code (abfd, info_ptr) == 0)
4919     {
4920       do_cleanups (cleanups);
4921       return;
4922     }
4923
4924   dwarf2_read_abbrevs (&cu, abbrev_section);
4925   make_cleanup (dwarf2_free_abbrev_table, &cu);
4926
4927   init_cu_die_reader (&reader, &cu, section, dwo_file);
4928   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4929
4930   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4931
4932   do_cleanups (cleanups);
4933 }
4934
4935 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4936    does not lookup the specified DWO file.
4937    This cannot be used to read DWO files.
4938
4939    THIS_CU->cu is always freed when done.
4940    This is done in order to not leave THIS_CU->cu in a state where we have
4941    to care whether it refers to the "main" CU or the DWO CU.
4942    We can revisit this if the data shows there's a performance issue.  */
4943
4944 static void
4945 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4946                                 die_reader_func_ftype *die_reader_func,
4947                                 void *data)
4948 {
4949   init_cutu_and_read_dies_no_follow (this_cu,
4950                                      get_abbrev_section_for_cu (this_cu),
4951                                      NULL,
4952                                      die_reader_func, data);
4953 }
4954 \f
4955 /* Type Unit Groups.
4956
4957    Type Unit Groups are a way to collapse the set of all TUs (type units) into
4958    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
4959    so that all types coming from the same compilation (.o file) are grouped
4960    together.  A future step could be to put the types in the same symtab as
4961    the CU the types ultimately came from.  */
4962
4963 static hashval_t
4964 hash_type_unit_group (const void *item)
4965 {
4966   const struct type_unit_group *tu_group = item;
4967
4968   return hash_stmt_list_entry (&tu_group->hash);
4969 }
4970
4971 static int
4972 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
4973 {
4974   const struct type_unit_group *lhs = item_lhs;
4975   const struct type_unit_group *rhs = item_rhs;
4976
4977   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
4978 }
4979
4980 /* Allocate a hash table for type unit groups.  */
4981
4982 static htab_t
4983 allocate_type_unit_groups_table (void)
4984 {
4985   return htab_create_alloc_ex (3,
4986                                hash_type_unit_group,
4987                                eq_type_unit_group,
4988                                NULL,
4989                                &dwarf2_per_objfile->objfile->objfile_obstack,
4990                                hashtab_obstack_allocate,
4991                                dummy_obstack_deallocate);
4992 }
4993
4994 /* Type units that don't have DW_AT_stmt_list are grouped into their own
4995    partial symtabs.  We combine several TUs per psymtab to not let the size
4996    of any one psymtab grow too big.  */
4997 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
4998 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
4999
5000 /* Helper routine for get_type_unit_group.
5001    Create the type_unit_group object used to hold one or more TUs.  */
5002
5003 static struct type_unit_group *
5004 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5005 {
5006   struct objfile *objfile = dwarf2_per_objfile->objfile;
5007   struct dwarf2_per_cu_data *per_cu;
5008   struct type_unit_group *tu_group;
5009
5010   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5011                              struct type_unit_group);
5012   per_cu = &tu_group->per_cu;
5013   per_cu->objfile = objfile;
5014
5015   if (dwarf2_per_objfile->using_index)
5016     {
5017       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5018                                         struct dwarf2_per_cu_quick_data);
5019     }
5020   else
5021     {
5022       unsigned int line_offset = line_offset_struct.sect_off;
5023       struct partial_symtab *pst;
5024       char *name;
5025
5026       /* Give the symtab a useful name for debug purposes.  */
5027       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5028         name = xstrprintf ("<type_units_%d>",
5029                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5030       else
5031         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5032
5033       pst = create_partial_symtab (per_cu, name);
5034       pst->anonymous = 1;
5035
5036       xfree (name);
5037     }
5038
5039   tu_group->hash.dwo_unit = cu->dwo_unit;
5040   tu_group->hash.line_offset = line_offset_struct;
5041
5042   return tu_group;
5043 }
5044
5045 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5046    STMT_LIST is a DW_AT_stmt_list attribute.  */
5047
5048 static struct type_unit_group *
5049 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5050 {
5051   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5052   struct type_unit_group *tu_group;
5053   void **slot;
5054   unsigned int line_offset;
5055   struct type_unit_group type_unit_group_for_lookup;
5056
5057   if (dwarf2_per_objfile->type_unit_groups == NULL)
5058     {
5059       dwarf2_per_objfile->type_unit_groups =
5060         allocate_type_unit_groups_table ();
5061     }
5062
5063   /* Do we need to create a new group, or can we use an existing one?  */
5064
5065   if (stmt_list)
5066     {
5067       line_offset = DW_UNSND (stmt_list);
5068       ++tu_stats->nr_symtab_sharers;
5069     }
5070   else
5071     {
5072       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5073          We can do various things here like create one group per TU or
5074          spread them over multiple groups to split up the expansion work.
5075          To avoid worst case scenarios (too many groups or too large groups)
5076          we, umm, group them in bunches.  */
5077       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5078                      | (tu_stats->nr_stmt_less_type_units
5079                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5080       ++tu_stats->nr_stmt_less_type_units;
5081     }
5082
5083   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5084   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5085   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5086                          &type_unit_group_for_lookup, INSERT);
5087   if (*slot != NULL)
5088     {
5089       tu_group = *slot;
5090       gdb_assert (tu_group != NULL);
5091     }
5092   else
5093     {
5094       sect_offset line_offset_struct;
5095
5096       line_offset_struct.sect_off = line_offset;
5097       tu_group = create_type_unit_group (cu, line_offset_struct);
5098       *slot = tu_group;
5099       ++tu_stats->nr_symtabs;
5100     }
5101
5102   return tu_group;
5103 }
5104
5105 /* Struct used to sort TUs by their abbreviation table offset.  */
5106
5107 struct tu_abbrev_offset
5108 {
5109   struct signatured_type *sig_type;
5110   sect_offset abbrev_offset;
5111 };
5112
5113 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5114
5115 static int
5116 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5117 {
5118   const struct tu_abbrev_offset * const *a = ap;
5119   const struct tu_abbrev_offset * const *b = bp;
5120   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5121   unsigned int boff = (*b)->abbrev_offset.sect_off;
5122
5123   return (aoff > boff) - (aoff < boff);
5124 }
5125
5126 /* A helper function to add a type_unit_group to a table.  */
5127
5128 static int
5129 add_type_unit_group_to_table (void **slot, void *datum)
5130 {
5131   struct type_unit_group *tu_group = *slot;
5132   struct type_unit_group ***datap = datum;
5133
5134   **datap = tu_group;
5135   ++*datap;
5136
5137   return 1;
5138 }
5139
5140 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5141    each one passing FUNC,DATA.
5142
5143    The efficiency is because we sort TUs by the abbrev table they use and
5144    only read each abbrev table once.  In one program there are 200K TUs
5145    sharing 8K abbrev tables.
5146
5147    The main purpose of this function is to support building the
5148    dwarf2_per_objfile->type_unit_groups table.
5149    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5150    can collapse the search space by grouping them by stmt_list.
5151    The savings can be significant, in the same program from above the 200K TUs
5152    share 8K stmt_list tables.
5153
5154    FUNC is expected to call get_type_unit_group, which will create the
5155    struct type_unit_group if necessary and add it to
5156    dwarf2_per_objfile->type_unit_groups.  */
5157
5158 static void
5159 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5160 {
5161   struct objfile *objfile = dwarf2_per_objfile->objfile;
5162   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5163   struct cleanup *cleanups;
5164   struct abbrev_table *abbrev_table;
5165   sect_offset abbrev_offset;
5166   struct tu_abbrev_offset *sorted_by_abbrev;
5167   struct type_unit_group **iter;
5168   int i;
5169
5170   /* It's up to the caller to not call us multiple times.  */
5171   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5172
5173   if (dwarf2_per_objfile->n_type_units == 0)
5174     return;
5175
5176   /* TUs typically share abbrev tables, and there can be way more TUs than
5177      abbrev tables.  Sort by abbrev table to reduce the number of times we
5178      read each abbrev table in.
5179      Alternatives are to punt or to maintain a cache of abbrev tables.
5180      This is simpler and efficient enough for now.
5181
5182      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5183      symtab to use).  Typically TUs with the same abbrev offset have the same
5184      stmt_list value too so in practice this should work well.
5185
5186      The basic algorithm here is:
5187
5188       sort TUs by abbrev table
5189       for each TU with same abbrev table:
5190         read abbrev table if first user
5191         read TU top level DIE
5192           [IWBN if DWO skeletons had DW_AT_stmt_list]
5193         call FUNC  */
5194
5195   if (dwarf2_read_debug)
5196     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5197
5198   /* Sort in a separate table to maintain the order of all_type_units
5199      for .gdb_index: TU indices directly index all_type_units.  */
5200   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5201                               dwarf2_per_objfile->n_type_units);
5202   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5203     {
5204       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5205
5206       sorted_by_abbrev[i].sig_type = sig_type;
5207       sorted_by_abbrev[i].abbrev_offset =
5208         read_abbrev_offset (sig_type->per_cu.section,
5209                             sig_type->per_cu.offset);
5210     }
5211   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5212   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5213          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5214
5215   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5216      called any number of times, so we don't reset tu_stats here.  */
5217
5218   abbrev_offset.sect_off = ~(unsigned) 0;
5219   abbrev_table = NULL;
5220   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5221
5222   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5223     {
5224       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5225
5226       /* Switch to the next abbrev table if necessary.  */
5227       if (abbrev_table == NULL
5228           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5229         {
5230           if (abbrev_table != NULL)
5231             {
5232               abbrev_table_free (abbrev_table);
5233               /* Reset to NULL in case abbrev_table_read_table throws
5234                  an error: abbrev_table_free_cleanup will get called.  */
5235               abbrev_table = NULL;
5236             }
5237           abbrev_offset = tu->abbrev_offset;
5238           abbrev_table =
5239             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5240                                      abbrev_offset);
5241           ++tu_stats->nr_uniq_abbrev_tables;
5242         }
5243
5244       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5245                                func, data);
5246     }
5247
5248   /* Create a vector of pointers to primary type units to make it easy to
5249      iterate over them and CUs.  See dw2_get_primary_cu.  */
5250   dwarf2_per_objfile->n_type_unit_groups =
5251     htab_elements (dwarf2_per_objfile->type_unit_groups);
5252   dwarf2_per_objfile->all_type_unit_groups =
5253     obstack_alloc (&objfile->objfile_obstack,
5254                    dwarf2_per_objfile->n_type_unit_groups
5255                    * sizeof (struct type_unit_group *));
5256   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5257   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5258                           add_type_unit_group_to_table, &iter);
5259   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5260               == dwarf2_per_objfile->n_type_unit_groups);
5261
5262   do_cleanups (cleanups);
5263
5264   if (dwarf2_read_debug)
5265     {
5266       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5267       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5268                           dwarf2_per_objfile->n_type_units);
5269       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5270                           tu_stats->nr_uniq_abbrev_tables);
5271       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5272                           tu_stats->nr_symtabs);
5273       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5274                           tu_stats->nr_symtab_sharers);
5275       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5276                           tu_stats->nr_stmt_less_type_units);
5277     }
5278 }
5279 \f
5280 /* Partial symbol tables.  */
5281
5282 /* Create a psymtab named NAME and assign it to PER_CU.
5283
5284    The caller must fill in the following details:
5285    dirname, textlow, texthigh.  */
5286
5287 static struct partial_symtab *
5288 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5289 {
5290   struct objfile *objfile = per_cu->objfile;
5291   struct partial_symtab *pst;
5292
5293   pst = start_psymtab_common (objfile, objfile->section_offsets,
5294                               name, 0,
5295                               objfile->global_psymbols.next,
5296                               objfile->static_psymbols.next);
5297
5298   pst->psymtabs_addrmap_supported = 1;
5299
5300   /* This is the glue that links PST into GDB's symbol API.  */
5301   pst->read_symtab_private = per_cu;
5302   pst->read_symtab = dwarf2_read_symtab;
5303   per_cu->v.psymtab = pst;
5304
5305   return pst;
5306 }
5307
5308 /* die_reader_func for process_psymtab_comp_unit.  */
5309
5310 static void
5311 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5312                                   const gdb_byte *info_ptr,
5313                                   struct die_info *comp_unit_die,
5314                                   int has_children,
5315                                   void *data)
5316 {
5317   struct dwarf2_cu *cu = reader->cu;
5318   struct objfile *objfile = cu->objfile;
5319   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5320   struct attribute *attr;
5321   CORE_ADDR baseaddr;
5322   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5323   struct partial_symtab *pst;
5324   int has_pc_info;
5325   const char *filename;
5326   int *want_partial_unit_ptr = data;
5327
5328   if (comp_unit_die->tag == DW_TAG_partial_unit
5329       && (want_partial_unit_ptr == NULL
5330           || !*want_partial_unit_ptr))
5331     return;
5332
5333   gdb_assert (! per_cu->is_debug_types);
5334
5335   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5336
5337   cu->list_in_scope = &file_symbols;
5338
5339   /* Allocate a new partial symbol table structure.  */
5340   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5341   if (attr == NULL || !DW_STRING (attr))
5342     filename = "";
5343   else
5344     filename = DW_STRING (attr);
5345
5346   pst = create_partial_symtab (per_cu, filename);
5347
5348   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5349   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5350   if (attr != NULL)
5351     pst->dirname = DW_STRING (attr);
5352
5353   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5354
5355   dwarf2_find_base_address (comp_unit_die, cu);
5356
5357   /* Possibly set the default values of LOWPC and HIGHPC from
5358      `DW_AT_ranges'.  */
5359   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5360                                       &best_highpc, cu, pst);
5361   if (has_pc_info == 1 && best_lowpc < best_highpc)
5362     /* Store the contiguous range if it is not empty; it can be empty for
5363        CUs with no code.  */
5364     addrmap_set_empty (objfile->psymtabs_addrmap,
5365                        best_lowpc + baseaddr,
5366                        best_highpc + baseaddr - 1, pst);
5367
5368   /* Check if comp unit has_children.
5369      If so, read the rest of the partial symbols from this comp unit.
5370      If not, there's no more debug_info for this comp unit.  */
5371   if (has_children)
5372     {
5373       struct partial_die_info *first_die;
5374       CORE_ADDR lowpc, highpc;
5375
5376       lowpc = ((CORE_ADDR) -1);
5377       highpc = ((CORE_ADDR) 0);
5378
5379       first_die = load_partial_dies (reader, info_ptr, 1);
5380
5381       scan_partial_symbols (first_die, &lowpc, &highpc,
5382                             ! has_pc_info, cu);
5383
5384       /* If we didn't find a lowpc, set it to highpc to avoid
5385          complaints from `maint check'.  */
5386       if (lowpc == ((CORE_ADDR) -1))
5387         lowpc = highpc;
5388
5389       /* If the compilation unit didn't have an explicit address range,
5390          then use the information extracted from its child dies.  */
5391       if (! has_pc_info)
5392         {
5393           best_lowpc = lowpc;
5394           best_highpc = highpc;
5395         }
5396     }
5397   pst->textlow = best_lowpc + baseaddr;
5398   pst->texthigh = best_highpc + baseaddr;
5399
5400   pst->n_global_syms = objfile->global_psymbols.next -
5401     (objfile->global_psymbols.list + pst->globals_offset);
5402   pst->n_static_syms = objfile->static_psymbols.next -
5403     (objfile->static_psymbols.list + pst->statics_offset);
5404   sort_pst_symbols (objfile, pst);
5405
5406   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5407     {
5408       int i;
5409       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5410       struct dwarf2_per_cu_data *iter;
5411
5412       /* Fill in 'dependencies' here; we fill in 'users' in a
5413          post-pass.  */
5414       pst->number_of_dependencies = len;
5415       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5416                                          len * sizeof (struct symtab *));
5417       for (i = 0;
5418            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5419                         i, iter);
5420            ++i)
5421         pst->dependencies[i] = iter->v.psymtab;
5422
5423       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5424     }
5425
5426   /* Get the list of files included in the current compilation unit,
5427      and build a psymtab for each of them.  */
5428   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5429
5430   if (dwarf2_read_debug)
5431     {
5432       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5433
5434       fprintf_unfiltered (gdb_stdlog,
5435                           "Psymtab for %s unit @0x%x: %s - %s"
5436                           ", %d global, %d static syms\n",
5437                           per_cu->is_debug_types ? "type" : "comp",
5438                           per_cu->offset.sect_off,
5439                           paddress (gdbarch, pst->textlow),
5440                           paddress (gdbarch, pst->texthigh),
5441                           pst->n_global_syms, pst->n_static_syms);
5442     }
5443 }
5444
5445 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5446    Process compilation unit THIS_CU for a psymtab.  */
5447
5448 static void
5449 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5450                            int want_partial_unit)
5451 {
5452   /* If this compilation unit was already read in, free the
5453      cached copy in order to read it in again.  This is
5454      necessary because we skipped some symbols when we first
5455      read in the compilation unit (see load_partial_dies).
5456      This problem could be avoided, but the benefit is unclear.  */
5457   if (this_cu->cu != NULL)
5458     free_one_cached_comp_unit (this_cu);
5459
5460   gdb_assert (! this_cu->is_debug_types);
5461   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5462                            process_psymtab_comp_unit_reader,
5463                            &want_partial_unit);
5464
5465   /* Age out any secondary CUs.  */
5466   age_cached_comp_units ();
5467 }
5468
5469 /* Reader function for build_type_psymtabs.  */
5470
5471 static void
5472 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5473                             const gdb_byte *info_ptr,
5474                             struct die_info *type_unit_die,
5475                             int has_children,
5476                             void *data)
5477 {
5478   struct objfile *objfile = dwarf2_per_objfile->objfile;
5479   struct dwarf2_cu *cu = reader->cu;
5480   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5481   struct signatured_type *sig_type;
5482   struct type_unit_group *tu_group;
5483   struct attribute *attr;
5484   struct partial_die_info *first_die;
5485   CORE_ADDR lowpc, highpc;
5486   struct partial_symtab *pst;
5487
5488   gdb_assert (data == NULL);
5489   gdb_assert (per_cu->is_debug_types);
5490   sig_type = (struct signatured_type *) per_cu;
5491
5492   if (! has_children)
5493     return;
5494
5495   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5496   tu_group = get_type_unit_group (cu, attr);
5497
5498   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
5499
5500   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5501   cu->list_in_scope = &file_symbols;
5502   pst = create_partial_symtab (per_cu, "");
5503   pst->anonymous = 1;
5504
5505   first_die = load_partial_dies (reader, info_ptr, 1);
5506
5507   lowpc = (CORE_ADDR) -1;
5508   highpc = (CORE_ADDR) 0;
5509   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5510
5511   pst->n_global_syms = objfile->global_psymbols.next -
5512     (objfile->global_psymbols.list + pst->globals_offset);
5513   pst->n_static_syms = objfile->static_psymbols.next -
5514     (objfile->static_psymbols.list + pst->statics_offset);
5515   sort_pst_symbols (objfile, pst);
5516 }
5517
5518 /* Traversal function for build_type_psymtabs.  */
5519
5520 static int
5521 build_type_psymtab_dependencies (void **slot, void *info)
5522 {
5523   struct objfile *objfile = dwarf2_per_objfile->objfile;
5524   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5525   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5526   struct partial_symtab *pst = per_cu->v.psymtab;
5527   int len = VEC_length (sig_type_ptr, tu_group->tus);
5528   struct signatured_type *iter;
5529   int i;
5530
5531   gdb_assert (len > 0);
5532   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
5533
5534   pst->number_of_dependencies = len;
5535   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5536                                      len * sizeof (struct psymtab *));
5537   for (i = 0;
5538        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
5539        ++i)
5540     {
5541       gdb_assert (iter->per_cu.is_debug_types);
5542       pst->dependencies[i] = iter->per_cu.v.psymtab;
5543       iter->type_unit_group = tu_group;
5544     }
5545
5546   VEC_free (sig_type_ptr, tu_group->tus);
5547
5548   return 1;
5549 }
5550
5551 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5552    Build partial symbol tables for the .debug_types comp-units.  */
5553
5554 static void
5555 build_type_psymtabs (struct objfile *objfile)
5556 {
5557   if (! create_all_type_units (objfile))
5558     return;
5559
5560   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5561
5562   /* Now that all TUs have been processed we can fill in the dependencies.  */
5563   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5564                           build_type_psymtab_dependencies, NULL);
5565 }
5566
5567 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5568
5569 static void
5570 psymtabs_addrmap_cleanup (void *o)
5571 {
5572   struct objfile *objfile = o;
5573
5574   objfile->psymtabs_addrmap = NULL;
5575 }
5576
5577 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5578
5579 static void
5580 set_partial_user (struct objfile *objfile)
5581 {
5582   int i;
5583
5584   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5585     {
5586       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5587       struct partial_symtab *pst = per_cu->v.psymtab;
5588       int j;
5589
5590       if (pst == NULL)
5591         continue;
5592
5593       for (j = 0; j < pst->number_of_dependencies; ++j)
5594         {
5595           /* Set the 'user' field only if it is not already set.  */
5596           if (pst->dependencies[j]->user == NULL)
5597             pst->dependencies[j]->user = pst;
5598         }
5599     }
5600 }
5601
5602 /* Build the partial symbol table by doing a quick pass through the
5603    .debug_info and .debug_abbrev sections.  */
5604
5605 static void
5606 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5607 {
5608   struct cleanup *back_to, *addrmap_cleanup;
5609   struct obstack temp_obstack;
5610   int i;
5611
5612   if (dwarf2_read_debug)
5613     {
5614       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5615                           objfile->name);
5616     }
5617
5618   dwarf2_per_objfile->reading_partial_symbols = 1;
5619
5620   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5621
5622   /* Any cached compilation units will be linked by the per-objfile
5623      read_in_chain.  Make sure to free them when we're done.  */
5624   back_to = make_cleanup (free_cached_comp_units, NULL);
5625
5626   build_type_psymtabs (objfile);
5627
5628   create_all_comp_units (objfile);
5629
5630   /* Create a temporary address map on a temporary obstack.  We later
5631      copy this to the final obstack.  */
5632   obstack_init (&temp_obstack);
5633   make_cleanup_obstack_free (&temp_obstack);
5634   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5635   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5636
5637   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5638     {
5639       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5640
5641       process_psymtab_comp_unit (per_cu, 0);
5642     }
5643
5644   set_partial_user (objfile);
5645
5646   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5647                                                     &objfile->objfile_obstack);
5648   discard_cleanups (addrmap_cleanup);
5649
5650   do_cleanups (back_to);
5651
5652   if (dwarf2_read_debug)
5653     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5654                         objfile->name);
5655 }
5656
5657 /* die_reader_func for load_partial_comp_unit.  */
5658
5659 static void
5660 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5661                                const gdb_byte *info_ptr,
5662                                struct die_info *comp_unit_die,
5663                                int has_children,
5664                                void *data)
5665 {
5666   struct dwarf2_cu *cu = reader->cu;
5667
5668   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5669
5670   /* Check if comp unit has_children.
5671      If so, read the rest of the partial symbols from this comp unit.
5672      If not, there's no more debug_info for this comp unit.  */
5673   if (has_children)
5674     load_partial_dies (reader, info_ptr, 0);
5675 }
5676
5677 /* Load the partial DIEs for a secondary CU into memory.
5678    This is also used when rereading a primary CU with load_all_dies.  */
5679
5680 static void
5681 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5682 {
5683   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5684                            load_partial_comp_unit_reader, NULL);
5685 }
5686
5687 static void
5688 read_comp_units_from_section (struct objfile *objfile,
5689                               struct dwarf2_section_info *section,
5690                               unsigned int is_dwz,
5691                               int *n_allocated,
5692                               int *n_comp_units,
5693                               struct dwarf2_per_cu_data ***all_comp_units)
5694 {
5695   const gdb_byte *info_ptr;
5696   bfd *abfd = section->asection->owner;
5697
5698   if (dwarf2_read_debug)
5699     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
5700                         section->asection->name, bfd_get_filename (abfd));
5701
5702   dwarf2_read_section (objfile, section);
5703
5704   info_ptr = section->buffer;
5705
5706   while (info_ptr < section->buffer + section->size)
5707     {
5708       unsigned int length, initial_length_size;
5709       struct dwarf2_per_cu_data *this_cu;
5710       sect_offset offset;
5711
5712       offset.sect_off = info_ptr - section->buffer;
5713
5714       /* Read just enough information to find out where the next
5715          compilation unit is.  */
5716       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5717
5718       /* Save the compilation unit for later lookup.  */
5719       this_cu = obstack_alloc (&objfile->objfile_obstack,
5720                                sizeof (struct dwarf2_per_cu_data));
5721       memset (this_cu, 0, sizeof (*this_cu));
5722       this_cu->offset = offset;
5723       this_cu->length = length + initial_length_size;
5724       this_cu->is_dwz = is_dwz;
5725       this_cu->objfile = objfile;
5726       this_cu->section = section;
5727
5728       if (*n_comp_units == *n_allocated)
5729         {
5730           *n_allocated *= 2;
5731           *all_comp_units = xrealloc (*all_comp_units,
5732                                       *n_allocated
5733                                       * sizeof (struct dwarf2_per_cu_data *));
5734         }
5735       (*all_comp_units)[*n_comp_units] = this_cu;
5736       ++*n_comp_units;
5737
5738       info_ptr = info_ptr + this_cu->length;
5739     }
5740 }
5741
5742 /* Create a list of all compilation units in OBJFILE.
5743    This is only done for -readnow and building partial symtabs.  */
5744
5745 static void
5746 create_all_comp_units (struct objfile *objfile)
5747 {
5748   int n_allocated;
5749   int n_comp_units;
5750   struct dwarf2_per_cu_data **all_comp_units;
5751
5752   n_comp_units = 0;
5753   n_allocated = 10;
5754   all_comp_units = xmalloc (n_allocated
5755                             * sizeof (struct dwarf2_per_cu_data *));
5756
5757   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5758                                 &n_allocated, &n_comp_units, &all_comp_units);
5759
5760   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5761     {
5762       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5763
5764       read_comp_units_from_section (objfile, &dwz->info, 1,
5765                                     &n_allocated, &n_comp_units,
5766                                     &all_comp_units);
5767     }
5768
5769   dwarf2_per_objfile->all_comp_units
5770     = obstack_alloc (&objfile->objfile_obstack,
5771                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5772   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5773           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5774   xfree (all_comp_units);
5775   dwarf2_per_objfile->n_comp_units = n_comp_units;
5776 }
5777
5778 /* Process all loaded DIEs for compilation unit CU, starting at
5779    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5780    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5781    DW_AT_ranges).  If NEED_PC is set, then this function will set
5782    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5783    and record the covered ranges in the addrmap.  */
5784
5785 static void
5786 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5787                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5788 {
5789   struct partial_die_info *pdi;
5790
5791   /* Now, march along the PDI's, descending into ones which have
5792      interesting children but skipping the children of the other ones,
5793      until we reach the end of the compilation unit.  */
5794
5795   pdi = first_die;
5796
5797   while (pdi != NULL)
5798     {
5799       fixup_partial_die (pdi, cu);
5800
5801       /* Anonymous namespaces or modules have no name but have interesting
5802          children, so we need to look at them.  Ditto for anonymous
5803          enums.  */
5804
5805       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5806           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5807           || pdi->tag == DW_TAG_imported_unit)
5808         {
5809           switch (pdi->tag)
5810             {
5811             case DW_TAG_subprogram:
5812               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5813               break;
5814             case DW_TAG_constant:
5815             case DW_TAG_variable:
5816             case DW_TAG_typedef:
5817             case DW_TAG_union_type:
5818               if (!pdi->is_declaration)
5819                 {
5820                   add_partial_symbol (pdi, cu);
5821                 }
5822               break;
5823             case DW_TAG_class_type:
5824             case DW_TAG_interface_type:
5825             case DW_TAG_structure_type:
5826               if (!pdi->is_declaration)
5827                 {
5828                   add_partial_symbol (pdi, cu);
5829                 }
5830               break;
5831             case DW_TAG_enumeration_type:
5832               if (!pdi->is_declaration)
5833                 add_partial_enumeration (pdi, cu);
5834               break;
5835             case DW_TAG_base_type:
5836             case DW_TAG_subrange_type:
5837               /* File scope base type definitions are added to the partial
5838                  symbol table.  */
5839               add_partial_symbol (pdi, cu);
5840               break;
5841             case DW_TAG_namespace:
5842               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5843               break;
5844             case DW_TAG_module:
5845               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5846               break;
5847             case DW_TAG_imported_unit:
5848               {
5849                 struct dwarf2_per_cu_data *per_cu;
5850
5851                 /* For now we don't handle imported units in type units.  */
5852                 if (cu->per_cu->is_debug_types)
5853                   {
5854                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5855                              " supported in type units [in module %s]"),
5856                            cu->objfile->name);
5857                   }
5858
5859                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5860                                                            pdi->is_dwz,
5861                                                            cu->objfile);
5862
5863                 /* Go read the partial unit, if needed.  */
5864                 if (per_cu->v.psymtab == NULL)
5865                   process_psymtab_comp_unit (per_cu, 1);
5866
5867                 VEC_safe_push (dwarf2_per_cu_ptr,
5868                                cu->per_cu->imported_symtabs, per_cu);
5869               }
5870               break;
5871             default:
5872               break;
5873             }
5874         }
5875
5876       /* If the die has a sibling, skip to the sibling.  */
5877
5878       pdi = pdi->die_sibling;
5879     }
5880 }
5881
5882 /* Functions used to compute the fully scoped name of a partial DIE.
5883
5884    Normally, this is simple.  For C++, the parent DIE's fully scoped
5885    name is concatenated with "::" and the partial DIE's name.  For
5886    Java, the same thing occurs except that "." is used instead of "::".
5887    Enumerators are an exception; they use the scope of their parent
5888    enumeration type, i.e. the name of the enumeration type is not
5889    prepended to the enumerator.
5890
5891    There are two complexities.  One is DW_AT_specification; in this
5892    case "parent" means the parent of the target of the specification,
5893    instead of the direct parent of the DIE.  The other is compilers
5894    which do not emit DW_TAG_namespace; in this case we try to guess
5895    the fully qualified name of structure types from their members'
5896    linkage names.  This must be done using the DIE's children rather
5897    than the children of any DW_AT_specification target.  We only need
5898    to do this for structures at the top level, i.e. if the target of
5899    any DW_AT_specification (if any; otherwise the DIE itself) does not
5900    have a parent.  */
5901
5902 /* Compute the scope prefix associated with PDI's parent, in
5903    compilation unit CU.  The result will be allocated on CU's
5904    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5905    field.  NULL is returned if no prefix is necessary.  */
5906 static const char *
5907 partial_die_parent_scope (struct partial_die_info *pdi,
5908                           struct dwarf2_cu *cu)
5909 {
5910   const char *grandparent_scope;
5911   struct partial_die_info *parent, *real_pdi;
5912
5913   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5914      then this means the parent of the specification DIE.  */
5915
5916   real_pdi = pdi;
5917   while (real_pdi->has_specification)
5918     real_pdi = find_partial_die (real_pdi->spec_offset,
5919                                  real_pdi->spec_is_dwz, cu);
5920
5921   parent = real_pdi->die_parent;
5922   if (parent == NULL)
5923     return NULL;
5924
5925   if (parent->scope_set)
5926     return parent->scope;
5927
5928   fixup_partial_die (parent, cu);
5929
5930   grandparent_scope = partial_die_parent_scope (parent, cu);
5931
5932   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5933      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5934      Work around this problem here.  */
5935   if (cu->language == language_cplus
5936       && parent->tag == DW_TAG_namespace
5937       && strcmp (parent->name, "::") == 0
5938       && grandparent_scope == NULL)
5939     {
5940       parent->scope = NULL;
5941       parent->scope_set = 1;
5942       return NULL;
5943     }
5944
5945   if (pdi->tag == DW_TAG_enumerator)
5946     /* Enumerators should not get the name of the enumeration as a prefix.  */
5947     parent->scope = grandparent_scope;
5948   else if (parent->tag == DW_TAG_namespace
5949       || parent->tag == DW_TAG_module
5950       || parent->tag == DW_TAG_structure_type
5951       || parent->tag == DW_TAG_class_type
5952       || parent->tag == DW_TAG_interface_type
5953       || parent->tag == DW_TAG_union_type
5954       || parent->tag == DW_TAG_enumeration_type)
5955     {
5956       if (grandparent_scope == NULL)
5957         parent->scope = parent->name;
5958       else
5959         parent->scope = typename_concat (&cu->comp_unit_obstack,
5960                                          grandparent_scope,
5961                                          parent->name, 0, cu);
5962     }
5963   else
5964     {
5965       /* FIXME drow/2004-04-01: What should we be doing with
5966          function-local names?  For partial symbols, we should probably be
5967          ignoring them.  */
5968       complaint (&symfile_complaints,
5969                  _("unhandled containing DIE tag %d for DIE at %d"),
5970                  parent->tag, pdi->offset.sect_off);
5971       parent->scope = grandparent_scope;
5972     }
5973
5974   parent->scope_set = 1;
5975   return parent->scope;
5976 }
5977
5978 /* Return the fully scoped name associated with PDI, from compilation unit
5979    CU.  The result will be allocated with malloc.  */
5980
5981 static char *
5982 partial_die_full_name (struct partial_die_info *pdi,
5983                        struct dwarf2_cu *cu)
5984 {
5985   const char *parent_scope;
5986
5987   /* If this is a template instantiation, we can not work out the
5988      template arguments from partial DIEs.  So, unfortunately, we have
5989      to go through the full DIEs.  At least any work we do building
5990      types here will be reused if full symbols are loaded later.  */
5991   if (pdi->has_template_arguments)
5992     {
5993       fixup_partial_die (pdi, cu);
5994
5995       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5996         {
5997           struct die_info *die;
5998           struct attribute attr;
5999           struct dwarf2_cu *ref_cu = cu;
6000
6001           /* DW_FORM_ref_addr is using section offset.  */
6002           attr.name = 0;
6003           attr.form = DW_FORM_ref_addr;
6004           attr.u.unsnd = pdi->offset.sect_off;
6005           die = follow_die_ref (NULL, &attr, &ref_cu);
6006
6007           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6008         }
6009     }
6010
6011   parent_scope = partial_die_parent_scope (pdi, cu);
6012   if (parent_scope == NULL)
6013     return NULL;
6014   else
6015     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6016 }
6017
6018 static void
6019 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6020 {
6021   struct objfile *objfile = cu->objfile;
6022   CORE_ADDR addr = 0;
6023   const char *actual_name = NULL;
6024   CORE_ADDR baseaddr;
6025   char *built_actual_name;
6026
6027   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6028
6029   built_actual_name = partial_die_full_name (pdi, cu);
6030   if (built_actual_name != NULL)
6031     actual_name = built_actual_name;
6032
6033   if (actual_name == NULL)
6034     actual_name = pdi->name;
6035
6036   switch (pdi->tag)
6037     {
6038     case DW_TAG_subprogram:
6039       if (pdi->is_external || cu->language == language_ada)
6040         {
6041           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6042              of the global scope.  But in Ada, we want to be able to access
6043              nested procedures globally.  So all Ada subprograms are stored
6044              in the global scope.  */
6045           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6046              mst_text, objfile); */
6047           add_psymbol_to_list (actual_name, strlen (actual_name),
6048                                built_actual_name != NULL,
6049                                VAR_DOMAIN, LOC_BLOCK,
6050                                &objfile->global_psymbols,
6051                                0, pdi->lowpc + baseaddr,
6052                                cu->language, objfile);
6053         }
6054       else
6055         {
6056           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6057              mst_file_text, objfile); */
6058           add_psymbol_to_list (actual_name, strlen (actual_name),
6059                                built_actual_name != NULL,
6060                                VAR_DOMAIN, LOC_BLOCK,
6061                                &objfile->static_psymbols,
6062                                0, pdi->lowpc + baseaddr,
6063                                cu->language, objfile);
6064         }
6065       break;
6066     case DW_TAG_constant:
6067       {
6068         struct psymbol_allocation_list *list;
6069
6070         if (pdi->is_external)
6071           list = &objfile->global_psymbols;
6072         else
6073           list = &objfile->static_psymbols;
6074         add_psymbol_to_list (actual_name, strlen (actual_name),
6075                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6076                              list, 0, 0, cu->language, objfile);
6077       }
6078       break;
6079     case DW_TAG_variable:
6080       if (pdi->d.locdesc)
6081         addr = decode_locdesc (pdi->d.locdesc, cu);
6082
6083       if (pdi->d.locdesc
6084           && addr == 0
6085           && !dwarf2_per_objfile->has_section_at_zero)
6086         {
6087           /* A global or static variable may also have been stripped
6088              out by the linker if unused, in which case its address
6089              will be nullified; do not add such variables into partial
6090              symbol table then.  */
6091         }
6092       else if (pdi->is_external)
6093         {
6094           /* Global Variable.
6095              Don't enter into the minimal symbol tables as there is
6096              a minimal symbol table entry from the ELF symbols already.
6097              Enter into partial symbol table if it has a location
6098              descriptor or a type.
6099              If the location descriptor is missing, new_symbol will create
6100              a LOC_UNRESOLVED symbol, the address of the variable will then
6101              be determined from the minimal symbol table whenever the variable
6102              is referenced.
6103              The address for the partial symbol table entry is not
6104              used by GDB, but it comes in handy for debugging partial symbol
6105              table building.  */
6106
6107           if (pdi->d.locdesc || pdi->has_type)
6108             add_psymbol_to_list (actual_name, strlen (actual_name),
6109                                  built_actual_name != NULL,
6110                                  VAR_DOMAIN, LOC_STATIC,
6111                                  &objfile->global_psymbols,
6112                                  0, addr + baseaddr,
6113                                  cu->language, objfile);
6114         }
6115       else
6116         {
6117           /* Static Variable.  Skip symbols without location descriptors.  */
6118           if (pdi->d.locdesc == NULL)
6119             {
6120               xfree (built_actual_name);
6121               return;
6122             }
6123           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6124              mst_file_data, objfile); */
6125           add_psymbol_to_list (actual_name, strlen (actual_name),
6126                                built_actual_name != NULL,
6127                                VAR_DOMAIN, LOC_STATIC,
6128                                &objfile->static_psymbols,
6129                                0, addr + baseaddr,
6130                                cu->language, objfile);
6131         }
6132       break;
6133     case DW_TAG_typedef:
6134     case DW_TAG_base_type:
6135     case DW_TAG_subrange_type:
6136       add_psymbol_to_list (actual_name, strlen (actual_name),
6137                            built_actual_name != NULL,
6138                            VAR_DOMAIN, LOC_TYPEDEF,
6139                            &objfile->static_psymbols,
6140                            0, (CORE_ADDR) 0, cu->language, objfile);
6141       break;
6142     case DW_TAG_namespace:
6143       add_psymbol_to_list (actual_name, strlen (actual_name),
6144                            built_actual_name != NULL,
6145                            VAR_DOMAIN, LOC_TYPEDEF,
6146                            &objfile->global_psymbols,
6147                            0, (CORE_ADDR) 0, cu->language, objfile);
6148       break;
6149     case DW_TAG_class_type:
6150     case DW_TAG_interface_type:
6151     case DW_TAG_structure_type:
6152     case DW_TAG_union_type:
6153     case DW_TAG_enumeration_type:
6154       /* Skip external references.  The DWARF standard says in the section
6155          about "Structure, Union, and Class Type Entries": "An incomplete
6156          structure, union or class type is represented by a structure,
6157          union or class entry that does not have a byte size attribute
6158          and that has a DW_AT_declaration attribute."  */
6159       if (!pdi->has_byte_size && pdi->is_declaration)
6160         {
6161           xfree (built_actual_name);
6162           return;
6163         }
6164
6165       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6166          static vs. global.  */
6167       add_psymbol_to_list (actual_name, strlen (actual_name),
6168                            built_actual_name != NULL,
6169                            STRUCT_DOMAIN, LOC_TYPEDEF,
6170                            (cu->language == language_cplus
6171                             || cu->language == language_java)
6172                            ? &objfile->global_psymbols
6173                            : &objfile->static_psymbols,
6174                            0, (CORE_ADDR) 0, cu->language, objfile);
6175
6176       break;
6177     case DW_TAG_enumerator:
6178       add_psymbol_to_list (actual_name, strlen (actual_name),
6179                            built_actual_name != NULL,
6180                            VAR_DOMAIN, LOC_CONST,
6181                            (cu->language == language_cplus
6182                             || cu->language == language_java)
6183                            ? &objfile->global_psymbols
6184                            : &objfile->static_psymbols,
6185                            0, (CORE_ADDR) 0, cu->language, objfile);
6186       break;
6187     default:
6188       break;
6189     }
6190
6191   xfree (built_actual_name);
6192 }
6193
6194 /* Read a partial die corresponding to a namespace; also, add a symbol
6195    corresponding to that namespace to the symbol table.  NAMESPACE is
6196    the name of the enclosing namespace.  */
6197
6198 static void
6199 add_partial_namespace (struct partial_die_info *pdi,
6200                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6201                        int need_pc, struct dwarf2_cu *cu)
6202 {
6203   /* Add a symbol for the namespace.  */
6204
6205   add_partial_symbol (pdi, cu);
6206
6207   /* Now scan partial symbols in that namespace.  */
6208
6209   if (pdi->has_children)
6210     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6211 }
6212
6213 /* Read a partial die corresponding to a Fortran module.  */
6214
6215 static void
6216 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6217                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6218 {
6219   /* Now scan partial symbols in that module.  */
6220
6221   if (pdi->has_children)
6222     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6223 }
6224
6225 /* Read a partial die corresponding to a subprogram and create a partial
6226    symbol for that subprogram.  When the CU language allows it, this
6227    routine also defines a partial symbol for each nested subprogram
6228    that this subprogram contains.
6229
6230    DIE my also be a lexical block, in which case we simply search
6231    recursively for suprograms defined inside that lexical block.
6232    Again, this is only performed when the CU language allows this
6233    type of definitions.  */
6234
6235 static void
6236 add_partial_subprogram (struct partial_die_info *pdi,
6237                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6238                         int need_pc, struct dwarf2_cu *cu)
6239 {
6240   if (pdi->tag == DW_TAG_subprogram)
6241     {
6242       if (pdi->has_pc_info)
6243         {
6244           if (pdi->lowpc < *lowpc)
6245             *lowpc = pdi->lowpc;
6246           if (pdi->highpc > *highpc)
6247             *highpc = pdi->highpc;
6248           if (need_pc)
6249             {
6250               CORE_ADDR baseaddr;
6251               struct objfile *objfile = cu->objfile;
6252
6253               baseaddr = ANOFFSET (objfile->section_offsets,
6254                                    SECT_OFF_TEXT (objfile));
6255               addrmap_set_empty (objfile->psymtabs_addrmap,
6256                                  pdi->lowpc + baseaddr,
6257                                  pdi->highpc - 1 + baseaddr,
6258                                  cu->per_cu->v.psymtab);
6259             }
6260         }
6261
6262       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6263         {
6264           if (!pdi->is_declaration)
6265             /* Ignore subprogram DIEs that do not have a name, they are
6266                illegal.  Do not emit a complaint at this point, we will
6267                do so when we convert this psymtab into a symtab.  */
6268             if (pdi->name)
6269               add_partial_symbol (pdi, cu);
6270         }
6271     }
6272
6273   if (! pdi->has_children)
6274     return;
6275
6276   if (cu->language == language_ada)
6277     {
6278       pdi = pdi->die_child;
6279       while (pdi != NULL)
6280         {
6281           fixup_partial_die (pdi, cu);
6282           if (pdi->tag == DW_TAG_subprogram
6283               || pdi->tag == DW_TAG_lexical_block)
6284             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6285           pdi = pdi->die_sibling;
6286         }
6287     }
6288 }
6289
6290 /* Read a partial die corresponding to an enumeration type.  */
6291
6292 static void
6293 add_partial_enumeration (struct partial_die_info *enum_pdi,
6294                          struct dwarf2_cu *cu)
6295 {
6296   struct partial_die_info *pdi;
6297
6298   if (enum_pdi->name != NULL)
6299     add_partial_symbol (enum_pdi, cu);
6300
6301   pdi = enum_pdi->die_child;
6302   while (pdi)
6303     {
6304       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6305         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6306       else
6307         add_partial_symbol (pdi, cu);
6308       pdi = pdi->die_sibling;
6309     }
6310 }
6311
6312 /* Return the initial uleb128 in the die at INFO_PTR.  */
6313
6314 static unsigned int
6315 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6316 {
6317   unsigned int bytes_read;
6318
6319   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6320 }
6321
6322 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6323    Return the corresponding abbrev, or NULL if the number is zero (indicating
6324    an empty DIE).  In either case *BYTES_READ will be set to the length of
6325    the initial number.  */
6326
6327 static struct abbrev_info *
6328 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6329                  struct dwarf2_cu *cu)
6330 {
6331   bfd *abfd = cu->objfile->obfd;
6332   unsigned int abbrev_number;
6333   struct abbrev_info *abbrev;
6334
6335   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6336
6337   if (abbrev_number == 0)
6338     return NULL;
6339
6340   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6341   if (!abbrev)
6342     {
6343       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6344              abbrev_number, bfd_get_filename (abfd));
6345     }
6346
6347   return abbrev;
6348 }
6349
6350 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6351    Returns a pointer to the end of a series of DIEs, terminated by an empty
6352    DIE.  Any children of the skipped DIEs will also be skipped.  */
6353
6354 static const gdb_byte *
6355 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6356 {
6357   struct dwarf2_cu *cu = reader->cu;
6358   struct abbrev_info *abbrev;
6359   unsigned int bytes_read;
6360
6361   while (1)
6362     {
6363       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6364       if (abbrev == NULL)
6365         return info_ptr + bytes_read;
6366       else
6367         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6368     }
6369 }
6370
6371 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6372    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6373    abbrev corresponding to that skipped uleb128 should be passed in
6374    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6375    children.  */
6376
6377 static const gdb_byte *
6378 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6379               struct abbrev_info *abbrev)
6380 {
6381   unsigned int bytes_read;
6382   struct attribute attr;
6383   bfd *abfd = reader->abfd;
6384   struct dwarf2_cu *cu = reader->cu;
6385   const gdb_byte *buffer = reader->buffer;
6386   const gdb_byte *buffer_end = reader->buffer_end;
6387   const gdb_byte *start_info_ptr = info_ptr;
6388   unsigned int form, i;
6389
6390   for (i = 0; i < abbrev->num_attrs; i++)
6391     {
6392       /* The only abbrev we care about is DW_AT_sibling.  */
6393       if (abbrev->attrs[i].name == DW_AT_sibling)
6394         {
6395           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6396           if (attr.form == DW_FORM_ref_addr)
6397             complaint (&symfile_complaints,
6398                        _("ignoring absolute DW_AT_sibling"));
6399           else
6400             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6401         }
6402
6403       /* If it isn't DW_AT_sibling, skip this attribute.  */
6404       form = abbrev->attrs[i].form;
6405     skip_attribute:
6406       switch (form)
6407         {
6408         case DW_FORM_ref_addr:
6409           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6410              and later it is offset sized.  */
6411           if (cu->header.version == 2)
6412             info_ptr += cu->header.addr_size;
6413           else
6414             info_ptr += cu->header.offset_size;
6415           break;
6416         case DW_FORM_GNU_ref_alt:
6417           info_ptr += cu->header.offset_size;
6418           break;
6419         case DW_FORM_addr:
6420           info_ptr += cu->header.addr_size;
6421           break;
6422         case DW_FORM_data1:
6423         case DW_FORM_ref1:
6424         case DW_FORM_flag:
6425           info_ptr += 1;
6426           break;
6427         case DW_FORM_flag_present:
6428           break;
6429         case DW_FORM_data2:
6430         case DW_FORM_ref2:
6431           info_ptr += 2;
6432           break;
6433         case DW_FORM_data4:
6434         case DW_FORM_ref4:
6435           info_ptr += 4;
6436           break;
6437         case DW_FORM_data8:
6438         case DW_FORM_ref8:
6439         case DW_FORM_ref_sig8:
6440           info_ptr += 8;
6441           break;
6442         case DW_FORM_string:
6443           read_direct_string (abfd, info_ptr, &bytes_read);
6444           info_ptr += bytes_read;
6445           break;
6446         case DW_FORM_sec_offset:
6447         case DW_FORM_strp:
6448         case DW_FORM_GNU_strp_alt:
6449           info_ptr += cu->header.offset_size;
6450           break;
6451         case DW_FORM_exprloc:
6452         case DW_FORM_block:
6453           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6454           info_ptr += bytes_read;
6455           break;
6456         case DW_FORM_block1:
6457           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6458           break;
6459         case DW_FORM_block2:
6460           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6461           break;
6462         case DW_FORM_block4:
6463           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6464           break;
6465         case DW_FORM_sdata:
6466         case DW_FORM_udata:
6467         case DW_FORM_ref_udata:
6468         case DW_FORM_GNU_addr_index:
6469         case DW_FORM_GNU_str_index:
6470           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
6471           break;
6472         case DW_FORM_indirect:
6473           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6474           info_ptr += bytes_read;
6475           /* We need to continue parsing from here, so just go back to
6476              the top.  */
6477           goto skip_attribute;
6478
6479         default:
6480           error (_("Dwarf Error: Cannot handle %s "
6481                    "in DWARF reader [in module %s]"),
6482                  dwarf_form_name (form),
6483                  bfd_get_filename (abfd));
6484         }
6485     }
6486
6487   if (abbrev->has_children)
6488     return skip_children (reader, info_ptr);
6489   else
6490     return info_ptr;
6491 }
6492
6493 /* Locate ORIG_PDI's sibling.
6494    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6495
6496 static const gdb_byte *
6497 locate_pdi_sibling (const struct die_reader_specs *reader,
6498                     struct partial_die_info *orig_pdi,
6499                     const gdb_byte *info_ptr)
6500 {
6501   /* Do we know the sibling already?  */
6502
6503   if (orig_pdi->sibling)
6504     return orig_pdi->sibling;
6505
6506   /* Are there any children to deal with?  */
6507
6508   if (!orig_pdi->has_children)
6509     return info_ptr;
6510
6511   /* Skip the children the long way.  */
6512
6513   return skip_children (reader, info_ptr);
6514 }
6515
6516 /* Expand this partial symbol table into a full symbol table.  SELF is
6517    not NULL.  */
6518
6519 static void
6520 dwarf2_read_symtab (struct partial_symtab *self,
6521                     struct objfile *objfile)
6522 {
6523   if (self->readin)
6524     {
6525       warning (_("bug: psymtab for %s is already read in."),
6526                self->filename);
6527     }
6528   else
6529     {
6530       if (info_verbose)
6531         {
6532           printf_filtered (_("Reading in symbols for %s..."),
6533                            self->filename);
6534           gdb_flush (gdb_stdout);
6535         }
6536
6537       /* Restore our global data.  */
6538       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6539
6540       /* If this psymtab is constructed from a debug-only objfile, the
6541          has_section_at_zero flag will not necessarily be correct.  We
6542          can get the correct value for this flag by looking at the data
6543          associated with the (presumably stripped) associated objfile.  */
6544       if (objfile->separate_debug_objfile_backlink)
6545         {
6546           struct dwarf2_per_objfile *dpo_backlink
6547             = objfile_data (objfile->separate_debug_objfile_backlink,
6548                             dwarf2_objfile_data_key);
6549
6550           dwarf2_per_objfile->has_section_at_zero
6551             = dpo_backlink->has_section_at_zero;
6552         }
6553
6554       dwarf2_per_objfile->reading_partial_symbols = 0;
6555
6556       psymtab_to_symtab_1 (self);
6557
6558       /* Finish up the debug error message.  */
6559       if (info_verbose)
6560         printf_filtered (_("done.\n"));
6561     }
6562
6563   process_cu_includes ();
6564 }
6565 \f
6566 /* Reading in full CUs.  */
6567
6568 /* Add PER_CU to the queue.  */
6569
6570 static void
6571 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6572                  enum language pretend_language)
6573 {
6574   struct dwarf2_queue_item *item;
6575
6576   per_cu->queued = 1;
6577   item = xmalloc (sizeof (*item));
6578   item->per_cu = per_cu;
6579   item->pretend_language = pretend_language;
6580   item->next = NULL;
6581
6582   if (dwarf2_queue == NULL)
6583     dwarf2_queue = item;
6584   else
6585     dwarf2_queue_tail->next = item;
6586
6587   dwarf2_queue_tail = item;
6588 }
6589
6590 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6591    unit and add it to our queue.
6592    The result is non-zero if PER_CU was queued, otherwise the result is zero
6593    meaning either PER_CU is already queued or it is already loaded.  */
6594
6595 static int
6596 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6597                        struct dwarf2_per_cu_data *per_cu,
6598                        enum language pretend_language)
6599 {
6600   /* We may arrive here during partial symbol reading, if we need full
6601      DIEs to process an unusual case (e.g. template arguments).  Do
6602      not queue PER_CU, just tell our caller to load its DIEs.  */
6603   if (dwarf2_per_objfile->reading_partial_symbols)
6604     {
6605       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6606         return 1;
6607       return 0;
6608     }
6609
6610   /* Mark the dependence relation so that we don't flush PER_CU
6611      too early.  */
6612   dwarf2_add_dependence (this_cu, per_cu);
6613
6614   /* If it's already on the queue, we have nothing to do.  */
6615   if (per_cu->queued)
6616     return 0;
6617
6618   /* If the compilation unit is already loaded, just mark it as
6619      used.  */
6620   if (per_cu->cu != NULL)
6621     {
6622       per_cu->cu->last_used = 0;
6623       return 0;
6624     }
6625
6626   /* Add it to the queue.  */
6627   queue_comp_unit (per_cu, pretend_language);
6628
6629   return 1;
6630 }
6631
6632 /* Process the queue.  */
6633
6634 static void
6635 process_queue (void)
6636 {
6637   struct dwarf2_queue_item *item, *next_item;
6638
6639   if (dwarf2_read_debug)
6640     {
6641       fprintf_unfiltered (gdb_stdlog,
6642                           "Expanding one or more symtabs of objfile %s ...\n",
6643                           dwarf2_per_objfile->objfile->name);
6644     }
6645
6646   /* The queue starts out with one item, but following a DIE reference
6647      may load a new CU, adding it to the end of the queue.  */
6648   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6649     {
6650       if (dwarf2_per_objfile->using_index
6651           ? !item->per_cu->v.quick->symtab
6652           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6653         {
6654           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6655
6656           if (dwarf2_read_debug)
6657             {
6658               fprintf_unfiltered (gdb_stdlog,
6659                                   "Expanding symtab of %s at offset 0x%x\n",
6660                                   per_cu->is_debug_types ? "TU" : "CU",
6661                                   per_cu->offset.sect_off);
6662             }
6663
6664           if (per_cu->is_debug_types)
6665             process_full_type_unit (per_cu, item->pretend_language);
6666           else
6667             process_full_comp_unit (per_cu, item->pretend_language);
6668
6669           if (dwarf2_read_debug)
6670             {
6671               fprintf_unfiltered (gdb_stdlog,
6672                                   "Done expanding %s at offset 0x%x\n",
6673                                   per_cu->is_debug_types ? "TU" : "CU",
6674                                   per_cu->offset.sect_off);
6675             }
6676         }
6677
6678       item->per_cu->queued = 0;
6679       next_item = item->next;
6680       xfree (item);
6681     }
6682
6683   dwarf2_queue_tail = NULL;
6684
6685   if (dwarf2_read_debug)
6686     {
6687       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6688                           dwarf2_per_objfile->objfile->name);
6689     }
6690 }
6691
6692 /* Free all allocated queue entries.  This function only releases anything if
6693    an error was thrown; if the queue was processed then it would have been
6694    freed as we went along.  */
6695
6696 static void
6697 dwarf2_release_queue (void *dummy)
6698 {
6699   struct dwarf2_queue_item *item, *last;
6700
6701   item = dwarf2_queue;
6702   while (item)
6703     {
6704       /* Anything still marked queued is likely to be in an
6705          inconsistent state, so discard it.  */
6706       if (item->per_cu->queued)
6707         {
6708           if (item->per_cu->cu != NULL)
6709             free_one_cached_comp_unit (item->per_cu);
6710           item->per_cu->queued = 0;
6711         }
6712
6713       last = item;
6714       item = item->next;
6715       xfree (last);
6716     }
6717
6718   dwarf2_queue = dwarf2_queue_tail = NULL;
6719 }
6720
6721 /* Read in full symbols for PST, and anything it depends on.  */
6722
6723 static void
6724 psymtab_to_symtab_1 (struct partial_symtab *pst)
6725 {
6726   struct dwarf2_per_cu_data *per_cu;
6727   int i;
6728
6729   if (pst->readin)
6730     return;
6731
6732   for (i = 0; i < pst->number_of_dependencies; i++)
6733     if (!pst->dependencies[i]->readin
6734         && pst->dependencies[i]->user == NULL)
6735       {
6736         /* Inform about additional files that need to be read in.  */
6737         if (info_verbose)
6738           {
6739             /* FIXME: i18n: Need to make this a single string.  */
6740             fputs_filtered (" ", gdb_stdout);
6741             wrap_here ("");
6742             fputs_filtered ("and ", gdb_stdout);
6743             wrap_here ("");
6744             printf_filtered ("%s...", pst->dependencies[i]->filename);
6745             wrap_here ("");     /* Flush output.  */
6746             gdb_flush (gdb_stdout);
6747           }
6748         psymtab_to_symtab_1 (pst->dependencies[i]);
6749       }
6750
6751   per_cu = pst->read_symtab_private;
6752
6753   if (per_cu == NULL)
6754     {
6755       /* It's an include file, no symbols to read for it.
6756          Everything is in the parent symtab.  */
6757       pst->readin = 1;
6758       return;
6759     }
6760
6761   dw2_do_instantiate_symtab (per_cu);
6762 }
6763
6764 /* Trivial hash function for die_info: the hash value of a DIE
6765    is its offset in .debug_info for this objfile.  */
6766
6767 static hashval_t
6768 die_hash (const void *item)
6769 {
6770   const struct die_info *die = item;
6771
6772   return die->offset.sect_off;
6773 }
6774
6775 /* Trivial comparison function for die_info structures: two DIEs
6776    are equal if they have the same offset.  */
6777
6778 static int
6779 die_eq (const void *item_lhs, const void *item_rhs)
6780 {
6781   const struct die_info *die_lhs = item_lhs;
6782   const struct die_info *die_rhs = item_rhs;
6783
6784   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6785 }
6786
6787 /* die_reader_func for load_full_comp_unit.
6788    This is identical to read_signatured_type_reader,
6789    but is kept separate for now.  */
6790
6791 static void
6792 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6793                             const gdb_byte *info_ptr,
6794                             struct die_info *comp_unit_die,
6795                             int has_children,
6796                             void *data)
6797 {
6798   struct dwarf2_cu *cu = reader->cu;
6799   enum language *language_ptr = data;
6800
6801   gdb_assert (cu->die_hash == NULL);
6802   cu->die_hash =
6803     htab_create_alloc_ex (cu->header.length / 12,
6804                           die_hash,
6805                           die_eq,
6806                           NULL,
6807                           &cu->comp_unit_obstack,
6808                           hashtab_obstack_allocate,
6809                           dummy_obstack_deallocate);
6810
6811   if (has_children)
6812     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6813                                                   &info_ptr, comp_unit_die);
6814   cu->dies = comp_unit_die;
6815   /* comp_unit_die is not stored in die_hash, no need.  */
6816
6817   /* We try not to read any attributes in this function, because not
6818      all CUs needed for references have been loaded yet, and symbol
6819      table processing isn't initialized.  But we have to set the CU language,
6820      or we won't be able to build types correctly.
6821      Similarly, if we do not read the producer, we can not apply
6822      producer-specific interpretation.  */
6823   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6824 }
6825
6826 /* Load the DIEs associated with PER_CU into memory.  */
6827
6828 static void
6829 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6830                      enum language pretend_language)
6831 {
6832   gdb_assert (! this_cu->is_debug_types);
6833
6834   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6835                            load_full_comp_unit_reader, &pretend_language);
6836 }
6837
6838 /* Add a DIE to the delayed physname list.  */
6839
6840 static void
6841 add_to_method_list (struct type *type, int fnfield_index, int index,
6842                     const char *name, struct die_info *die,
6843                     struct dwarf2_cu *cu)
6844 {
6845   struct delayed_method_info mi;
6846   mi.type = type;
6847   mi.fnfield_index = fnfield_index;
6848   mi.index = index;
6849   mi.name = name;
6850   mi.die = die;
6851   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6852 }
6853
6854 /* A cleanup for freeing the delayed method list.  */
6855
6856 static void
6857 free_delayed_list (void *ptr)
6858 {
6859   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6860   if (cu->method_list != NULL)
6861     {
6862       VEC_free (delayed_method_info, cu->method_list);
6863       cu->method_list = NULL;
6864     }
6865 }
6866
6867 /* Compute the physnames of any methods on the CU's method list.
6868
6869    The computation of method physnames is delayed in order to avoid the
6870    (bad) condition that one of the method's formal parameters is of an as yet
6871    incomplete type.  */
6872
6873 static void
6874 compute_delayed_physnames (struct dwarf2_cu *cu)
6875 {
6876   int i;
6877   struct delayed_method_info *mi;
6878   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6879     {
6880       const char *physname;
6881       struct fn_fieldlist *fn_flp
6882         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6883       physname = dwarf2_physname (mi->name, mi->die, cu);
6884       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6885     }
6886 }
6887
6888 /* Go objects should be embedded in a DW_TAG_module DIE,
6889    and it's not clear if/how imported objects will appear.
6890    To keep Go support simple until that's worked out,
6891    go back through what we've read and create something usable.
6892    We could do this while processing each DIE, and feels kinda cleaner,
6893    but that way is more invasive.
6894    This is to, for example, allow the user to type "p var" or "b main"
6895    without having to specify the package name, and allow lookups
6896    of module.object to work in contexts that use the expression
6897    parser.  */
6898
6899 static void
6900 fixup_go_packaging (struct dwarf2_cu *cu)
6901 {
6902   char *package_name = NULL;
6903   struct pending *list;
6904   int i;
6905
6906   for (list = global_symbols; list != NULL; list = list->next)
6907     {
6908       for (i = 0; i < list->nsyms; ++i)
6909         {
6910           struct symbol *sym = list->symbol[i];
6911
6912           if (SYMBOL_LANGUAGE (sym) == language_go
6913               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6914             {
6915               char *this_package_name = go_symbol_package_name (sym);
6916
6917               if (this_package_name == NULL)
6918                 continue;
6919               if (package_name == NULL)
6920                 package_name = this_package_name;
6921               else
6922                 {
6923                   if (strcmp (package_name, this_package_name) != 0)
6924                     complaint (&symfile_complaints,
6925                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6926                                (SYMBOL_SYMTAB (sym)
6927                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
6928                                 : cu->objfile->name),
6929                                this_package_name, package_name);
6930                   xfree (this_package_name);
6931                 }
6932             }
6933         }
6934     }
6935
6936   if (package_name != NULL)
6937     {
6938       struct objfile *objfile = cu->objfile;
6939       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6940                                                       package_name,
6941                                                       strlen (package_name));
6942       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6943                                      saved_package_name, objfile);
6944       struct symbol *sym;
6945
6946       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6947
6948       sym = allocate_symbol (objfile);
6949       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
6950       SYMBOL_SET_NAMES (sym, saved_package_name,
6951                         strlen (saved_package_name), 0, objfile);
6952       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6953          e.g., "main" finds the "main" module and not C's main().  */
6954       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6955       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
6956       SYMBOL_TYPE (sym) = type;
6957
6958       add_symbol_to_list (sym, &global_symbols);
6959
6960       xfree (package_name);
6961     }
6962 }
6963
6964 /* Return the symtab for PER_CU.  This works properly regardless of
6965    whether we're using the index or psymtabs.  */
6966
6967 static struct symtab *
6968 get_symtab (struct dwarf2_per_cu_data *per_cu)
6969 {
6970   return (dwarf2_per_objfile->using_index
6971           ? per_cu->v.quick->symtab
6972           : per_cu->v.psymtab->symtab);
6973 }
6974
6975 /* A helper function for computing the list of all symbol tables
6976    included by PER_CU.  */
6977
6978 static void
6979 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6980                                 htab_t all_children,
6981                                 struct dwarf2_per_cu_data *per_cu)
6982 {
6983   void **slot;
6984   int ix;
6985   struct dwarf2_per_cu_data *iter;
6986
6987   slot = htab_find_slot (all_children, per_cu, INSERT);
6988   if (*slot != NULL)
6989     {
6990       /* This inclusion and its children have been processed.  */
6991       return;
6992     }
6993
6994   *slot = per_cu;
6995   /* Only add a CU if it has a symbol table.  */
6996   if (get_symtab (per_cu) != NULL)
6997     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6998
6999   for (ix = 0;
7000        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7001        ++ix)
7002     recursively_compute_inclusions (result, all_children, iter);
7003 }
7004
7005 /* Compute the symtab 'includes' fields for the symtab related to
7006    PER_CU.  */
7007
7008 static void
7009 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7010 {
7011   gdb_assert (! per_cu->is_debug_types);
7012
7013   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7014     {
7015       int ix, len;
7016       struct dwarf2_per_cu_data *iter;
7017       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
7018       htab_t all_children;
7019       struct symtab *symtab = get_symtab (per_cu);
7020
7021       /* If we don't have a symtab, we can just skip this case.  */
7022       if (symtab == NULL)
7023         return;
7024
7025       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7026                                         NULL, xcalloc, xfree);
7027
7028       for (ix = 0;
7029            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7030                         ix, iter);
7031            ++ix)
7032         recursively_compute_inclusions (&result_children, all_children, iter);
7033
7034       /* Now we have a transitive closure of all the included CUs, and
7035          for .gdb_index version 7 the included TUs, so we can convert it
7036          to a list of symtabs.  */
7037       len = VEC_length (dwarf2_per_cu_ptr, result_children);
7038       symtab->includes
7039         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7040                          (len + 1) * sizeof (struct symtab *));
7041       for (ix = 0;
7042            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
7043            ++ix)
7044         symtab->includes[ix] = get_symtab (iter);
7045       symtab->includes[len] = NULL;
7046
7047       VEC_free (dwarf2_per_cu_ptr, result_children);
7048       htab_delete (all_children);
7049     }
7050 }
7051
7052 /* Compute the 'includes' field for the symtabs of all the CUs we just
7053    read.  */
7054
7055 static void
7056 process_cu_includes (void)
7057 {
7058   int ix;
7059   struct dwarf2_per_cu_data *iter;
7060
7061   for (ix = 0;
7062        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7063                     ix, iter);
7064        ++ix)
7065     {
7066       if (! iter->is_debug_types)
7067         compute_symtab_includes (iter);
7068     }
7069
7070   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7071 }
7072
7073 /* Generate full symbol information for PER_CU, whose DIEs have
7074    already been loaded into memory.  */
7075
7076 static void
7077 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7078                         enum language pretend_language)
7079 {
7080   struct dwarf2_cu *cu = per_cu->cu;
7081   struct objfile *objfile = per_cu->objfile;
7082   CORE_ADDR lowpc, highpc;
7083   struct symtab *symtab;
7084   struct cleanup *back_to, *delayed_list_cleanup;
7085   CORE_ADDR baseaddr;
7086   struct block *static_block;
7087
7088   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7089
7090   buildsym_init ();
7091   back_to = make_cleanup (really_free_pendings, NULL);
7092   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7093
7094   cu->list_in_scope = &file_symbols;
7095
7096   cu->language = pretend_language;
7097   cu->language_defn = language_def (cu->language);
7098
7099   /* Do line number decoding in read_file_scope () */
7100   process_die (cu->dies, cu);
7101
7102   /* For now fudge the Go package.  */
7103   if (cu->language == language_go)
7104     fixup_go_packaging (cu);
7105
7106   /* Now that we have processed all the DIEs in the CU, all the types 
7107      should be complete, and it should now be safe to compute all of the
7108      physnames.  */
7109   compute_delayed_physnames (cu);
7110   do_cleanups (delayed_list_cleanup);
7111
7112   /* Some compilers don't define a DW_AT_high_pc attribute for the
7113      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7114      it, by scanning the DIE's below the compilation unit.  */
7115   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7116
7117   static_block
7118     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
7119                                    per_cu->imported_symtabs != NULL);
7120
7121   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7122      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7123      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7124      addrmap to help ensure it has an accurate map of pc values belonging to
7125      this comp unit.  */
7126   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7127
7128   symtab = end_symtab_from_static_block (static_block, objfile,
7129                                          SECT_OFF_TEXT (objfile), 0);
7130
7131   if (symtab != NULL)
7132     {
7133       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7134
7135       /* Set symtab language to language from DW_AT_language.  If the
7136          compilation is from a C file generated by language preprocessors, do
7137          not set the language if it was already deduced by start_subfile.  */
7138       if (!(cu->language == language_c && symtab->language != language_c))
7139         symtab->language = cu->language;
7140
7141       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7142          produce DW_AT_location with location lists but it can be possibly
7143          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7144          there were bugs in prologue debug info, fixed later in GCC-4.5
7145          by "unwind info for epilogues" patch (which is not directly related).
7146
7147          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7148          needed, it would be wrong due to missing DW_AT_producer there.
7149
7150          Still one can confuse GDB by using non-standard GCC compilation
7151          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7152          */ 
7153       if (cu->has_loclist && gcc_4_minor >= 5)
7154         symtab->locations_valid = 1;
7155
7156       if (gcc_4_minor >= 5)
7157         symtab->epilogue_unwind_valid = 1;
7158
7159       symtab->call_site_htab = cu->call_site_htab;
7160     }
7161
7162   if (dwarf2_per_objfile->using_index)
7163     per_cu->v.quick->symtab = symtab;
7164   else
7165     {
7166       struct partial_symtab *pst = per_cu->v.psymtab;
7167       pst->symtab = symtab;
7168       pst->readin = 1;
7169     }
7170
7171   /* Push it for inclusion processing later.  */
7172   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7173
7174   do_cleanups (back_to);
7175 }
7176
7177 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7178    already been loaded into memory.  */
7179
7180 static void
7181 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7182                         enum language pretend_language)
7183 {
7184   struct dwarf2_cu *cu = per_cu->cu;
7185   struct objfile *objfile = per_cu->objfile;
7186   struct symtab *symtab;
7187   struct cleanup *back_to, *delayed_list_cleanup;
7188   struct signatured_type *sig_type;
7189
7190   gdb_assert (per_cu->is_debug_types);
7191   sig_type = (struct signatured_type *) per_cu;
7192
7193   buildsym_init ();
7194   back_to = make_cleanup (really_free_pendings, NULL);
7195   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7196
7197   cu->list_in_scope = &file_symbols;
7198
7199   cu->language = pretend_language;
7200   cu->language_defn = language_def (cu->language);
7201
7202   /* The symbol tables are set up in read_type_unit_scope.  */
7203   process_die (cu->dies, cu);
7204
7205   /* For now fudge the Go package.  */
7206   if (cu->language == language_go)
7207     fixup_go_packaging (cu);
7208
7209   /* Now that we have processed all the DIEs in the CU, all the types 
7210      should be complete, and it should now be safe to compute all of the
7211      physnames.  */
7212   compute_delayed_physnames (cu);
7213   do_cleanups (delayed_list_cleanup);
7214
7215   /* TUs share symbol tables.
7216      If this is the first TU to use this symtab, complete the construction
7217      of it with end_expandable_symtab.  Otherwise, complete the addition of
7218      this TU's symbols to the existing symtab.  */
7219   if (sig_type->type_unit_group->primary_symtab == NULL)
7220     {
7221       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7222       sig_type->type_unit_group->primary_symtab = symtab;
7223
7224       if (symtab != NULL)
7225         {
7226           /* Set symtab language to language from DW_AT_language.  If the
7227              compilation is from a C file generated by language preprocessors,
7228              do not set the language if it was already deduced by
7229              start_subfile.  */
7230           if (!(cu->language == language_c && symtab->language != language_c))
7231             symtab->language = cu->language;
7232         }
7233     }
7234   else
7235     {
7236       augment_type_symtab (objfile,
7237                            sig_type->type_unit_group->primary_symtab);
7238       symtab = sig_type->type_unit_group->primary_symtab;
7239     }
7240
7241   if (dwarf2_per_objfile->using_index)
7242     per_cu->v.quick->symtab = symtab;
7243   else
7244     {
7245       struct partial_symtab *pst = per_cu->v.psymtab;
7246       pst->symtab = symtab;
7247       pst->readin = 1;
7248     }
7249
7250   do_cleanups (back_to);
7251 }
7252
7253 /* Process an imported unit DIE.  */
7254
7255 static void
7256 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7257 {
7258   struct attribute *attr;
7259
7260   /* For now we don't handle imported units in type units.  */
7261   if (cu->per_cu->is_debug_types)
7262     {
7263       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7264                " supported in type units [in module %s]"),
7265              cu->objfile->name);
7266     }
7267
7268   attr = dwarf2_attr (die, DW_AT_import, cu);
7269   if (attr != NULL)
7270     {
7271       struct dwarf2_per_cu_data *per_cu;
7272       struct symtab *imported_symtab;
7273       sect_offset offset;
7274       int is_dwz;
7275
7276       offset = dwarf2_get_ref_die_offset (attr);
7277       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7278       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7279
7280       /* Queue the unit, if needed.  */
7281       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7282         load_full_comp_unit (per_cu, cu->language);
7283
7284       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7285                      per_cu);
7286     }
7287 }
7288
7289 /* Process a die and its children.  */
7290
7291 static void
7292 process_die (struct die_info *die, struct dwarf2_cu *cu)
7293 {
7294   switch (die->tag)
7295     {
7296     case DW_TAG_padding:
7297       break;
7298     case DW_TAG_compile_unit:
7299     case DW_TAG_partial_unit:
7300       read_file_scope (die, cu);
7301       break;
7302     case DW_TAG_type_unit:
7303       read_type_unit_scope (die, cu);
7304       break;
7305     case DW_TAG_subprogram:
7306     case DW_TAG_inlined_subroutine:
7307       read_func_scope (die, cu);
7308       break;
7309     case DW_TAG_lexical_block:
7310     case DW_TAG_try_block:
7311     case DW_TAG_catch_block:
7312       read_lexical_block_scope (die, cu);
7313       break;
7314     case DW_TAG_GNU_call_site:
7315       read_call_site_scope (die, cu);
7316       break;
7317     case DW_TAG_class_type:
7318     case DW_TAG_interface_type:
7319     case DW_TAG_structure_type:
7320     case DW_TAG_union_type:
7321       process_structure_scope (die, cu);
7322       break;
7323     case DW_TAG_enumeration_type:
7324       process_enumeration_scope (die, cu);
7325       break;
7326
7327     /* These dies have a type, but processing them does not create
7328        a symbol or recurse to process the children.  Therefore we can
7329        read them on-demand through read_type_die.  */
7330     case DW_TAG_subroutine_type:
7331     case DW_TAG_set_type:
7332     case DW_TAG_array_type:
7333     case DW_TAG_pointer_type:
7334     case DW_TAG_ptr_to_member_type:
7335     case DW_TAG_reference_type:
7336     case DW_TAG_string_type:
7337       break;
7338
7339     case DW_TAG_base_type:
7340     case DW_TAG_subrange_type:
7341     case DW_TAG_typedef:
7342       /* Add a typedef symbol for the type definition, if it has a
7343          DW_AT_name.  */
7344       new_symbol (die, read_type_die (die, cu), cu);
7345       break;
7346     case DW_TAG_common_block:
7347       read_common_block (die, cu);
7348       break;
7349     case DW_TAG_common_inclusion:
7350       break;
7351     case DW_TAG_namespace:
7352       cu->processing_has_namespace_info = 1;
7353       read_namespace (die, cu);
7354       break;
7355     case DW_TAG_module:
7356       cu->processing_has_namespace_info = 1;
7357       read_module (die, cu);
7358       break;
7359     case DW_TAG_imported_declaration:
7360     case DW_TAG_imported_module:
7361       cu->processing_has_namespace_info = 1;
7362       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7363                                  || cu->language != language_fortran))
7364         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7365                    dwarf_tag_name (die->tag));
7366       read_import_statement (die, cu);
7367       break;
7368
7369     case DW_TAG_imported_unit:
7370       process_imported_unit_die (die, cu);
7371       break;
7372
7373     default:
7374       new_symbol (die, NULL, cu);
7375       break;
7376     }
7377 }
7378 \f
7379 /* DWARF name computation.  */
7380
7381 /* A helper function for dwarf2_compute_name which determines whether DIE
7382    needs to have the name of the scope prepended to the name listed in the
7383    die.  */
7384
7385 static int
7386 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7387 {
7388   struct attribute *attr;
7389
7390   switch (die->tag)
7391     {
7392     case DW_TAG_namespace:
7393     case DW_TAG_typedef:
7394     case DW_TAG_class_type:
7395     case DW_TAG_interface_type:
7396     case DW_TAG_structure_type:
7397     case DW_TAG_union_type:
7398     case DW_TAG_enumeration_type:
7399     case DW_TAG_enumerator:
7400     case DW_TAG_subprogram:
7401     case DW_TAG_member:
7402       return 1;
7403
7404     case DW_TAG_variable:
7405     case DW_TAG_constant:
7406       /* We only need to prefix "globally" visible variables.  These include
7407          any variable marked with DW_AT_external or any variable that
7408          lives in a namespace.  [Variables in anonymous namespaces
7409          require prefixing, but they are not DW_AT_external.]  */
7410
7411       if (dwarf2_attr (die, DW_AT_specification, cu))
7412         {
7413           struct dwarf2_cu *spec_cu = cu;
7414
7415           return die_needs_namespace (die_specification (die, &spec_cu),
7416                                       spec_cu);
7417         }
7418
7419       attr = dwarf2_attr (die, DW_AT_external, cu);
7420       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7421           && die->parent->tag != DW_TAG_module)
7422         return 0;
7423       /* A variable in a lexical block of some kind does not need a
7424          namespace, even though in C++ such variables may be external
7425          and have a mangled name.  */
7426       if (die->parent->tag ==  DW_TAG_lexical_block
7427           || die->parent->tag ==  DW_TAG_try_block
7428           || die->parent->tag ==  DW_TAG_catch_block
7429           || die->parent->tag == DW_TAG_subprogram)
7430         return 0;
7431       return 1;
7432
7433     default:
7434       return 0;
7435     }
7436 }
7437
7438 /* Retrieve the last character from a mem_file.  */
7439
7440 static void
7441 do_ui_file_peek_last (void *object, const char *buffer, long length)
7442 {
7443   char *last_char_p = (char *) object;
7444
7445   if (length > 0)
7446     *last_char_p = buffer[length - 1];
7447 }
7448
7449 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7450    compute the physname for the object, which include a method's:
7451    - formal parameters (C++/Java),
7452    - receiver type (Go),
7453    - return type (Java).
7454
7455    The term "physname" is a bit confusing.
7456    For C++, for example, it is the demangled name.
7457    For Go, for example, it's the mangled name.
7458
7459    For Ada, return the DIE's linkage name rather than the fully qualified
7460    name.  PHYSNAME is ignored..
7461
7462    The result is allocated on the objfile_obstack and canonicalized.  */
7463
7464 static const char *
7465 dwarf2_compute_name (const char *name,
7466                      struct die_info *die, struct dwarf2_cu *cu,
7467                      int physname)
7468 {
7469   struct objfile *objfile = cu->objfile;
7470
7471   if (name == NULL)
7472     name = dwarf2_name (die, cu);
7473
7474   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7475      compute it by typename_concat inside GDB.  */
7476   if (cu->language == language_ada
7477       || (cu->language == language_fortran && physname))
7478     {
7479       /* For Ada unit, we prefer the linkage name over the name, as
7480          the former contains the exported name, which the user expects
7481          to be able to reference.  Ideally, we want the user to be able
7482          to reference this entity using either natural or linkage name,
7483          but we haven't started looking at this enhancement yet.  */
7484       struct attribute *attr;
7485
7486       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7487       if (attr == NULL)
7488         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7489       if (attr && DW_STRING (attr))
7490         return DW_STRING (attr);
7491     }
7492
7493   /* These are the only languages we know how to qualify names in.  */
7494   if (name != NULL
7495       && (cu->language == language_cplus || cu->language == language_java
7496           || cu->language == language_fortran))
7497     {
7498       if (die_needs_namespace (die, cu))
7499         {
7500           long length;
7501           const char *prefix;
7502           struct ui_file *buf;
7503
7504           prefix = determine_prefix (die, cu);
7505           buf = mem_fileopen ();
7506           if (*prefix != '\0')
7507             {
7508               char *prefixed_name = typename_concat (NULL, prefix, name,
7509                                                      physname, cu);
7510
7511               fputs_unfiltered (prefixed_name, buf);
7512               xfree (prefixed_name);
7513             }
7514           else
7515             fputs_unfiltered (name, buf);
7516
7517           /* Template parameters may be specified in the DIE's DW_AT_name, or
7518              as children with DW_TAG_template_type_param or
7519              DW_TAG_value_type_param.  If the latter, add them to the name
7520              here.  If the name already has template parameters, then
7521              skip this step; some versions of GCC emit both, and
7522              it is more efficient to use the pre-computed name.
7523
7524              Something to keep in mind about this process: it is very
7525              unlikely, or in some cases downright impossible, to produce
7526              something that will match the mangled name of a function.
7527              If the definition of the function has the same debug info,
7528              we should be able to match up with it anyway.  But fallbacks
7529              using the minimal symbol, for instance to find a method
7530              implemented in a stripped copy of libstdc++, will not work.
7531              If we do not have debug info for the definition, we will have to
7532              match them up some other way.
7533
7534              When we do name matching there is a related problem with function
7535              templates; two instantiated function templates are allowed to
7536              differ only by their return types, which we do not add here.  */
7537
7538           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7539             {
7540               struct attribute *attr;
7541               struct die_info *child;
7542               int first = 1;
7543
7544               die->building_fullname = 1;
7545
7546               for (child = die->child; child != NULL; child = child->sibling)
7547                 {
7548                   struct type *type;
7549                   LONGEST value;
7550                   const gdb_byte *bytes;
7551                   struct dwarf2_locexpr_baton *baton;
7552                   struct value *v;
7553
7554                   if (child->tag != DW_TAG_template_type_param
7555                       && child->tag != DW_TAG_template_value_param)
7556                     continue;
7557
7558                   if (first)
7559                     {
7560                       fputs_unfiltered ("<", buf);
7561                       first = 0;
7562                     }
7563                   else
7564                     fputs_unfiltered (", ", buf);
7565
7566                   attr = dwarf2_attr (child, DW_AT_type, cu);
7567                   if (attr == NULL)
7568                     {
7569                       complaint (&symfile_complaints,
7570                                  _("template parameter missing DW_AT_type"));
7571                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7572                       continue;
7573                     }
7574                   type = die_type (child, cu);
7575
7576                   if (child->tag == DW_TAG_template_type_param)
7577                     {
7578                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7579                       continue;
7580                     }
7581
7582                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7583                   if (attr == NULL)
7584                     {
7585                       complaint (&symfile_complaints,
7586                                  _("template parameter missing "
7587                                    "DW_AT_const_value"));
7588                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7589                       continue;
7590                     }
7591
7592                   dwarf2_const_value_attr (attr, type, name,
7593                                            &cu->comp_unit_obstack, cu,
7594                                            &value, &bytes, &baton);
7595
7596                   if (TYPE_NOSIGN (type))
7597                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7598                        changed, this can use value_print instead.  */
7599                     c_printchar (value, type, buf);
7600                   else
7601                     {
7602                       struct value_print_options opts;
7603
7604                       if (baton != NULL)
7605                         v = dwarf2_evaluate_loc_desc (type, NULL,
7606                                                       baton->data,
7607                                                       baton->size,
7608                                                       baton->per_cu);
7609                       else if (bytes != NULL)
7610                         {
7611                           v = allocate_value (type);
7612                           memcpy (value_contents_writeable (v), bytes,
7613                                   TYPE_LENGTH (type));
7614                         }
7615                       else
7616                         v = value_from_longest (type, value);
7617
7618                       /* Specify decimal so that we do not depend on
7619                          the radix.  */
7620                       get_formatted_print_options (&opts, 'd');
7621                       opts.raw = 1;
7622                       value_print (v, buf, &opts);
7623                       release_value (v);
7624                       value_free (v);
7625                     }
7626                 }
7627
7628               die->building_fullname = 0;
7629
7630               if (!first)
7631                 {
7632                   /* Close the argument list, with a space if necessary
7633                      (nested templates).  */
7634                   char last_char = '\0';
7635                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7636                   if (last_char == '>')
7637                     fputs_unfiltered (" >", buf);
7638                   else
7639                     fputs_unfiltered (">", buf);
7640                 }
7641             }
7642
7643           /* For Java and C++ methods, append formal parameter type
7644              information, if PHYSNAME.  */
7645
7646           if (physname && die->tag == DW_TAG_subprogram
7647               && (cu->language == language_cplus
7648                   || cu->language == language_java))
7649             {
7650               struct type *type = read_type_die (die, cu);
7651
7652               c_type_print_args (type, buf, 1, cu->language,
7653                                  &type_print_raw_options);
7654
7655               if (cu->language == language_java)
7656                 {
7657                   /* For java, we must append the return type to method
7658                      names.  */
7659                   if (die->tag == DW_TAG_subprogram)
7660                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7661                                      0, 0, &type_print_raw_options);
7662                 }
7663               else if (cu->language == language_cplus)
7664                 {
7665                   /* Assume that an artificial first parameter is
7666                      "this", but do not crash if it is not.  RealView
7667                      marks unnamed (and thus unused) parameters as
7668                      artificial; there is no way to differentiate
7669                      the two cases.  */
7670                   if (TYPE_NFIELDS (type) > 0
7671                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7672                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7673                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7674                                                                         0))))
7675                     fputs_unfiltered (" const", buf);
7676                 }
7677             }
7678
7679           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7680                                        &length);
7681           ui_file_delete (buf);
7682
7683           if (cu->language == language_cplus)
7684             {
7685               const char *cname
7686                 = dwarf2_canonicalize_name (name, cu,
7687                                             &objfile->objfile_obstack);
7688
7689               if (cname != NULL)
7690                 name = cname;
7691             }
7692         }
7693     }
7694
7695   return name;
7696 }
7697
7698 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7699    If scope qualifiers are appropriate they will be added.  The result
7700    will be allocated on the objfile_obstack, or NULL if the DIE does
7701    not have a name.  NAME may either be from a previous call to
7702    dwarf2_name or NULL.
7703
7704    The output string will be canonicalized (if C++/Java).  */
7705
7706 static const char *
7707 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7708 {
7709   return dwarf2_compute_name (name, die, cu, 0);
7710 }
7711
7712 /* Construct a physname for the given DIE in CU.  NAME may either be
7713    from a previous call to dwarf2_name or NULL.  The result will be
7714    allocated on the objfile_objstack or NULL if the DIE does not have a
7715    name.
7716
7717    The output string will be canonicalized (if C++/Java).  */
7718
7719 static const char *
7720 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7721 {
7722   struct objfile *objfile = cu->objfile;
7723   struct attribute *attr;
7724   const char *retval, *mangled = NULL, *canon = NULL;
7725   struct cleanup *back_to;
7726   int need_copy = 1;
7727
7728   /* In this case dwarf2_compute_name is just a shortcut not building anything
7729      on its own.  */
7730   if (!die_needs_namespace (die, cu))
7731     return dwarf2_compute_name (name, die, cu, 1);
7732
7733   back_to = make_cleanup (null_cleanup, NULL);
7734
7735   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7736   if (!attr)
7737     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7738
7739   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7740      has computed.  */
7741   if (attr && DW_STRING (attr))
7742     {
7743       char *demangled;
7744
7745       mangled = DW_STRING (attr);
7746
7747       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7748          type.  It is easier for GDB users to search for such functions as
7749          `name(params)' than `long name(params)'.  In such case the minimal
7750          symbol names do not match the full symbol names but for template
7751          functions there is never a need to look up their definition from their
7752          declaration so the only disadvantage remains the minimal symbol
7753          variant `long name(params)' does not have the proper inferior type.
7754          */
7755
7756       if (cu->language == language_go)
7757         {
7758           /* This is a lie, but we already lie to the caller new_symbol_full.
7759              new_symbol_full assumes we return the mangled name.
7760              This just undoes that lie until things are cleaned up.  */
7761           demangled = NULL;
7762         }
7763       else
7764         {
7765           demangled = gdb_demangle (mangled,
7766                                     (DMGL_PARAMS | DMGL_ANSI
7767                                      | (cu->language == language_java
7768                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
7769                                         : DMGL_RET_DROP)));
7770         }
7771       if (demangled)
7772         {
7773           make_cleanup (xfree, demangled);
7774           canon = demangled;
7775         }
7776       else
7777         {
7778           canon = mangled;
7779           need_copy = 0;
7780         }
7781     }
7782
7783   if (canon == NULL || check_physname)
7784     {
7785       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7786
7787       if (canon != NULL && strcmp (physname, canon) != 0)
7788         {
7789           /* It may not mean a bug in GDB.  The compiler could also
7790              compute DW_AT_linkage_name incorrectly.  But in such case
7791              GDB would need to be bug-to-bug compatible.  */
7792
7793           complaint (&symfile_complaints,
7794                      _("Computed physname <%s> does not match demangled <%s> "
7795                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7796                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7797
7798           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7799              is available here - over computed PHYSNAME.  It is safer
7800              against both buggy GDB and buggy compilers.  */
7801
7802           retval = canon;
7803         }
7804       else
7805         {
7806           retval = physname;
7807           need_copy = 0;
7808         }
7809     }
7810   else
7811     retval = canon;
7812
7813   if (need_copy)
7814     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7815
7816   do_cleanups (back_to);
7817   return retval;
7818 }
7819
7820 /* Read the import statement specified by the given die and record it.  */
7821
7822 static void
7823 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7824 {
7825   struct objfile *objfile = cu->objfile;
7826   struct attribute *import_attr;
7827   struct die_info *imported_die, *child_die;
7828   struct dwarf2_cu *imported_cu;
7829   const char *imported_name;
7830   const char *imported_name_prefix;
7831   const char *canonical_name;
7832   const char *import_alias;
7833   const char *imported_declaration = NULL;
7834   const char *import_prefix;
7835   VEC (const_char_ptr) *excludes = NULL;
7836   struct cleanup *cleanups;
7837
7838   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7839   if (import_attr == NULL)
7840     {
7841       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7842                  dwarf_tag_name (die->tag));
7843       return;
7844     }
7845
7846   imported_cu = cu;
7847   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7848   imported_name = dwarf2_name (imported_die, imported_cu);
7849   if (imported_name == NULL)
7850     {
7851       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7852
7853         The import in the following code:
7854         namespace A
7855           {
7856             typedef int B;
7857           }
7858
7859         int main ()
7860           {
7861             using A::B;
7862             B b;
7863             return b;
7864           }
7865
7866         ...
7867          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7868             <52>   DW_AT_decl_file   : 1
7869             <53>   DW_AT_decl_line   : 6
7870             <54>   DW_AT_import      : <0x75>
7871          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7872             <59>   DW_AT_name        : B
7873             <5b>   DW_AT_decl_file   : 1
7874             <5c>   DW_AT_decl_line   : 2
7875             <5d>   DW_AT_type        : <0x6e>
7876         ...
7877          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7878             <76>   DW_AT_byte_size   : 4
7879             <77>   DW_AT_encoding    : 5        (signed)
7880
7881         imports the wrong die ( 0x75 instead of 0x58 ).
7882         This case will be ignored until the gcc bug is fixed.  */
7883       return;
7884     }
7885
7886   /* Figure out the local name after import.  */
7887   import_alias = dwarf2_name (die, cu);
7888
7889   /* Figure out where the statement is being imported to.  */
7890   import_prefix = determine_prefix (die, cu);
7891
7892   /* Figure out what the scope of the imported die is and prepend it
7893      to the name of the imported die.  */
7894   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7895
7896   if (imported_die->tag != DW_TAG_namespace
7897       && imported_die->tag != DW_TAG_module)
7898     {
7899       imported_declaration = imported_name;
7900       canonical_name = imported_name_prefix;
7901     }
7902   else if (strlen (imported_name_prefix) > 0)
7903     canonical_name = obconcat (&objfile->objfile_obstack,
7904                                imported_name_prefix, "::", imported_name,
7905                                (char *) NULL);
7906   else
7907     canonical_name = imported_name;
7908
7909   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7910
7911   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7912     for (child_die = die->child; child_die && child_die->tag;
7913          child_die = sibling_die (child_die))
7914       {
7915         /* DWARF-4: A Fortran use statement with a “rename list” may be
7916            represented by an imported module entry with an import attribute
7917            referring to the module and owned entries corresponding to those
7918            entities that are renamed as part of being imported.  */
7919
7920         if (child_die->tag != DW_TAG_imported_declaration)
7921           {
7922             complaint (&symfile_complaints,
7923                        _("child DW_TAG_imported_declaration expected "
7924                          "- DIE at 0x%x [in module %s]"),
7925                        child_die->offset.sect_off, objfile->name);
7926             continue;
7927           }
7928
7929         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7930         if (import_attr == NULL)
7931           {
7932             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7933                        dwarf_tag_name (child_die->tag));
7934             continue;
7935           }
7936
7937         imported_cu = cu;
7938         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7939                                               &imported_cu);
7940         imported_name = dwarf2_name (imported_die, imported_cu);
7941         if (imported_name == NULL)
7942           {
7943             complaint (&symfile_complaints,
7944                        _("child DW_TAG_imported_declaration has unknown "
7945                          "imported name - DIE at 0x%x [in module %s]"),
7946                        child_die->offset.sect_off, objfile->name);
7947             continue;
7948           }
7949
7950         VEC_safe_push (const_char_ptr, excludes, imported_name);
7951
7952         process_die (child_die, cu);
7953       }
7954
7955   cp_add_using_directive (import_prefix,
7956                           canonical_name,
7957                           import_alias,
7958                           imported_declaration,
7959                           excludes,
7960                           0,
7961                           &objfile->objfile_obstack);
7962
7963   do_cleanups (cleanups);
7964 }
7965
7966 /* Cleanup function for handle_DW_AT_stmt_list.  */
7967
7968 static void
7969 free_cu_line_header (void *arg)
7970 {
7971   struct dwarf2_cu *cu = arg;
7972
7973   free_line_header (cu->line_header);
7974   cu->line_header = NULL;
7975 }
7976
7977 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7978    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7979    this, it was first present in GCC release 4.3.0.  */
7980
7981 static int
7982 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7983 {
7984   if (!cu->checked_producer)
7985     check_producer (cu);
7986
7987   return cu->producer_is_gcc_lt_4_3;
7988 }
7989
7990 static void
7991 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7992                          const char **name, const char **comp_dir)
7993 {
7994   struct attribute *attr;
7995
7996   *name = NULL;
7997   *comp_dir = NULL;
7998
7999   /* Find the filename.  Do not use dwarf2_name here, since the filename
8000      is not a source language identifier.  */
8001   attr = dwarf2_attr (die, DW_AT_name, cu);
8002   if (attr)
8003     {
8004       *name = DW_STRING (attr);
8005     }
8006
8007   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8008   if (attr)
8009     *comp_dir = DW_STRING (attr);
8010   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8011            && IS_ABSOLUTE_PATH (*name))
8012     {
8013       char *d = ldirname (*name);
8014
8015       *comp_dir = d;
8016       if (d != NULL)
8017         make_cleanup (xfree, d);
8018     }
8019   if (*comp_dir != NULL)
8020     {
8021       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8022          directory, get rid of it.  */
8023       char *cp = strchr (*comp_dir, ':');
8024
8025       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8026         *comp_dir = cp + 1;
8027     }
8028
8029   if (*name == NULL)
8030     *name = "<unknown>";
8031 }
8032
8033 /* Handle DW_AT_stmt_list for a compilation unit.
8034    DIE is the DW_TAG_compile_unit die for CU.
8035    COMP_DIR is the compilation directory.
8036    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8037
8038 static void
8039 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8040                         const char *comp_dir)
8041 {
8042   struct attribute *attr;
8043
8044   gdb_assert (! cu->per_cu->is_debug_types);
8045
8046   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8047   if (attr)
8048     {
8049       unsigned int line_offset = DW_UNSND (attr);
8050       struct line_header *line_header
8051         = dwarf_decode_line_header (line_offset, cu);
8052
8053       if (line_header)
8054         {
8055           cu->line_header = line_header;
8056           make_cleanup (free_cu_line_header, cu);
8057           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8058         }
8059     }
8060 }
8061
8062 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8063
8064 static void
8065 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8066 {
8067   struct objfile *objfile = dwarf2_per_objfile->objfile;
8068   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8069   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8070   CORE_ADDR highpc = ((CORE_ADDR) 0);
8071   struct attribute *attr;
8072   const char *name = NULL;
8073   const char *comp_dir = NULL;
8074   struct die_info *child_die;
8075   bfd *abfd = objfile->obfd;
8076   CORE_ADDR baseaddr;
8077
8078   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8079
8080   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8081
8082   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8083      from finish_block.  */
8084   if (lowpc == ((CORE_ADDR) -1))
8085     lowpc = highpc;
8086   lowpc += baseaddr;
8087   highpc += baseaddr;
8088
8089   find_file_and_directory (die, cu, &name, &comp_dir);
8090
8091   prepare_one_comp_unit (cu, die, cu->language);
8092
8093   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8094      standardised yet.  As a workaround for the language detection we fall
8095      back to the DW_AT_producer string.  */
8096   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8097     cu->language = language_opencl;
8098
8099   /* Similar hack for Go.  */
8100   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8101     set_cu_language (DW_LANG_Go, cu);
8102
8103   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8104
8105   /* Decode line number information if present.  We do this before
8106      processing child DIEs, so that the line header table is available
8107      for DW_AT_decl_file.  */
8108   handle_DW_AT_stmt_list (die, cu, comp_dir);
8109
8110   /* Process all dies in compilation unit.  */
8111   if (die->child != NULL)
8112     {
8113       child_die = die->child;
8114       while (child_die && child_die->tag)
8115         {
8116           process_die (child_die, cu);
8117           child_die = sibling_die (child_die);
8118         }
8119     }
8120
8121   /* Decode macro information, if present.  Dwarf 2 macro information
8122      refers to information in the line number info statement program
8123      header, so we can only read it if we've read the header
8124      successfully.  */
8125   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8126   if (attr && cu->line_header)
8127     {
8128       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8129         complaint (&symfile_complaints,
8130                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8131
8132       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8133     }
8134   else
8135     {
8136       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8137       if (attr && cu->line_header)
8138         {
8139           unsigned int macro_offset = DW_UNSND (attr);
8140
8141           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8142         }
8143     }
8144
8145   do_cleanups (back_to);
8146 }
8147
8148 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8149    Create the set of symtabs used by this TU, or if this TU is sharing
8150    symtabs with another TU and the symtabs have already been created
8151    then restore those symtabs in the line header.
8152    We don't need the pc/line-number mapping for type units.  */
8153
8154 static void
8155 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8156 {
8157   struct objfile *objfile = dwarf2_per_objfile->objfile;
8158   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8159   struct type_unit_group *tu_group;
8160   int first_time;
8161   struct line_header *lh;
8162   struct attribute *attr;
8163   unsigned int i, line_offset;
8164   struct signatured_type *sig_type;
8165
8166   gdb_assert (per_cu->is_debug_types);
8167   sig_type = (struct signatured_type *) per_cu;
8168
8169   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8170
8171   /* If we're using .gdb_index (includes -readnow) then
8172      per_cu->s.type_unit_group may not have been set up yet.  */
8173   if (sig_type->type_unit_group == NULL)
8174     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8175   tu_group = sig_type->type_unit_group;
8176
8177   /* If we've already processed this stmt_list there's no real need to
8178      do it again, we could fake it and just recreate the part we need
8179      (file name,index -> symtab mapping).  If data shows this optimization
8180      is useful we can do it then.  */
8181   first_time = tu_group->primary_symtab == NULL;
8182
8183   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8184      debug info.  */
8185   lh = NULL;
8186   if (attr != NULL)
8187     {
8188       line_offset = DW_UNSND (attr);
8189       lh = dwarf_decode_line_header (line_offset, cu);
8190     }
8191   if (lh == NULL)
8192     {
8193       if (first_time)
8194         dwarf2_start_symtab (cu, "", NULL, 0);
8195       else
8196         {
8197           gdb_assert (tu_group->symtabs == NULL);
8198           restart_symtab (0);
8199         }
8200       /* Note: The primary symtab will get allocated at the end.  */
8201       return;
8202     }
8203
8204   cu->line_header = lh;
8205   make_cleanup (free_cu_line_header, cu);
8206
8207   if (first_time)
8208     {
8209       dwarf2_start_symtab (cu, "", NULL, 0);
8210
8211       tu_group->num_symtabs = lh->num_file_names;
8212       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8213
8214       for (i = 0; i < lh->num_file_names; ++i)
8215         {
8216           const char *dir = NULL;
8217           struct file_entry *fe = &lh->file_names[i];
8218
8219           if (fe->dir_index)
8220             dir = lh->include_dirs[fe->dir_index - 1];
8221           dwarf2_start_subfile (fe->name, dir, NULL);
8222
8223           /* Note: We don't have to watch for the main subfile here, type units
8224              don't have DW_AT_name.  */
8225
8226           if (current_subfile->symtab == NULL)
8227             {
8228               /* NOTE: start_subfile will recognize when it's been passed
8229                  a file it has already seen.  So we can't assume there's a
8230                  simple mapping from lh->file_names to subfiles,
8231                  lh->file_names may contain dups.  */
8232               current_subfile->symtab = allocate_symtab (current_subfile->name,
8233                                                          objfile);
8234             }
8235
8236           fe->symtab = current_subfile->symtab;
8237           tu_group->symtabs[i] = fe->symtab;
8238         }
8239     }
8240   else
8241     {
8242       restart_symtab (0);
8243
8244       for (i = 0; i < lh->num_file_names; ++i)
8245         {
8246           struct file_entry *fe = &lh->file_names[i];
8247
8248           fe->symtab = tu_group->symtabs[i];
8249         }
8250     }
8251
8252   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8253      so they don't have a "real" (so to speak) symtab anyway.
8254      There is later code that will assign the main symtab to all symbols
8255      that don't have one.  We need to handle the case of a symbol with a
8256      missing symtab (DW_AT_decl_file) anyway.  */
8257 }
8258
8259 /* Process DW_TAG_type_unit.
8260    For TUs we want to skip the first top level sibling if it's not the
8261    actual type being defined by this TU.  In this case the first top
8262    level sibling is there to provide context only.  */
8263
8264 static void
8265 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8266 {
8267   struct die_info *child_die;
8268
8269   prepare_one_comp_unit (cu, die, language_minimal);
8270
8271   /* Initialize (or reinitialize) the machinery for building symtabs.
8272      We do this before processing child DIEs, so that the line header table
8273      is available for DW_AT_decl_file.  */
8274   setup_type_unit_groups (die, cu);
8275
8276   if (die->child != NULL)
8277     {
8278       child_die = die->child;
8279       while (child_die && child_die->tag)
8280         {
8281           process_die (child_die, cu);
8282           child_die = sibling_die (child_die);
8283         }
8284     }
8285 }
8286 \f
8287 /* DWO/DWP files.
8288
8289    http://gcc.gnu.org/wiki/DebugFission
8290    http://gcc.gnu.org/wiki/DebugFissionDWP
8291
8292    To simplify handling of both DWO files ("object" files with the DWARF info)
8293    and DWP files (a file with the DWOs packaged up into one file), we treat
8294    DWP files as having a collection of virtual DWO files.  */
8295
8296 static hashval_t
8297 hash_dwo_file (const void *item)
8298 {
8299   const struct dwo_file *dwo_file = item;
8300
8301   return (htab_hash_string (dwo_file->dwo_name)
8302           + htab_hash_string (dwo_file->comp_dir));
8303 }
8304
8305 static int
8306 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8307 {
8308   const struct dwo_file *lhs = item_lhs;
8309   const struct dwo_file *rhs = item_rhs;
8310
8311   return (strcmp (lhs->dwo_name, rhs->dwo_name) == 0
8312           && strcmp (lhs->comp_dir, rhs->comp_dir) == 0);
8313 }
8314
8315 /* Allocate a hash table for DWO files.  */
8316
8317 static htab_t
8318 allocate_dwo_file_hash_table (void)
8319 {
8320   struct objfile *objfile = dwarf2_per_objfile->objfile;
8321
8322   return htab_create_alloc_ex (41,
8323                                hash_dwo_file,
8324                                eq_dwo_file,
8325                                NULL,
8326                                &objfile->objfile_obstack,
8327                                hashtab_obstack_allocate,
8328                                dummy_obstack_deallocate);
8329 }
8330
8331 /* Lookup DWO file DWO_NAME.  */
8332
8333 static void **
8334 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8335 {
8336   struct dwo_file find_entry;
8337   void **slot;
8338
8339   if (dwarf2_per_objfile->dwo_files == NULL)
8340     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8341
8342   memset (&find_entry, 0, sizeof (find_entry));
8343   find_entry.dwo_name = dwo_name;
8344   find_entry.comp_dir = comp_dir;
8345   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8346
8347   return slot;
8348 }
8349
8350 static hashval_t
8351 hash_dwo_unit (const void *item)
8352 {
8353   const struct dwo_unit *dwo_unit = item;
8354
8355   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8356   return dwo_unit->signature;
8357 }
8358
8359 static int
8360 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8361 {
8362   const struct dwo_unit *lhs = item_lhs;
8363   const struct dwo_unit *rhs = item_rhs;
8364
8365   /* The signature is assumed to be unique within the DWO file.
8366      So while object file CU dwo_id's always have the value zero,
8367      that's OK, assuming each object file DWO file has only one CU,
8368      and that's the rule for now.  */
8369   return lhs->signature == rhs->signature;
8370 }
8371
8372 /* Allocate a hash table for DWO CUs,TUs.
8373    There is one of these tables for each of CUs,TUs for each DWO file.  */
8374
8375 static htab_t
8376 allocate_dwo_unit_table (struct objfile *objfile)
8377 {
8378   /* Start out with a pretty small number.
8379      Generally DWO files contain only one CU and maybe some TUs.  */
8380   return htab_create_alloc_ex (3,
8381                                hash_dwo_unit,
8382                                eq_dwo_unit,
8383                                NULL,
8384                                &objfile->objfile_obstack,
8385                                hashtab_obstack_allocate,
8386                                dummy_obstack_deallocate);
8387 }
8388
8389 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8390
8391 struct create_dwo_info_table_data
8392 {
8393   struct dwo_file *dwo_file;
8394   htab_t cu_htab;
8395 };
8396
8397 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8398
8399 static void
8400 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8401                                          const gdb_byte *info_ptr,
8402                                          struct die_info *comp_unit_die,
8403                                          int has_children,
8404                                          void *datap)
8405 {
8406   struct dwarf2_cu *cu = reader->cu;
8407   struct objfile *objfile = dwarf2_per_objfile->objfile;
8408   sect_offset offset = cu->per_cu->offset;
8409   struct dwarf2_section_info *section = cu->per_cu->section;
8410   struct create_dwo_info_table_data *data = datap;
8411   struct dwo_file *dwo_file = data->dwo_file;
8412   htab_t cu_htab = data->cu_htab;
8413   void **slot;
8414   struct attribute *attr;
8415   struct dwo_unit *dwo_unit;
8416
8417   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8418   if (attr == NULL)
8419     {
8420       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8421                " its dwo_id [in module %s]"),
8422              offset.sect_off, dwo_file->dwo_name);
8423       return;
8424     }
8425
8426   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8427   dwo_unit->dwo_file = dwo_file;
8428   dwo_unit->signature = DW_UNSND (attr);
8429   dwo_unit->section = section;
8430   dwo_unit->offset = offset;
8431   dwo_unit->length = cu->per_cu->length;
8432
8433   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8434   gdb_assert (slot != NULL);
8435   if (*slot != NULL)
8436     {
8437       const struct dwo_unit *dup_dwo_unit = *slot;
8438
8439       complaint (&symfile_complaints,
8440                  _("debug entry at offset 0x%x is duplicate to the entry at"
8441                    " offset 0x%x, dwo_id %s [in module %s]"),
8442                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8443                  hex_string (dwo_unit->signature), dwo_file->dwo_name);
8444     }
8445   else
8446     *slot = dwo_unit;
8447
8448   if (dwarf2_read_debug)
8449     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
8450                         offset.sect_off, hex_string (dwo_unit->signature));
8451 }
8452
8453 /* Create a hash table to map DWO IDs to their CU entry in
8454    .debug_info.dwo in DWO_FILE.
8455    Note: This function processes DWO files only, not DWP files.
8456    Note: A DWO file generally contains one CU, but we don't assume this.  */
8457
8458 static htab_t
8459 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8460 {
8461   struct objfile *objfile = dwarf2_per_objfile->objfile;
8462   struct dwarf2_section_info *section = &dwo_file->sections.info;
8463   bfd *abfd;
8464   htab_t cu_htab;
8465   const gdb_byte *info_ptr, *end_ptr;
8466   struct create_dwo_info_table_data create_dwo_info_table_data;
8467
8468   dwarf2_read_section (objfile, section);
8469   info_ptr = section->buffer;
8470
8471   if (info_ptr == NULL)
8472     return NULL;
8473
8474   /* We can't set abfd until now because the section may be empty or
8475      not present, in which case section->asection will be NULL.  */
8476   abfd = section->asection->owner;
8477
8478   if (dwarf2_read_debug)
8479     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8480                         bfd_get_filename (abfd));
8481
8482   cu_htab = allocate_dwo_unit_table (objfile);
8483
8484   create_dwo_info_table_data.dwo_file = dwo_file;
8485   create_dwo_info_table_data.cu_htab = cu_htab;
8486
8487   end_ptr = info_ptr + section->size;
8488   while (info_ptr < end_ptr)
8489     {
8490       struct dwarf2_per_cu_data per_cu;
8491
8492       memset (&per_cu, 0, sizeof (per_cu));
8493       per_cu.objfile = objfile;
8494       per_cu.is_debug_types = 0;
8495       per_cu.offset.sect_off = info_ptr - section->buffer;
8496       per_cu.section = section;
8497
8498       init_cutu_and_read_dies_no_follow (&per_cu,
8499                                          &dwo_file->sections.abbrev,
8500                                          dwo_file,
8501                                          create_dwo_debug_info_hash_table_reader,
8502                                          &create_dwo_info_table_data);
8503
8504       info_ptr += per_cu.length;
8505     }
8506
8507   return cu_htab;
8508 }
8509
8510 /* DWP file .debug_{cu,tu}_index section format:
8511    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8512
8513    Both index sections have the same format, and serve to map a 64-bit
8514    signature to a set of section numbers.  Each section begins with a header,
8515    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8516    indexes, and a pool of 32-bit section numbers.  The index sections will be
8517    aligned at 8-byte boundaries in the file.
8518
8519    The index section header contains two unsigned 32-bit values (using the
8520    byte order of the application binary):
8521
8522     N, the number of compilation units or type units in the index
8523     M, the number of slots in the hash table
8524
8525   (We assume that N and M will not exceed 2^32 - 1.)
8526
8527   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8528
8529   The hash table begins at offset 8 in the section, and consists of an array
8530   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8531   order of the application binary).  Unused slots in the hash table are 0.
8532   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8533
8534   The parallel table begins immediately after the hash table
8535   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8536   array of 32-bit indexes (using the byte order of the application binary),
8537   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8538   table contains a 32-bit index into the pool of section numbers.  For unused
8539   hash table slots, the corresponding entry in the parallel table will be 0.
8540
8541   Given a 64-bit compilation unit signature or a type signature S, an entry
8542   in the hash table is located as follows:
8543
8544   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8545      the low-order k bits all set to 1.
8546
8547   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8548
8549   3) If the hash table entry at index H matches the signature, use that
8550      entry.  If the hash table entry at index H is unused (all zeroes),
8551      terminate the search: the signature is not present in the table.
8552
8553   4) Let H = (H + H') modulo M. Repeat at Step 3.
8554
8555   Because M > N and H' and M are relatively prime, the search is guaranteed
8556   to stop at an unused slot or find the match.
8557
8558   The pool of section numbers begins immediately following the hash table
8559   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8560   section numbers consists of an array of 32-bit words (using the byte order
8561   of the application binary).  Each item in the array is indexed starting
8562   from 0.  The hash table entry provides the index of the first section
8563   number in the set.  Additional section numbers in the set follow, and the
8564   set is terminated by a 0 entry (section number 0 is not used in ELF).
8565
8566   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8567   section must be the first entry in the set, and the .debug_abbrev.dwo must
8568   be the second entry. Other members of the set may follow in any order.  */
8569
8570 /* Create a hash table to map DWO IDs to their CU/TU entry in
8571    .debug_{info,types}.dwo in DWP_FILE.
8572    Returns NULL if there isn't one.
8573    Note: This function processes DWP files only, not DWO files.  */
8574
8575 static struct dwp_hash_table *
8576 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8577 {
8578   struct objfile *objfile = dwarf2_per_objfile->objfile;
8579   bfd *dbfd = dwp_file->dbfd;
8580   const char *index_ptr, *index_end;
8581   struct dwarf2_section_info *index;
8582   uint32_t version, nr_units, nr_slots;
8583   struct dwp_hash_table *htab;
8584
8585   if (is_debug_types)
8586     index = &dwp_file->sections.tu_index;
8587   else
8588     index = &dwp_file->sections.cu_index;
8589
8590   if (dwarf2_section_empty_p (index))
8591     return NULL;
8592   dwarf2_read_section (objfile, index);
8593
8594   index_ptr = index->buffer;
8595   index_end = index_ptr + index->size;
8596
8597   version = read_4_bytes (dbfd, index_ptr);
8598   index_ptr += 8; /* Skip the unused word.  */
8599   nr_units = read_4_bytes (dbfd, index_ptr);
8600   index_ptr += 4;
8601   nr_slots = read_4_bytes (dbfd, index_ptr);
8602   index_ptr += 4;
8603
8604   if (version != 1)
8605     {
8606       error (_("Dwarf Error: unsupported DWP file version (%u)"
8607                " [in module %s]"),
8608              version, dwp_file->name);
8609     }
8610   if (nr_slots != (nr_slots & -nr_slots))
8611     {
8612       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8613                " is not power of 2 [in module %s]"),
8614              nr_slots, dwp_file->name);
8615     }
8616
8617   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8618   htab->nr_units = nr_units;
8619   htab->nr_slots = nr_slots;
8620   htab->hash_table = index_ptr;
8621   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8622   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8623
8624   return htab;
8625 }
8626
8627 /* Update SECTIONS with the data from SECTP.
8628
8629    This function is like the other "locate" section routines that are
8630    passed to bfd_map_over_sections, but in this context the sections to
8631    read comes from the DWP hash table, not the full ELF section table.
8632
8633    The result is non-zero for success, or zero if an error was found.  */
8634
8635 static int
8636 locate_virtual_dwo_sections (asection *sectp,
8637                              struct virtual_dwo_sections *sections)
8638 {
8639   const struct dwop_section_names *names = &dwop_section_names;
8640
8641   if (section_is_p (sectp->name, &names->abbrev_dwo))
8642     {
8643       /* There can be only one.  */
8644       if (sections->abbrev.asection != NULL)
8645         return 0;
8646       sections->abbrev.asection = sectp;
8647       sections->abbrev.size = bfd_get_section_size (sectp);
8648     }
8649   else if (section_is_p (sectp->name, &names->info_dwo)
8650            || section_is_p (sectp->name, &names->types_dwo))
8651     {
8652       /* There can be only one.  */
8653       if (sections->info_or_types.asection != NULL)
8654         return 0;
8655       sections->info_or_types.asection = sectp;
8656       sections->info_or_types.size = bfd_get_section_size (sectp);
8657     }
8658   else if (section_is_p (sectp->name, &names->line_dwo))
8659     {
8660       /* There can be only one.  */
8661       if (sections->line.asection != NULL)
8662         return 0;
8663       sections->line.asection = sectp;
8664       sections->line.size = bfd_get_section_size (sectp);
8665     }
8666   else if (section_is_p (sectp->name, &names->loc_dwo))
8667     {
8668       /* There can be only one.  */
8669       if (sections->loc.asection != NULL)
8670         return 0;
8671       sections->loc.asection = sectp;
8672       sections->loc.size = bfd_get_section_size (sectp);
8673     }
8674   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8675     {
8676       /* There can be only one.  */
8677       if (sections->macinfo.asection != NULL)
8678         return 0;
8679       sections->macinfo.asection = sectp;
8680       sections->macinfo.size = bfd_get_section_size (sectp);
8681     }
8682   else if (section_is_p (sectp->name, &names->macro_dwo))
8683     {
8684       /* There can be only one.  */
8685       if (sections->macro.asection != NULL)
8686         return 0;
8687       sections->macro.asection = sectp;
8688       sections->macro.size = bfd_get_section_size (sectp);
8689     }
8690   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8691     {
8692       /* There can be only one.  */
8693       if (sections->str_offsets.asection != NULL)
8694         return 0;
8695       sections->str_offsets.asection = sectp;
8696       sections->str_offsets.size = bfd_get_section_size (sectp);
8697     }
8698   else
8699     {
8700       /* No other kind of section is valid.  */
8701       return 0;
8702     }
8703
8704   return 1;
8705 }
8706
8707 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8708    HTAB is the hash table from the DWP file.
8709    SECTION_INDEX is the index of the DWO in HTAB.
8710    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.  */
8711
8712 static struct dwo_unit *
8713 create_dwo_in_dwp (struct dwp_file *dwp_file,
8714                    const struct dwp_hash_table *htab,
8715                    uint32_t section_index,
8716                    const char *comp_dir,
8717                    ULONGEST signature, int is_debug_types)
8718 {
8719   struct objfile *objfile = dwarf2_per_objfile->objfile;
8720   bfd *dbfd = dwp_file->dbfd;
8721   const char *kind = is_debug_types ? "TU" : "CU";
8722   struct dwo_file *dwo_file;
8723   struct dwo_unit *dwo_unit;
8724   struct virtual_dwo_sections sections;
8725   void **dwo_file_slot;
8726   char *virtual_dwo_name;
8727   struct dwarf2_section_info *cutu;
8728   struct cleanup *cleanups;
8729   int i;
8730
8731   if (dwarf2_read_debug)
8732     {
8733       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/%s in DWP file: %s\n",
8734                           kind,
8735                           section_index, hex_string (signature),
8736                           dwp_file->name);
8737     }
8738
8739   /* Fetch the sections of this DWO.
8740      Put a limit on the number of sections we look for so that bad data
8741      doesn't cause us to loop forever.  */
8742
8743 #define MAX_NR_DWO_SECTIONS \
8744   (1 /* .debug_info or .debug_types */ \
8745    + 1 /* .debug_abbrev */ \
8746    + 1 /* .debug_line */ \
8747    + 1 /* .debug_loc */ \
8748    + 1 /* .debug_str_offsets */ \
8749    + 1 /* .debug_macro */ \
8750    + 1 /* .debug_macinfo */ \
8751    + 1 /* trailing zero */)
8752
8753   memset (&sections, 0, sizeof (sections));
8754   cleanups = make_cleanup (null_cleanup, 0);
8755
8756   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8757     {
8758       asection *sectp;
8759       uint32_t section_nr =
8760         read_4_bytes (dbfd,
8761                       htab->section_pool
8762                       + (section_index + i) * sizeof (uint32_t));
8763
8764       if (section_nr == 0)
8765         break;
8766       if (section_nr >= dwp_file->num_sections)
8767         {
8768           error (_("Dwarf Error: bad DWP hash table, section number too large"
8769                    " [in module %s]"),
8770                  dwp_file->name);
8771         }
8772
8773       sectp = dwp_file->elf_sections[section_nr];
8774       if (! locate_virtual_dwo_sections (sectp, &sections))
8775         {
8776           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8777                    " [in module %s]"),
8778                  dwp_file->name);
8779         }
8780     }
8781
8782   if (i < 2
8783       || sections.info_or_types.asection == NULL
8784       || sections.abbrev.asection == NULL)
8785     {
8786       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8787                " [in module %s]"),
8788              dwp_file->name);
8789     }
8790   if (i == MAX_NR_DWO_SECTIONS)
8791     {
8792       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8793                " [in module %s]"),
8794              dwp_file->name);
8795     }
8796
8797   /* It's easier for the rest of the code if we fake a struct dwo_file and
8798      have dwo_unit "live" in that.  At least for now.
8799
8800      The DWP file can be made up of a random collection of CUs and TUs.
8801      However, for each CU + set of TUs that came from the same original DWO
8802      file, we want to combine them back into a virtual DWO file to save space
8803      (fewer struct dwo_file objects to allocated).  Remember that for really
8804      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8805
8806   virtual_dwo_name =
8807     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8808                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8809                 sections.line.asection ? sections.line.asection->id : 0,
8810                 sections.loc.asection ? sections.loc.asection->id : 0,
8811                 (sections.str_offsets.asection
8812                 ? sections.str_offsets.asection->id
8813                 : 0));
8814   make_cleanup (xfree, virtual_dwo_name);
8815   /* Can we use an existing virtual DWO file?  */
8816   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
8817   /* Create one if necessary.  */
8818   if (*dwo_file_slot == NULL)
8819     {
8820       if (dwarf2_read_debug)
8821         {
8822           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8823                               virtual_dwo_name);
8824         }
8825       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8826       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
8827                                           virtual_dwo_name,
8828                                           strlen (virtual_dwo_name));
8829       dwo_file->comp_dir = comp_dir;
8830       dwo_file->sections.abbrev = sections.abbrev;
8831       dwo_file->sections.line = sections.line;
8832       dwo_file->sections.loc = sections.loc;
8833       dwo_file->sections.macinfo = sections.macinfo;
8834       dwo_file->sections.macro = sections.macro;
8835       dwo_file->sections.str_offsets = sections.str_offsets;
8836       /* The "str" section is global to the entire DWP file.  */
8837       dwo_file->sections.str = dwp_file->sections.str;
8838       /* The info or types section is assigned later to dwo_unit,
8839          there's no need to record it in dwo_file.
8840          Also, we can't simply record type sections in dwo_file because
8841          we record a pointer into the vector in dwo_unit.  As we collect more
8842          types we'll grow the vector and eventually have to reallocate space
8843          for it, invalidating all the pointers into the current copy.  */
8844       *dwo_file_slot = dwo_file;
8845     }
8846   else
8847     {
8848       if (dwarf2_read_debug)
8849         {
8850           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8851                               virtual_dwo_name);
8852         }
8853       dwo_file = *dwo_file_slot;
8854     }
8855   do_cleanups (cleanups);
8856
8857   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8858   dwo_unit->dwo_file = dwo_file;
8859   dwo_unit->signature = signature;
8860   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
8861                                      sizeof (struct dwarf2_section_info));
8862   *dwo_unit->section = sections.info_or_types;
8863   /* offset, length, type_offset_in_tu are set later.  */
8864
8865   return dwo_unit;
8866 }
8867
8868 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8869
8870 static struct dwo_unit *
8871 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8872                    const struct dwp_hash_table *htab,
8873                    const char *comp_dir,
8874                    ULONGEST signature, int is_debug_types)
8875 {
8876   bfd *dbfd = dwp_file->dbfd;
8877   uint32_t mask = htab->nr_slots - 1;
8878   uint32_t hash = signature & mask;
8879   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8880   unsigned int i;
8881   void **slot;
8882   struct dwo_unit find_dwo_cu, *dwo_cu;
8883
8884   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8885   find_dwo_cu.signature = signature;
8886   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8887
8888   if (*slot != NULL)
8889     return *slot;
8890
8891   /* Use a for loop so that we don't loop forever on bad debug info.  */
8892   for (i = 0; i < htab->nr_slots; ++i)
8893     {
8894       ULONGEST signature_in_table;
8895
8896       signature_in_table =
8897         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8898       if (signature_in_table == signature)
8899         {
8900           uint32_t section_index =
8901             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8902
8903           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8904                                      comp_dir, signature, is_debug_types);
8905           return *slot;
8906         }
8907       if (signature_in_table == 0)
8908         return NULL;
8909       hash = (hash + hash2) & mask;
8910     }
8911
8912   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8913            " [in module %s]"),
8914          dwp_file->name);
8915 }
8916
8917 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
8918    Open the file specified by FILE_NAME and hand it off to BFD for
8919    preliminary analysis.  Return a newly initialized bfd *, which
8920    includes a canonicalized copy of FILE_NAME.
8921    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8922    In case of trouble, return NULL.
8923    NOTE: This function is derived from symfile_bfd_open.  */
8924
8925 static bfd *
8926 try_open_dwop_file (const char *file_name, int is_dwp)
8927 {
8928   bfd *sym_bfd;
8929   int desc, flags;
8930   char *absolute_name;
8931
8932   flags = OPF_TRY_CWD_FIRST;
8933   if (is_dwp)
8934     flags |= OPF_SEARCH_IN_PATH;
8935   desc = openp (debug_file_directory, flags, file_name,
8936                 O_RDONLY | O_BINARY, &absolute_name);
8937   if (desc < 0)
8938     return NULL;
8939
8940   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8941   if (!sym_bfd)
8942     {
8943       xfree (absolute_name);
8944       return NULL;
8945     }
8946   xfree (absolute_name);
8947   bfd_set_cacheable (sym_bfd, 1);
8948
8949   if (!bfd_check_format (sym_bfd, bfd_object))
8950     {
8951       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8952       return NULL;
8953     }
8954
8955   return sym_bfd;
8956 }
8957
8958 /* Try to open DWO file FILE_NAME.
8959    COMP_DIR is the DW_AT_comp_dir attribute.
8960    The result is the bfd handle of the file.
8961    If there is a problem finding or opening the file, return NULL.
8962    Upon success, the canonicalized path of the file is stored in the bfd,
8963    same as symfile_bfd_open.  */
8964
8965 static bfd *
8966 open_dwo_file (const char *file_name, const char *comp_dir)
8967 {
8968   bfd *abfd;
8969
8970   if (IS_ABSOLUTE_PATH (file_name))
8971     return try_open_dwop_file (file_name, 0 /*is_dwp*/);
8972
8973   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8974
8975   if (comp_dir != NULL)
8976     {
8977       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8978
8979       /* NOTE: If comp_dir is a relative path, this will also try the
8980          search path, which seems useful.  */
8981       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/);
8982       xfree (path_to_try);
8983       if (abfd != NULL)
8984         return abfd;
8985     }
8986
8987   /* That didn't work, try debug-file-directory, which, despite its name,
8988      is a list of paths.  */
8989
8990   if (*debug_file_directory == '\0')
8991     return NULL;
8992
8993   return try_open_dwop_file (file_name, 0 /*is_dwp*/);
8994 }
8995
8996 /* This function is mapped across the sections and remembers the offset and
8997    size of each of the DWO debugging sections we are interested in.  */
8998
8999 static void
9000 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
9001 {
9002   struct dwo_sections *dwo_sections = dwo_sections_ptr;
9003   const struct dwop_section_names *names = &dwop_section_names;
9004
9005   if (section_is_p (sectp->name, &names->abbrev_dwo))
9006     {
9007       dwo_sections->abbrev.asection = sectp;
9008       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
9009     }
9010   else if (section_is_p (sectp->name, &names->info_dwo))
9011     {
9012       dwo_sections->info.asection = sectp;
9013       dwo_sections->info.size = bfd_get_section_size (sectp);
9014     }
9015   else if (section_is_p (sectp->name, &names->line_dwo))
9016     {
9017       dwo_sections->line.asection = sectp;
9018       dwo_sections->line.size = bfd_get_section_size (sectp);
9019     }
9020   else if (section_is_p (sectp->name, &names->loc_dwo))
9021     {
9022       dwo_sections->loc.asection = sectp;
9023       dwo_sections->loc.size = bfd_get_section_size (sectp);
9024     }
9025   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9026     {
9027       dwo_sections->macinfo.asection = sectp;
9028       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
9029     }
9030   else if (section_is_p (sectp->name, &names->macro_dwo))
9031     {
9032       dwo_sections->macro.asection = sectp;
9033       dwo_sections->macro.size = bfd_get_section_size (sectp);
9034     }
9035   else if (section_is_p (sectp->name, &names->str_dwo))
9036     {
9037       dwo_sections->str.asection = sectp;
9038       dwo_sections->str.size = bfd_get_section_size (sectp);
9039     }
9040   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9041     {
9042       dwo_sections->str_offsets.asection = sectp;
9043       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
9044     }
9045   else if (section_is_p (sectp->name, &names->types_dwo))
9046     {
9047       struct dwarf2_section_info type_section;
9048
9049       memset (&type_section, 0, sizeof (type_section));
9050       type_section.asection = sectp;
9051       type_section.size = bfd_get_section_size (sectp);
9052       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
9053                      &type_section);
9054     }
9055 }
9056
9057 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
9058    by PER_CU.
9059    The result is NULL if DWO_NAME can't be found.  */
9060
9061 static struct dwo_file *
9062 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
9063                         const char *dwo_name, const char *comp_dir)
9064 {
9065   struct objfile *objfile = dwarf2_per_objfile->objfile;
9066   struct dwo_file *dwo_file;
9067   bfd *dbfd;
9068   struct cleanup *cleanups;
9069
9070   dbfd = open_dwo_file (dwo_name, comp_dir);
9071   if (dbfd == NULL)
9072     {
9073       if (dwarf2_read_debug)
9074         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
9075       return NULL;
9076     }
9077   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9078   dwo_file->dwo_name = dwo_name;
9079   dwo_file->comp_dir = comp_dir;
9080   dwo_file->dbfd = dbfd;
9081
9082   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
9083
9084   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
9085
9086   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
9087
9088   dwo_file->tus = create_debug_types_hash_table (dwo_file,
9089                                                  dwo_file->sections.types);
9090
9091   discard_cleanups (cleanups);
9092
9093   if (dwarf2_read_debug)
9094     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
9095
9096   return dwo_file;
9097 }
9098
9099 /* This function is mapped across the sections and remembers the offset and
9100    size of each of the DWP debugging sections we are interested in.  */
9101
9102 static void
9103 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
9104 {
9105   struct dwp_file *dwp_file = dwp_file_ptr;
9106   const struct dwop_section_names *names = &dwop_section_names;
9107   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9108
9109   /* Record the ELF section number for later lookup: this is what the
9110      .debug_cu_index,.debug_tu_index tables use.  */
9111   gdb_assert (elf_section_nr < dwp_file->num_sections);
9112   dwp_file->elf_sections[elf_section_nr] = sectp;
9113
9114   /* Look for specific sections that we need.  */
9115   if (section_is_p (sectp->name, &names->str_dwo))
9116     {
9117       dwp_file->sections.str.asection = sectp;
9118       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9119     }
9120   else if (section_is_p (sectp->name, &names->cu_index))
9121     {
9122       dwp_file->sections.cu_index.asection = sectp;
9123       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9124     }
9125   else if (section_is_p (sectp->name, &names->tu_index))
9126     {
9127       dwp_file->sections.tu_index.asection = sectp;
9128       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9129     }
9130 }
9131
9132 /* Hash function for dwp_file loaded CUs/TUs.  */
9133
9134 static hashval_t
9135 hash_dwp_loaded_cutus (const void *item)
9136 {
9137   const struct dwo_unit *dwo_unit = item;
9138
9139   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9140   return dwo_unit->signature;
9141 }
9142
9143 /* Equality function for dwp_file loaded CUs/TUs.  */
9144
9145 static int
9146 eq_dwp_loaded_cutus (const void *a, const void *b)
9147 {
9148   const struct dwo_unit *dua = a;
9149   const struct dwo_unit *dub = b;
9150
9151   return dua->signature == dub->signature;
9152 }
9153
9154 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9155
9156 static htab_t
9157 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9158 {
9159   return htab_create_alloc_ex (3,
9160                                hash_dwp_loaded_cutus,
9161                                eq_dwp_loaded_cutus,
9162                                NULL,
9163                                &objfile->objfile_obstack,
9164                                hashtab_obstack_allocate,
9165                                dummy_obstack_deallocate);
9166 }
9167
9168 /* Try to open DWP file FILE_NAME.
9169    The result is the bfd handle of the file.
9170    If there is a problem finding or opening the file, return NULL.
9171    Upon success, the canonicalized path of the file is stored in the bfd,
9172    same as symfile_bfd_open.  */
9173
9174 static bfd *
9175 open_dwp_file (const char *file_name)
9176 {
9177   return try_open_dwop_file (file_name, 1 /*is_dwp*/);
9178 }
9179
9180 /* Initialize the use of the DWP file for the current objfile.
9181    By convention the name of the DWP file is ${objfile}.dwp.
9182    The result is NULL if it can't be found.  */
9183
9184 static struct dwp_file *
9185 open_and_init_dwp_file (void)
9186 {
9187   struct objfile *objfile = dwarf2_per_objfile->objfile;
9188   struct dwp_file *dwp_file;
9189   char *dwp_name;
9190   bfd *dbfd;
9191   struct cleanup *cleanups;
9192
9193   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9194   cleanups = make_cleanup (xfree, dwp_name);
9195
9196   dbfd = open_dwp_file (dwp_name);
9197   if (dbfd == NULL)
9198     {
9199       if (dwarf2_read_debug)
9200         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9201       do_cleanups (cleanups);
9202       return NULL;
9203     }
9204   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9205   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9206                                   dwp_name, strlen (dwp_name));
9207   dwp_file->dbfd = dbfd;
9208   do_cleanups (cleanups);
9209
9210   /* +1: section 0 is unused */
9211   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9212   dwp_file->elf_sections =
9213     OBSTACK_CALLOC (&objfile->objfile_obstack,
9214                     dwp_file->num_sections, asection *);
9215
9216   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9217
9218   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9219
9220   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9221
9222   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9223
9224   if (dwarf2_read_debug)
9225     {
9226       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9227       fprintf_unfiltered (gdb_stdlog,
9228                           "    %u CUs, %u TUs\n",
9229                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9230                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9231     }
9232
9233   return dwp_file;
9234 }
9235
9236 /* Wrapper around open_and_init_dwp_file, only open it once.  */
9237
9238 static struct dwp_file *
9239 get_dwp_file (void)
9240 {
9241   if (! dwarf2_per_objfile->dwp_checked)
9242     {
9243       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
9244       dwarf2_per_objfile->dwp_checked = 1;
9245     }
9246   return dwarf2_per_objfile->dwp_file;
9247 }
9248
9249 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9250    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9251    or in the DWP file for the objfile, referenced by THIS_UNIT.
9252    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9253    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9254
9255    This is called, for example, when wanting to read a variable with a
9256    complex location.  Therefore we don't want to do file i/o for every call.
9257    Therefore we don't want to look for a DWO file on every call.
9258    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9259    then we check if we've already seen DWO_NAME, and only THEN do we check
9260    for a DWO file.
9261
9262    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9263    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9264
9265 static struct dwo_unit *
9266 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9267                  const char *dwo_name, const char *comp_dir,
9268                  ULONGEST signature, int is_debug_types)
9269 {
9270   struct objfile *objfile = dwarf2_per_objfile->objfile;
9271   const char *kind = is_debug_types ? "TU" : "CU";
9272   void **dwo_file_slot;
9273   struct dwo_file *dwo_file;
9274   struct dwp_file *dwp_file;
9275
9276   /* Have we already read SIGNATURE from a DWP file?  */
9277
9278   dwp_file = get_dwp_file ();
9279   if (dwp_file != NULL)
9280     {
9281       const struct dwp_hash_table *dwp_htab =
9282         is_debug_types ? dwp_file->tus : dwp_file->cus;
9283
9284       if (dwp_htab != NULL)
9285         {
9286           struct dwo_unit *dwo_cutu =
9287             lookup_dwo_in_dwp (dwp_file, dwp_htab, comp_dir,
9288                                signature, is_debug_types);
9289
9290           if (dwo_cutu != NULL)
9291             {
9292               if (dwarf2_read_debug)
9293                 {
9294                   fprintf_unfiltered (gdb_stdlog,
9295                                       "Virtual DWO %s %s found: @%s\n",
9296                                       kind, hex_string (signature),
9297                                       host_address_to_string (dwo_cutu));
9298                 }
9299               return dwo_cutu;
9300             }
9301         }
9302     }
9303
9304   /* Have we already seen DWO_NAME?  */
9305
9306   dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
9307   if (*dwo_file_slot == NULL)
9308     {
9309       /* Read in the file and build a table of the DWOs it contains.  */
9310       *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
9311     }
9312   /* NOTE: This will be NULL if unable to open the file.  */
9313   dwo_file = *dwo_file_slot;
9314
9315   if (dwo_file != NULL)
9316     {
9317       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9318
9319       if (htab != NULL)
9320         {
9321           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9322
9323           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9324           find_dwo_cutu.signature = signature;
9325           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9326
9327           if (dwo_cutu != NULL)
9328             {
9329               if (dwarf2_read_debug)
9330                 {
9331                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9332                                       kind, dwo_name, hex_string (signature),
9333                                       host_address_to_string (dwo_cutu));
9334                 }
9335               return dwo_cutu;
9336             }
9337         }
9338     }
9339
9340   /* We didn't find it.  This could mean a dwo_id mismatch, or
9341      someone deleted the DWO/DWP file, or the search path isn't set up
9342      correctly to find the file.  */
9343
9344   if (dwarf2_read_debug)
9345     {
9346       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9347                           kind, dwo_name, hex_string (signature));
9348     }
9349
9350   complaint (&symfile_complaints,
9351              _("Could not find DWO %s referenced by CU at offset 0x%x"
9352                " [in module %s]"),
9353              kind, this_unit->offset.sect_off, objfile->name);
9354   return NULL;
9355 }
9356
9357 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9358    See lookup_dwo_cutu_unit for details.  */
9359
9360 static struct dwo_unit *
9361 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9362                       const char *dwo_name, const char *comp_dir,
9363                       ULONGEST signature)
9364 {
9365   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9366 }
9367
9368 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9369    See lookup_dwo_cutu_unit for details.  */
9370
9371 static struct dwo_unit *
9372 lookup_dwo_type_unit (struct signatured_type *this_tu,
9373                       const char *dwo_name, const char *comp_dir)
9374 {
9375   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9376 }
9377
9378 /* Free all resources associated with DWO_FILE.
9379    Close the DWO file and munmap the sections.
9380    All memory should be on the objfile obstack.  */
9381
9382 static void
9383 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9384 {
9385   int ix;
9386   struct dwarf2_section_info *section;
9387
9388   /* Note: dbfd is NULL for virtual DWO files.  */
9389   gdb_bfd_unref (dwo_file->dbfd);
9390
9391   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9392 }
9393
9394 /* Wrapper for free_dwo_file for use in cleanups.  */
9395
9396 static void
9397 free_dwo_file_cleanup (void *arg)
9398 {
9399   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9400   struct objfile *objfile = dwarf2_per_objfile->objfile;
9401
9402   free_dwo_file (dwo_file, objfile);
9403 }
9404
9405 /* Traversal function for free_dwo_files.  */
9406
9407 static int
9408 free_dwo_file_from_slot (void **slot, void *info)
9409 {
9410   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9411   struct objfile *objfile = (struct objfile *) info;
9412
9413   free_dwo_file (dwo_file, objfile);
9414
9415   return 1;
9416 }
9417
9418 /* Free all resources associated with DWO_FILES.  */
9419
9420 static void
9421 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9422 {
9423   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9424 }
9425 \f
9426 /* Read in various DIEs.  */
9427
9428 /* qsort helper for inherit_abstract_dies.  */
9429
9430 static int
9431 unsigned_int_compar (const void *ap, const void *bp)
9432 {
9433   unsigned int a = *(unsigned int *) ap;
9434   unsigned int b = *(unsigned int *) bp;
9435
9436   return (a > b) - (b > a);
9437 }
9438
9439 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9440    Inherit only the children of the DW_AT_abstract_origin DIE not being
9441    already referenced by DW_AT_abstract_origin from the children of the
9442    current DIE.  */
9443
9444 static void
9445 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9446 {
9447   struct die_info *child_die;
9448   unsigned die_children_count;
9449   /* CU offsets which were referenced by children of the current DIE.  */
9450   sect_offset *offsets;
9451   sect_offset *offsets_end, *offsetp;
9452   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9453   struct die_info *origin_die;
9454   /* Iterator of the ORIGIN_DIE children.  */
9455   struct die_info *origin_child_die;
9456   struct cleanup *cleanups;
9457   struct attribute *attr;
9458   struct dwarf2_cu *origin_cu;
9459   struct pending **origin_previous_list_in_scope;
9460
9461   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9462   if (!attr)
9463     return;
9464
9465   /* Note that following die references may follow to a die in a
9466      different cu.  */
9467
9468   origin_cu = cu;
9469   origin_die = follow_die_ref (die, attr, &origin_cu);
9470
9471   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9472      symbols in.  */
9473   origin_previous_list_in_scope = origin_cu->list_in_scope;
9474   origin_cu->list_in_scope = cu->list_in_scope;
9475
9476   if (die->tag != origin_die->tag
9477       && !(die->tag == DW_TAG_inlined_subroutine
9478            && origin_die->tag == DW_TAG_subprogram))
9479     complaint (&symfile_complaints,
9480                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9481                die->offset.sect_off, origin_die->offset.sect_off);
9482
9483   child_die = die->child;
9484   die_children_count = 0;
9485   while (child_die && child_die->tag)
9486     {
9487       child_die = sibling_die (child_die);
9488       die_children_count++;
9489     }
9490   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9491   cleanups = make_cleanup (xfree, offsets);
9492
9493   offsets_end = offsets;
9494   child_die = die->child;
9495   while (child_die && child_die->tag)
9496     {
9497       /* For each CHILD_DIE, find the corresponding child of
9498          ORIGIN_DIE.  If there is more than one layer of
9499          DW_AT_abstract_origin, follow them all; there shouldn't be,
9500          but GCC versions at least through 4.4 generate this (GCC PR
9501          40573).  */
9502       struct die_info *child_origin_die = child_die;
9503       struct dwarf2_cu *child_origin_cu = cu;
9504
9505       while (1)
9506         {
9507           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9508                               child_origin_cu);
9509           if (attr == NULL)
9510             break;
9511           child_origin_die = follow_die_ref (child_origin_die, attr,
9512                                              &child_origin_cu);
9513         }
9514
9515       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9516          counterpart may exist.  */
9517       if (child_origin_die != child_die)
9518         {
9519           if (child_die->tag != child_origin_die->tag
9520               && !(child_die->tag == DW_TAG_inlined_subroutine
9521                    && child_origin_die->tag == DW_TAG_subprogram))
9522             complaint (&symfile_complaints,
9523                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9524                          "different tags"), child_die->offset.sect_off,
9525                        child_origin_die->offset.sect_off);
9526           if (child_origin_die->parent != origin_die)
9527             complaint (&symfile_complaints,
9528                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9529                          "different parents"), child_die->offset.sect_off,
9530                        child_origin_die->offset.sect_off);
9531           else
9532             *offsets_end++ = child_origin_die->offset;
9533         }
9534       child_die = sibling_die (child_die);
9535     }
9536   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9537          unsigned_int_compar);
9538   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9539     if (offsetp[-1].sect_off == offsetp->sect_off)
9540       complaint (&symfile_complaints,
9541                  _("Multiple children of DIE 0x%x refer "
9542                    "to DIE 0x%x as their abstract origin"),
9543                  die->offset.sect_off, offsetp->sect_off);
9544
9545   offsetp = offsets;
9546   origin_child_die = origin_die->child;
9547   while (origin_child_die && origin_child_die->tag)
9548     {
9549       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9550       while (offsetp < offsets_end
9551              && offsetp->sect_off < origin_child_die->offset.sect_off)
9552         offsetp++;
9553       if (offsetp >= offsets_end
9554           || offsetp->sect_off > origin_child_die->offset.sect_off)
9555         {
9556           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9557           process_die (origin_child_die, origin_cu);
9558         }
9559       origin_child_die = sibling_die (origin_child_die);
9560     }
9561   origin_cu->list_in_scope = origin_previous_list_in_scope;
9562
9563   do_cleanups (cleanups);
9564 }
9565
9566 static void
9567 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9568 {
9569   struct objfile *objfile = cu->objfile;
9570   struct context_stack *new;
9571   CORE_ADDR lowpc;
9572   CORE_ADDR highpc;
9573   struct die_info *child_die;
9574   struct attribute *attr, *call_line, *call_file;
9575   const char *name;
9576   CORE_ADDR baseaddr;
9577   struct block *block;
9578   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9579   VEC (symbolp) *template_args = NULL;
9580   struct template_symbol *templ_func = NULL;
9581
9582   if (inlined_func)
9583     {
9584       /* If we do not have call site information, we can't show the
9585          caller of this inlined function.  That's too confusing, so
9586          only use the scope for local variables.  */
9587       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9588       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9589       if (call_line == NULL || call_file == NULL)
9590         {
9591           read_lexical_block_scope (die, cu);
9592           return;
9593         }
9594     }
9595
9596   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9597
9598   name = dwarf2_name (die, cu);
9599
9600   /* Ignore functions with missing or empty names.  These are actually
9601      illegal according to the DWARF standard.  */
9602   if (name == NULL)
9603     {
9604       complaint (&symfile_complaints,
9605                  _("missing name for subprogram DIE at %d"),
9606                  die->offset.sect_off);
9607       return;
9608     }
9609
9610   /* Ignore functions with missing or invalid low and high pc attributes.  */
9611   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9612     {
9613       attr = dwarf2_attr (die, DW_AT_external, cu);
9614       if (!attr || !DW_UNSND (attr))
9615         complaint (&symfile_complaints,
9616                    _("cannot get low and high bounds "
9617                      "for subprogram DIE at %d"),
9618                    die->offset.sect_off);
9619       return;
9620     }
9621
9622   lowpc += baseaddr;
9623   highpc += baseaddr;
9624
9625   /* If we have any template arguments, then we must allocate a
9626      different sort of symbol.  */
9627   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9628     {
9629       if (child_die->tag == DW_TAG_template_type_param
9630           || child_die->tag == DW_TAG_template_value_param)
9631         {
9632           templ_func = allocate_template_symbol (objfile);
9633           templ_func->base.is_cplus_template_function = 1;
9634           break;
9635         }
9636     }
9637
9638   new = push_context (0, lowpc);
9639   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9640                                (struct symbol *) templ_func);
9641
9642   /* If there is a location expression for DW_AT_frame_base, record
9643      it.  */
9644   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9645   if (attr)
9646     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
9647
9648   cu->list_in_scope = &local_symbols;
9649
9650   if (die->child != NULL)
9651     {
9652       child_die = die->child;
9653       while (child_die && child_die->tag)
9654         {
9655           if (child_die->tag == DW_TAG_template_type_param
9656               || child_die->tag == DW_TAG_template_value_param)
9657             {
9658               struct symbol *arg = new_symbol (child_die, NULL, cu);
9659
9660               if (arg != NULL)
9661                 VEC_safe_push (symbolp, template_args, arg);
9662             }
9663           else
9664             process_die (child_die, cu);
9665           child_die = sibling_die (child_die);
9666         }
9667     }
9668
9669   inherit_abstract_dies (die, cu);
9670
9671   /* If we have a DW_AT_specification, we might need to import using
9672      directives from the context of the specification DIE.  See the
9673      comment in determine_prefix.  */
9674   if (cu->language == language_cplus
9675       && dwarf2_attr (die, DW_AT_specification, cu))
9676     {
9677       struct dwarf2_cu *spec_cu = cu;
9678       struct die_info *spec_die = die_specification (die, &spec_cu);
9679
9680       while (spec_die)
9681         {
9682           child_die = spec_die->child;
9683           while (child_die && child_die->tag)
9684             {
9685               if (child_die->tag == DW_TAG_imported_module)
9686                 process_die (child_die, spec_cu);
9687               child_die = sibling_die (child_die);
9688             }
9689
9690           /* In some cases, GCC generates specification DIEs that
9691              themselves contain DW_AT_specification attributes.  */
9692           spec_die = die_specification (spec_die, &spec_cu);
9693         }
9694     }
9695
9696   new = pop_context ();
9697   /* Make a block for the local symbols within.  */
9698   block = finish_block (new->name, &local_symbols, new->old_blocks,
9699                         lowpc, highpc, objfile);
9700
9701   /* For C++, set the block's scope.  */
9702   if ((cu->language == language_cplus || cu->language == language_fortran)
9703       && cu->processing_has_namespace_info)
9704     block_set_scope (block, determine_prefix (die, cu),
9705                      &objfile->objfile_obstack);
9706
9707   /* If we have address ranges, record them.  */
9708   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9709
9710   /* Attach template arguments to function.  */
9711   if (! VEC_empty (symbolp, template_args))
9712     {
9713       gdb_assert (templ_func != NULL);
9714
9715       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9716       templ_func->template_arguments
9717         = obstack_alloc (&objfile->objfile_obstack,
9718                          (templ_func->n_template_arguments
9719                           * sizeof (struct symbol *)));
9720       memcpy (templ_func->template_arguments,
9721               VEC_address (symbolp, template_args),
9722               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9723       VEC_free (symbolp, template_args);
9724     }
9725
9726   /* In C++, we can have functions nested inside functions (e.g., when
9727      a function declares a class that has methods).  This means that
9728      when we finish processing a function scope, we may need to go
9729      back to building a containing block's symbol lists.  */
9730   local_symbols = new->locals;
9731   using_directives = new->using_directives;
9732
9733   /* If we've finished processing a top-level function, subsequent
9734      symbols go in the file symbol list.  */
9735   if (outermost_context_p ())
9736     cu->list_in_scope = &file_symbols;
9737 }
9738
9739 /* Process all the DIES contained within a lexical block scope.  Start
9740    a new scope, process the dies, and then close the scope.  */
9741
9742 static void
9743 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9744 {
9745   struct objfile *objfile = cu->objfile;
9746   struct context_stack *new;
9747   CORE_ADDR lowpc, highpc;
9748   struct die_info *child_die;
9749   CORE_ADDR baseaddr;
9750
9751   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9752
9753   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9754   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9755      as multiple lexical blocks?  Handling children in a sane way would
9756      be nasty.  Might be easier to properly extend generic blocks to
9757      describe ranges.  */
9758   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9759     return;
9760   lowpc += baseaddr;
9761   highpc += baseaddr;
9762
9763   push_context (0, lowpc);
9764   if (die->child != NULL)
9765     {
9766       child_die = die->child;
9767       while (child_die && child_die->tag)
9768         {
9769           process_die (child_die, cu);
9770           child_die = sibling_die (child_die);
9771         }
9772     }
9773   new = pop_context ();
9774
9775   if (local_symbols != NULL || using_directives != NULL)
9776     {
9777       struct block *block
9778         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9779                         highpc, objfile);
9780
9781       /* Note that recording ranges after traversing children, as we
9782          do here, means that recording a parent's ranges entails
9783          walking across all its children's ranges as they appear in
9784          the address map, which is quadratic behavior.
9785
9786          It would be nicer to record the parent's ranges before
9787          traversing its children, simply overriding whatever you find
9788          there.  But since we don't even decide whether to create a
9789          block until after we've traversed its children, that's hard
9790          to do.  */
9791       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9792     }
9793   local_symbols = new->locals;
9794   using_directives = new->using_directives;
9795 }
9796
9797 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9798
9799 static void
9800 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9801 {
9802   struct objfile *objfile = cu->objfile;
9803   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9804   CORE_ADDR pc, baseaddr;
9805   struct attribute *attr;
9806   struct call_site *call_site, call_site_local;
9807   void **slot;
9808   int nparams;
9809   struct die_info *child_die;
9810
9811   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9812
9813   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9814   if (!attr)
9815     {
9816       complaint (&symfile_complaints,
9817                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9818                    "DIE 0x%x [in module %s]"),
9819                  die->offset.sect_off, objfile->name);
9820       return;
9821     }
9822   pc = DW_ADDR (attr) + baseaddr;
9823
9824   if (cu->call_site_htab == NULL)
9825     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9826                                                NULL, &objfile->objfile_obstack,
9827                                                hashtab_obstack_allocate, NULL);
9828   call_site_local.pc = pc;
9829   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9830   if (*slot != NULL)
9831     {
9832       complaint (&symfile_complaints,
9833                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9834                    "DIE 0x%x [in module %s]"),
9835                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9836       return;
9837     }
9838
9839   /* Count parameters at the caller.  */
9840
9841   nparams = 0;
9842   for (child_die = die->child; child_die && child_die->tag;
9843        child_die = sibling_die (child_die))
9844     {
9845       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9846         {
9847           complaint (&symfile_complaints,
9848                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9849                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9850                      child_die->tag, child_die->offset.sect_off, objfile->name);
9851           continue;
9852         }
9853
9854       nparams++;
9855     }
9856
9857   call_site = obstack_alloc (&objfile->objfile_obstack,
9858                              (sizeof (*call_site)
9859                               + (sizeof (*call_site->parameter)
9860                                  * (nparams - 1))));
9861   *slot = call_site;
9862   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9863   call_site->pc = pc;
9864
9865   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9866     {
9867       struct die_info *func_die;
9868
9869       /* Skip also over DW_TAG_inlined_subroutine.  */
9870       for (func_die = die->parent;
9871            func_die && func_die->tag != DW_TAG_subprogram
9872            && func_die->tag != DW_TAG_subroutine_type;
9873            func_die = func_die->parent);
9874
9875       /* DW_AT_GNU_all_call_sites is a superset
9876          of DW_AT_GNU_all_tail_call_sites.  */
9877       if (func_die
9878           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9879           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9880         {
9881           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9882              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9883              both the initial caller containing the real return address PC and
9884              the final callee containing the current PC of a chain of tail
9885              calls do not need to have the tail call list complete.  But any
9886              function candidate for a virtual tail call frame searched via
9887              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9888              determined unambiguously.  */
9889         }
9890       else
9891         {
9892           struct type *func_type = NULL;
9893
9894           if (func_die)
9895             func_type = get_die_type (func_die, cu);
9896           if (func_type != NULL)
9897             {
9898               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9899
9900               /* Enlist this call site to the function.  */
9901               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9902               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9903             }
9904           else
9905             complaint (&symfile_complaints,
9906                        _("Cannot find function owning DW_TAG_GNU_call_site "
9907                          "DIE 0x%x [in module %s]"),
9908                        die->offset.sect_off, objfile->name);
9909         }
9910     }
9911
9912   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9913   if (attr == NULL)
9914     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9915   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9916   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9917     /* Keep NULL DWARF_BLOCK.  */;
9918   else if (attr_form_is_block (attr))
9919     {
9920       struct dwarf2_locexpr_baton *dlbaton;
9921
9922       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9923       dlbaton->data = DW_BLOCK (attr)->data;
9924       dlbaton->size = DW_BLOCK (attr)->size;
9925       dlbaton->per_cu = cu->per_cu;
9926
9927       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9928     }
9929   else if (is_ref_attr (attr))
9930     {
9931       struct dwarf2_cu *target_cu = cu;
9932       struct die_info *target_die;
9933
9934       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9935       gdb_assert (target_cu->objfile == objfile);
9936       if (die_is_declaration (target_die, target_cu))
9937         {
9938           const char *target_physname = NULL;
9939           struct attribute *target_attr;
9940
9941           /* Prefer the mangled name; otherwise compute the demangled one.  */
9942           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
9943           if (target_attr == NULL)
9944             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
9945                                        target_cu);
9946           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
9947             target_physname = DW_STRING (target_attr);
9948           else
9949             target_physname = dwarf2_physname (NULL, target_die, target_cu);
9950           if (target_physname == NULL)
9951             complaint (&symfile_complaints,
9952                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9953                          "physname, for referencing DIE 0x%x [in module %s]"),
9954                        die->offset.sect_off, objfile->name);
9955           else
9956             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9957         }
9958       else
9959         {
9960           CORE_ADDR lowpc;
9961
9962           /* DW_AT_entry_pc should be preferred.  */
9963           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9964             complaint (&symfile_complaints,
9965                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9966                          "low pc, for referencing DIE 0x%x [in module %s]"),
9967                        die->offset.sect_off, objfile->name);
9968           else
9969             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9970         }
9971     }
9972   else
9973     complaint (&symfile_complaints,
9974                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9975                  "block nor reference, for DIE 0x%x [in module %s]"),
9976                die->offset.sect_off, objfile->name);
9977
9978   call_site->per_cu = cu->per_cu;
9979
9980   for (child_die = die->child;
9981        child_die && child_die->tag;
9982        child_die = sibling_die (child_die))
9983     {
9984       struct call_site_parameter *parameter;
9985       struct attribute *loc, *origin;
9986
9987       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9988         {
9989           /* Already printed the complaint above.  */
9990           continue;
9991         }
9992
9993       gdb_assert (call_site->parameter_count < nparams);
9994       parameter = &call_site->parameter[call_site->parameter_count];
9995
9996       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
9997          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
9998          register is contained in DW_AT_GNU_call_site_value.  */
9999
10000       loc = dwarf2_attr (child_die, DW_AT_location, cu);
10001       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
10002       if (loc == NULL && origin != NULL && is_ref_attr (origin))
10003         {
10004           sect_offset offset;
10005
10006           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
10007           offset = dwarf2_get_ref_die_offset (origin);
10008           if (!offset_in_cu_p (&cu->header, offset))
10009             {
10010               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
10011                  binding can be done only inside one CU.  Such referenced DIE
10012                  therefore cannot be even moved to DW_TAG_partial_unit.  */
10013               complaint (&symfile_complaints,
10014                          _("DW_AT_abstract_origin offset is not in CU for "
10015                            "DW_TAG_GNU_call_site child DIE 0x%x "
10016                            "[in module %s]"),
10017                          child_die->offset.sect_off, objfile->name);
10018               continue;
10019             }
10020           parameter->u.param_offset.cu_off = (offset.sect_off
10021                                               - cu->header.offset.sect_off);
10022         }
10023       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
10024         {
10025           complaint (&symfile_complaints,
10026                      _("No DW_FORM_block* DW_AT_location for "
10027                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10028                      child_die->offset.sect_off, objfile->name);
10029           continue;
10030         }
10031       else
10032         {
10033           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
10034             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
10035           if (parameter->u.dwarf_reg != -1)
10036             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
10037           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
10038                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
10039                                              &parameter->u.fb_offset))
10040             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
10041           else
10042             {
10043               complaint (&symfile_complaints,
10044                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
10045                            "for DW_FORM_block* DW_AT_location is supported for "
10046                            "DW_TAG_GNU_call_site child DIE 0x%x "
10047                            "[in module %s]"),
10048                          child_die->offset.sect_off, objfile->name);
10049               continue;
10050             }
10051         }
10052
10053       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
10054       if (!attr_form_is_block (attr))
10055         {
10056           complaint (&symfile_complaints,
10057                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
10058                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10059                      child_die->offset.sect_off, objfile->name);
10060           continue;
10061         }
10062       parameter->value = DW_BLOCK (attr)->data;
10063       parameter->value_size = DW_BLOCK (attr)->size;
10064
10065       /* Parameters are not pre-cleared by memset above.  */
10066       parameter->data_value = NULL;
10067       parameter->data_value_size = 0;
10068       call_site->parameter_count++;
10069
10070       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
10071       if (attr)
10072         {
10073           if (!attr_form_is_block (attr))
10074             complaint (&symfile_complaints,
10075                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
10076                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
10077                        child_die->offset.sect_off, objfile->name);
10078           else
10079             {
10080               parameter->data_value = DW_BLOCK (attr)->data;
10081               parameter->data_value_size = DW_BLOCK (attr)->size;
10082             }
10083         }
10084     }
10085 }
10086
10087 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
10088    Return 1 if the attributes are present and valid, otherwise, return 0.
10089    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
10090
10091 static int
10092 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
10093                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
10094                     struct partial_symtab *ranges_pst)
10095 {
10096   struct objfile *objfile = cu->objfile;
10097   struct comp_unit_head *cu_header = &cu->header;
10098   bfd *obfd = objfile->obfd;
10099   unsigned int addr_size = cu_header->addr_size;
10100   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10101   /* Base address selection entry.  */
10102   CORE_ADDR base;
10103   int found_base;
10104   unsigned int dummy;
10105   const gdb_byte *buffer;
10106   CORE_ADDR marker;
10107   int low_set;
10108   CORE_ADDR low = 0;
10109   CORE_ADDR high = 0;
10110   CORE_ADDR baseaddr;
10111
10112   found_base = cu->base_known;
10113   base = cu->base_address;
10114
10115   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
10116   if (offset >= dwarf2_per_objfile->ranges.size)
10117     {
10118       complaint (&symfile_complaints,
10119                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
10120                  offset);
10121       return 0;
10122     }
10123   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10124
10125   /* Read in the largest possible address.  */
10126   marker = read_address (obfd, buffer, cu, &dummy);
10127   if ((marker & mask) == mask)
10128     {
10129       /* If we found the largest possible address, then
10130          read the base address.  */
10131       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10132       buffer += 2 * addr_size;
10133       offset += 2 * addr_size;
10134       found_base = 1;
10135     }
10136
10137   low_set = 0;
10138
10139   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10140
10141   while (1)
10142     {
10143       CORE_ADDR range_beginning, range_end;
10144
10145       range_beginning = read_address (obfd, buffer, cu, &dummy);
10146       buffer += addr_size;
10147       range_end = read_address (obfd, buffer, cu, &dummy);
10148       buffer += addr_size;
10149       offset += 2 * addr_size;
10150
10151       /* An end of list marker is a pair of zero addresses.  */
10152       if (range_beginning == 0 && range_end == 0)
10153         /* Found the end of list entry.  */
10154         break;
10155
10156       /* Each base address selection entry is a pair of 2 values.
10157          The first is the largest possible address, the second is
10158          the base address.  Check for a base address here.  */
10159       if ((range_beginning & mask) == mask)
10160         {
10161           /* If we found the largest possible address, then
10162              read the base address.  */
10163           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10164           found_base = 1;
10165           continue;
10166         }
10167
10168       if (!found_base)
10169         {
10170           /* We have no valid base address for the ranges
10171              data.  */
10172           complaint (&symfile_complaints,
10173                      _("Invalid .debug_ranges data (no base address)"));
10174           return 0;
10175         }
10176
10177       if (range_beginning > range_end)
10178         {
10179           /* Inverted range entries are invalid.  */
10180           complaint (&symfile_complaints,
10181                      _("Invalid .debug_ranges data (inverted range)"));
10182           return 0;
10183         }
10184
10185       /* Empty range entries have no effect.  */
10186       if (range_beginning == range_end)
10187         continue;
10188
10189       range_beginning += base;
10190       range_end += base;
10191
10192       /* A not-uncommon case of bad debug info.
10193          Don't pollute the addrmap with bad data.  */
10194       if (range_beginning + baseaddr == 0
10195           && !dwarf2_per_objfile->has_section_at_zero)
10196         {
10197           complaint (&symfile_complaints,
10198                      _(".debug_ranges entry has start address of zero"
10199                        " [in module %s]"), objfile->name);
10200           continue;
10201         }
10202
10203       if (ranges_pst != NULL)
10204         addrmap_set_empty (objfile->psymtabs_addrmap,
10205                            range_beginning + baseaddr,
10206                            range_end - 1 + baseaddr,
10207                            ranges_pst);
10208
10209       /* FIXME: This is recording everything as a low-high
10210          segment of consecutive addresses.  We should have a
10211          data structure for discontiguous block ranges
10212          instead.  */
10213       if (! low_set)
10214         {
10215           low = range_beginning;
10216           high = range_end;
10217           low_set = 1;
10218         }
10219       else
10220         {
10221           if (range_beginning < low)
10222             low = range_beginning;
10223           if (range_end > high)
10224             high = range_end;
10225         }
10226     }
10227
10228   if (! low_set)
10229     /* If the first entry is an end-of-list marker, the range
10230        describes an empty scope, i.e. no instructions.  */
10231     return 0;
10232
10233   if (low_return)
10234     *low_return = low;
10235   if (high_return)
10236     *high_return = high;
10237   return 1;
10238 }
10239
10240 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10241    are present and valid, otherwise, return 0.  Return -1 if the range is
10242    discontinuous, i.e. derived from DW_AT_ranges information.  */
10243
10244 static int
10245 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10246                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10247                       struct partial_symtab *pst)
10248 {
10249   struct attribute *attr;
10250   struct attribute *attr_high;
10251   CORE_ADDR low = 0;
10252   CORE_ADDR high = 0;
10253   int ret = 0;
10254
10255   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10256   if (attr_high)
10257     {
10258       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10259       if (attr)
10260         {
10261           low = DW_ADDR (attr);
10262           if (attr_high->form == DW_FORM_addr
10263               || attr_high->form == DW_FORM_GNU_addr_index)
10264             high = DW_ADDR (attr_high);
10265           else
10266             high = low + DW_UNSND (attr_high);
10267         }
10268       else
10269         /* Found high w/o low attribute.  */
10270         return 0;
10271
10272       /* Found consecutive range of addresses.  */
10273       ret = 1;
10274     }
10275   else
10276     {
10277       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10278       if (attr != NULL)
10279         {
10280           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10281              We take advantage of the fact that DW_AT_ranges does not appear
10282              in DW_TAG_compile_unit of DWO files.  */
10283           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10284           unsigned int ranges_offset = (DW_UNSND (attr)
10285                                         + (need_ranges_base
10286                                            ? cu->ranges_base
10287                                            : 0));
10288
10289           /* Value of the DW_AT_ranges attribute is the offset in the
10290              .debug_ranges section.  */
10291           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10292             return 0;
10293           /* Found discontinuous range of addresses.  */
10294           ret = -1;
10295         }
10296     }
10297
10298   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10299   if (high <= low)
10300     return 0;
10301
10302   /* When using the GNU linker, .gnu.linkonce. sections are used to
10303      eliminate duplicate copies of functions and vtables and such.
10304      The linker will arbitrarily choose one and discard the others.
10305      The AT_*_pc values for such functions refer to local labels in
10306      these sections.  If the section from that file was discarded, the
10307      labels are not in the output, so the relocs get a value of 0.
10308      If this is a discarded function, mark the pc bounds as invalid,
10309      so that GDB will ignore it.  */
10310   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10311     return 0;
10312
10313   *lowpc = low;
10314   if (highpc)
10315     *highpc = high;
10316   return ret;
10317 }
10318
10319 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10320    its low and high PC addresses.  Do nothing if these addresses could not
10321    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10322    and HIGHPC to the high address if greater than HIGHPC.  */
10323
10324 static void
10325 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10326                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10327                                  struct dwarf2_cu *cu)
10328 {
10329   CORE_ADDR low, high;
10330   struct die_info *child = die->child;
10331
10332   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10333     {
10334       *lowpc = min (*lowpc, low);
10335       *highpc = max (*highpc, high);
10336     }
10337
10338   /* If the language does not allow nested subprograms (either inside
10339      subprograms or lexical blocks), we're done.  */
10340   if (cu->language != language_ada)
10341     return;
10342
10343   /* Check all the children of the given DIE.  If it contains nested
10344      subprograms, then check their pc bounds.  Likewise, we need to
10345      check lexical blocks as well, as they may also contain subprogram
10346      definitions.  */
10347   while (child && child->tag)
10348     {
10349       if (child->tag == DW_TAG_subprogram
10350           || child->tag == DW_TAG_lexical_block)
10351         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10352       child = sibling_die (child);
10353     }
10354 }
10355
10356 /* Get the low and high pc's represented by the scope DIE, and store
10357    them in *LOWPC and *HIGHPC.  If the correct values can't be
10358    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10359
10360 static void
10361 get_scope_pc_bounds (struct die_info *die,
10362                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10363                      struct dwarf2_cu *cu)
10364 {
10365   CORE_ADDR best_low = (CORE_ADDR) -1;
10366   CORE_ADDR best_high = (CORE_ADDR) 0;
10367   CORE_ADDR current_low, current_high;
10368
10369   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10370     {
10371       best_low = current_low;
10372       best_high = current_high;
10373     }
10374   else
10375     {
10376       struct die_info *child = die->child;
10377
10378       while (child && child->tag)
10379         {
10380           switch (child->tag) {
10381           case DW_TAG_subprogram:
10382             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10383             break;
10384           case DW_TAG_namespace:
10385           case DW_TAG_module:
10386             /* FIXME: carlton/2004-01-16: Should we do this for
10387                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10388                that current GCC's always emit the DIEs corresponding
10389                to definitions of methods of classes as children of a
10390                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10391                the DIEs giving the declarations, which could be
10392                anywhere).  But I don't see any reason why the
10393                standards says that they have to be there.  */
10394             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10395
10396             if (current_low != ((CORE_ADDR) -1))
10397               {
10398                 best_low = min (best_low, current_low);
10399                 best_high = max (best_high, current_high);
10400               }
10401             break;
10402           default:
10403             /* Ignore.  */
10404             break;
10405           }
10406
10407           child = sibling_die (child);
10408         }
10409     }
10410
10411   *lowpc = best_low;
10412   *highpc = best_high;
10413 }
10414
10415 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10416    in DIE.  */
10417
10418 static void
10419 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10420                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10421 {
10422   struct objfile *objfile = cu->objfile;
10423   struct attribute *attr;
10424   struct attribute *attr_high;
10425
10426   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10427   if (attr_high)
10428     {
10429       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10430       if (attr)
10431         {
10432           CORE_ADDR low = DW_ADDR (attr);
10433           CORE_ADDR high;
10434           if (attr_high->form == DW_FORM_addr
10435               || attr_high->form == DW_FORM_GNU_addr_index)
10436             high = DW_ADDR (attr_high);
10437           else
10438             high = low + DW_UNSND (attr_high);
10439
10440           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10441         }
10442     }
10443
10444   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10445   if (attr)
10446     {
10447       bfd *obfd = objfile->obfd;
10448       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10449          We take advantage of the fact that DW_AT_ranges does not appear
10450          in DW_TAG_compile_unit of DWO files.  */
10451       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10452
10453       /* The value of the DW_AT_ranges attribute is the offset of the
10454          address range list in the .debug_ranges section.  */
10455       unsigned long offset = (DW_UNSND (attr)
10456                               + (need_ranges_base ? cu->ranges_base : 0));
10457       const gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10458
10459       /* For some target architectures, but not others, the
10460          read_address function sign-extends the addresses it returns.
10461          To recognize base address selection entries, we need a
10462          mask.  */
10463       unsigned int addr_size = cu->header.addr_size;
10464       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10465
10466       /* The base address, to which the next pair is relative.  Note
10467          that this 'base' is a DWARF concept: most entries in a range
10468          list are relative, to reduce the number of relocs against the
10469          debugging information.  This is separate from this function's
10470          'baseaddr' argument, which GDB uses to relocate debugging
10471          information from a shared library based on the address at
10472          which the library was loaded.  */
10473       CORE_ADDR base = cu->base_address;
10474       int base_known = cu->base_known;
10475
10476       gdb_assert (dwarf2_per_objfile->ranges.readin);
10477       if (offset >= dwarf2_per_objfile->ranges.size)
10478         {
10479           complaint (&symfile_complaints,
10480                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10481                      offset);
10482           return;
10483         }
10484
10485       for (;;)
10486         {
10487           unsigned int bytes_read;
10488           CORE_ADDR start, end;
10489
10490           start = read_address (obfd, buffer, cu, &bytes_read);
10491           buffer += bytes_read;
10492           end = read_address (obfd, buffer, cu, &bytes_read);
10493           buffer += bytes_read;
10494
10495           /* Did we find the end of the range list?  */
10496           if (start == 0 && end == 0)
10497             break;
10498
10499           /* Did we find a base address selection entry?  */
10500           else if ((start & base_select_mask) == base_select_mask)
10501             {
10502               base = end;
10503               base_known = 1;
10504             }
10505
10506           /* We found an ordinary address range.  */
10507           else
10508             {
10509               if (!base_known)
10510                 {
10511                   complaint (&symfile_complaints,
10512                              _("Invalid .debug_ranges data "
10513                                "(no base address)"));
10514                   return;
10515                 }
10516
10517               if (start > end)
10518                 {
10519                   /* Inverted range entries are invalid.  */
10520                   complaint (&symfile_complaints,
10521                              _("Invalid .debug_ranges data "
10522                                "(inverted range)"));
10523                   return;
10524                 }
10525
10526               /* Empty range entries have no effect.  */
10527               if (start == end)
10528                 continue;
10529
10530               start += base + baseaddr;
10531               end += base + baseaddr;
10532
10533               /* A not-uncommon case of bad debug info.
10534                  Don't pollute the addrmap with bad data.  */
10535               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10536                 {
10537                   complaint (&symfile_complaints,
10538                              _(".debug_ranges entry has start address of zero"
10539                                " [in module %s]"), objfile->name);
10540                   continue;
10541                 }
10542
10543               record_block_range (block, start, end - 1);
10544             }
10545         }
10546     }
10547 }
10548
10549 /* Check whether the producer field indicates either of GCC < 4.6, or the
10550    Intel C/C++ compiler, and cache the result in CU.  */
10551
10552 static void
10553 check_producer (struct dwarf2_cu *cu)
10554 {
10555   const char *cs;
10556   int major, minor, release;
10557
10558   if (cu->producer == NULL)
10559     {
10560       /* For unknown compilers expect their behavior is DWARF version
10561          compliant.
10562
10563          GCC started to support .debug_types sections by -gdwarf-4 since
10564          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10565          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10566          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10567          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10568     }
10569   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10570     {
10571       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10572
10573       cs = &cu->producer[strlen ("GNU ")];
10574       while (*cs && !isdigit (*cs))
10575         cs++;
10576       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10577         {
10578           /* Not recognized as GCC.  */
10579         }
10580       else
10581         {
10582           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10583           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10584         }
10585     }
10586   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10587     cu->producer_is_icc = 1;
10588   else
10589     {
10590       /* For other non-GCC compilers, expect their behavior is DWARF version
10591          compliant.  */
10592     }
10593
10594   cu->checked_producer = 1;
10595 }
10596
10597 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10598    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10599    during 4.6.0 experimental.  */
10600
10601 static int
10602 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10603 {
10604   if (!cu->checked_producer)
10605     check_producer (cu);
10606
10607   return cu->producer_is_gxx_lt_4_6;
10608 }
10609
10610 /* Return the default accessibility type if it is not overriden by
10611    DW_AT_accessibility.  */
10612
10613 static enum dwarf_access_attribute
10614 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10615 {
10616   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10617     {
10618       /* The default DWARF 2 accessibility for members is public, the default
10619          accessibility for inheritance is private.  */
10620
10621       if (die->tag != DW_TAG_inheritance)
10622         return DW_ACCESS_public;
10623       else
10624         return DW_ACCESS_private;
10625     }
10626   else
10627     {
10628       /* DWARF 3+ defines the default accessibility a different way.  The same
10629          rules apply now for DW_TAG_inheritance as for the members and it only
10630          depends on the container kind.  */
10631
10632       if (die->parent->tag == DW_TAG_class_type)
10633         return DW_ACCESS_private;
10634       else
10635         return DW_ACCESS_public;
10636     }
10637 }
10638
10639 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10640    offset.  If the attribute was not found return 0, otherwise return
10641    1.  If it was found but could not properly be handled, set *OFFSET
10642    to 0.  */
10643
10644 static int
10645 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10646                              LONGEST *offset)
10647 {
10648   struct attribute *attr;
10649
10650   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10651   if (attr != NULL)
10652     {
10653       *offset = 0;
10654
10655       /* Note that we do not check for a section offset first here.
10656          This is because DW_AT_data_member_location is new in DWARF 4,
10657          so if we see it, we can assume that a constant form is really
10658          a constant and not a section offset.  */
10659       if (attr_form_is_constant (attr))
10660         *offset = dwarf2_get_attr_constant_value (attr, 0);
10661       else if (attr_form_is_section_offset (attr))
10662         dwarf2_complex_location_expr_complaint ();
10663       else if (attr_form_is_block (attr))
10664         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10665       else
10666         dwarf2_complex_location_expr_complaint ();
10667
10668       return 1;
10669     }
10670
10671   return 0;
10672 }
10673
10674 /* Add an aggregate field to the field list.  */
10675
10676 static void
10677 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10678                   struct dwarf2_cu *cu)
10679 {
10680   struct objfile *objfile = cu->objfile;
10681   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10682   struct nextfield *new_field;
10683   struct attribute *attr;
10684   struct field *fp;
10685   const char *fieldname = "";
10686
10687   /* Allocate a new field list entry and link it in.  */
10688   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10689   make_cleanup (xfree, new_field);
10690   memset (new_field, 0, sizeof (struct nextfield));
10691
10692   if (die->tag == DW_TAG_inheritance)
10693     {
10694       new_field->next = fip->baseclasses;
10695       fip->baseclasses = new_field;
10696     }
10697   else
10698     {
10699       new_field->next = fip->fields;
10700       fip->fields = new_field;
10701     }
10702   fip->nfields++;
10703
10704   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10705   if (attr)
10706     new_field->accessibility = DW_UNSND (attr);
10707   else
10708     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10709   if (new_field->accessibility != DW_ACCESS_public)
10710     fip->non_public_fields = 1;
10711
10712   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10713   if (attr)
10714     new_field->virtuality = DW_UNSND (attr);
10715   else
10716     new_field->virtuality = DW_VIRTUALITY_none;
10717
10718   fp = &new_field->field;
10719
10720   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10721     {
10722       LONGEST offset;
10723
10724       /* Data member other than a C++ static data member.  */
10725
10726       /* Get type of field.  */
10727       fp->type = die_type (die, cu);
10728
10729       SET_FIELD_BITPOS (*fp, 0);
10730
10731       /* Get bit size of field (zero if none).  */
10732       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10733       if (attr)
10734         {
10735           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10736         }
10737       else
10738         {
10739           FIELD_BITSIZE (*fp) = 0;
10740         }
10741
10742       /* Get bit offset of field.  */
10743       if (handle_data_member_location (die, cu, &offset))
10744         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10745       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10746       if (attr)
10747         {
10748           if (gdbarch_bits_big_endian (gdbarch))
10749             {
10750               /* For big endian bits, the DW_AT_bit_offset gives the
10751                  additional bit offset from the MSB of the containing
10752                  anonymous object to the MSB of the field.  We don't
10753                  have to do anything special since we don't need to
10754                  know the size of the anonymous object.  */
10755               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10756             }
10757           else
10758             {
10759               /* For little endian bits, compute the bit offset to the
10760                  MSB of the anonymous object, subtract off the number of
10761                  bits from the MSB of the field to the MSB of the
10762                  object, and then subtract off the number of bits of
10763                  the field itself.  The result is the bit offset of
10764                  the LSB of the field.  */
10765               int anonymous_size;
10766               int bit_offset = DW_UNSND (attr);
10767
10768               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10769               if (attr)
10770                 {
10771                   /* The size of the anonymous object containing
10772                      the bit field is explicit, so use the
10773                      indicated size (in bytes).  */
10774                   anonymous_size = DW_UNSND (attr);
10775                 }
10776               else
10777                 {
10778                   /* The size of the anonymous object containing
10779                      the bit field must be inferred from the type
10780                      attribute of the data member containing the
10781                      bit field.  */
10782                   anonymous_size = TYPE_LENGTH (fp->type);
10783                 }
10784               SET_FIELD_BITPOS (*fp,
10785                                 (FIELD_BITPOS (*fp)
10786                                  + anonymous_size * bits_per_byte
10787                                  - bit_offset - FIELD_BITSIZE (*fp)));
10788             }
10789         }
10790
10791       /* Get name of field.  */
10792       fieldname = dwarf2_name (die, cu);
10793       if (fieldname == NULL)
10794         fieldname = "";
10795
10796       /* The name is already allocated along with this objfile, so we don't
10797          need to duplicate it for the type.  */
10798       fp->name = fieldname;
10799
10800       /* Change accessibility for artificial fields (e.g. virtual table
10801          pointer or virtual base class pointer) to private.  */
10802       if (dwarf2_attr (die, DW_AT_artificial, cu))
10803         {
10804           FIELD_ARTIFICIAL (*fp) = 1;
10805           new_field->accessibility = DW_ACCESS_private;
10806           fip->non_public_fields = 1;
10807         }
10808     }
10809   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10810     {
10811       /* C++ static member.  */
10812
10813       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10814          is a declaration, but all versions of G++ as of this writing
10815          (so through at least 3.2.1) incorrectly generate
10816          DW_TAG_variable tags.  */
10817
10818       const char *physname;
10819
10820       /* Get name of field.  */
10821       fieldname = dwarf2_name (die, cu);
10822       if (fieldname == NULL)
10823         return;
10824
10825       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10826       if (attr
10827           /* Only create a symbol if this is an external value.
10828              new_symbol checks this and puts the value in the global symbol
10829              table, which we want.  If it is not external, new_symbol
10830              will try to put the value in cu->list_in_scope which is wrong.  */
10831           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10832         {
10833           /* A static const member, not much different than an enum as far as
10834              we're concerned, except that we can support more types.  */
10835           new_symbol (die, NULL, cu);
10836         }
10837
10838       /* Get physical name.  */
10839       physname = dwarf2_physname (fieldname, die, cu);
10840
10841       /* The name is already allocated along with this objfile, so we don't
10842          need to duplicate it for the type.  */
10843       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10844       FIELD_TYPE (*fp) = die_type (die, cu);
10845       FIELD_NAME (*fp) = fieldname;
10846     }
10847   else if (die->tag == DW_TAG_inheritance)
10848     {
10849       LONGEST offset;
10850
10851       /* C++ base class field.  */
10852       if (handle_data_member_location (die, cu, &offset))
10853         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10854       FIELD_BITSIZE (*fp) = 0;
10855       FIELD_TYPE (*fp) = die_type (die, cu);
10856       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10857       fip->nbaseclasses++;
10858     }
10859 }
10860
10861 /* Add a typedef defined in the scope of the FIP's class.  */
10862
10863 static void
10864 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10865                     struct dwarf2_cu *cu)
10866 {
10867   struct objfile *objfile = cu->objfile;
10868   struct typedef_field_list *new_field;
10869   struct attribute *attr;
10870   struct typedef_field *fp;
10871   char *fieldname = "";
10872
10873   /* Allocate a new field list entry and link it in.  */
10874   new_field = xzalloc (sizeof (*new_field));
10875   make_cleanup (xfree, new_field);
10876
10877   gdb_assert (die->tag == DW_TAG_typedef);
10878
10879   fp = &new_field->field;
10880
10881   /* Get name of field.  */
10882   fp->name = dwarf2_name (die, cu);
10883   if (fp->name == NULL)
10884     return;
10885
10886   fp->type = read_type_die (die, cu);
10887
10888   new_field->next = fip->typedef_field_list;
10889   fip->typedef_field_list = new_field;
10890   fip->typedef_field_list_count++;
10891 }
10892
10893 /* Create the vector of fields, and attach it to the type.  */
10894
10895 static void
10896 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10897                               struct dwarf2_cu *cu)
10898 {
10899   int nfields = fip->nfields;
10900
10901   /* Record the field count, allocate space for the array of fields,
10902      and create blank accessibility bitfields if necessary.  */
10903   TYPE_NFIELDS (type) = nfields;
10904   TYPE_FIELDS (type) = (struct field *)
10905     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10906   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10907
10908   if (fip->non_public_fields && cu->language != language_ada)
10909     {
10910       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10911
10912       TYPE_FIELD_PRIVATE_BITS (type) =
10913         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10914       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10915
10916       TYPE_FIELD_PROTECTED_BITS (type) =
10917         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10918       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10919
10920       TYPE_FIELD_IGNORE_BITS (type) =
10921         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10922       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10923     }
10924
10925   /* If the type has baseclasses, allocate and clear a bit vector for
10926      TYPE_FIELD_VIRTUAL_BITS.  */
10927   if (fip->nbaseclasses && cu->language != language_ada)
10928     {
10929       int num_bytes = B_BYTES (fip->nbaseclasses);
10930       unsigned char *pointer;
10931
10932       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10933       pointer = TYPE_ALLOC (type, num_bytes);
10934       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10935       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10936       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10937     }
10938
10939   /* Copy the saved-up fields into the field vector.  Start from the head of
10940      the list, adding to the tail of the field array, so that they end up in
10941      the same order in the array in which they were added to the list.  */
10942   while (nfields-- > 0)
10943     {
10944       struct nextfield *fieldp;
10945
10946       if (fip->fields)
10947         {
10948           fieldp = fip->fields;
10949           fip->fields = fieldp->next;
10950         }
10951       else
10952         {
10953           fieldp = fip->baseclasses;
10954           fip->baseclasses = fieldp->next;
10955         }
10956
10957       TYPE_FIELD (type, nfields) = fieldp->field;
10958       switch (fieldp->accessibility)
10959         {
10960         case DW_ACCESS_private:
10961           if (cu->language != language_ada)
10962             SET_TYPE_FIELD_PRIVATE (type, nfields);
10963           break;
10964
10965         case DW_ACCESS_protected:
10966           if (cu->language != language_ada)
10967             SET_TYPE_FIELD_PROTECTED (type, nfields);
10968           break;
10969
10970         case DW_ACCESS_public:
10971           break;
10972
10973         default:
10974           /* Unknown accessibility.  Complain and treat it as public.  */
10975           {
10976             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10977                        fieldp->accessibility);
10978           }
10979           break;
10980         }
10981       if (nfields < fip->nbaseclasses)
10982         {
10983           switch (fieldp->virtuality)
10984             {
10985             case DW_VIRTUALITY_virtual:
10986             case DW_VIRTUALITY_pure_virtual:
10987               if (cu->language == language_ada)
10988                 error (_("unexpected virtuality in component of Ada type"));
10989               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10990               break;
10991             }
10992         }
10993     }
10994 }
10995
10996 /* Return true if this member function is a constructor, false
10997    otherwise.  */
10998
10999 static int
11000 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
11001 {
11002   const char *fieldname;
11003   const char *typename;
11004   int len;
11005
11006   if (die->parent == NULL)
11007     return 0;
11008
11009   if (die->parent->tag != DW_TAG_structure_type
11010       && die->parent->tag != DW_TAG_union_type
11011       && die->parent->tag != DW_TAG_class_type)
11012     return 0;
11013
11014   fieldname = dwarf2_name (die, cu);
11015   typename = dwarf2_name (die->parent, cu);
11016   if (fieldname == NULL || typename == NULL)
11017     return 0;
11018
11019   len = strlen (fieldname);
11020   return (strncmp (fieldname, typename, len) == 0
11021           && (typename[len] == '\0' || typename[len] == '<'));
11022 }
11023
11024 /* Add a member function to the proper fieldlist.  */
11025
11026 static void
11027 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
11028                       struct type *type, struct dwarf2_cu *cu)
11029 {
11030   struct objfile *objfile = cu->objfile;
11031   struct attribute *attr;
11032   struct fnfieldlist *flp;
11033   int i;
11034   struct fn_field *fnp;
11035   const char *fieldname;
11036   struct nextfnfield *new_fnfield;
11037   struct type *this_type;
11038   enum dwarf_access_attribute accessibility;
11039
11040   if (cu->language == language_ada)
11041     error (_("unexpected member function in Ada type"));
11042
11043   /* Get name of member function.  */
11044   fieldname = dwarf2_name (die, cu);
11045   if (fieldname == NULL)
11046     return;
11047
11048   /* Look up member function name in fieldlist.  */
11049   for (i = 0; i < fip->nfnfields; i++)
11050     {
11051       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
11052         break;
11053     }
11054
11055   /* Create new list element if necessary.  */
11056   if (i < fip->nfnfields)
11057     flp = &fip->fnfieldlists[i];
11058   else
11059     {
11060       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
11061         {
11062           fip->fnfieldlists = (struct fnfieldlist *)
11063             xrealloc (fip->fnfieldlists,
11064                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
11065                       * sizeof (struct fnfieldlist));
11066           if (fip->nfnfields == 0)
11067             make_cleanup (free_current_contents, &fip->fnfieldlists);
11068         }
11069       flp = &fip->fnfieldlists[fip->nfnfields];
11070       flp->name = fieldname;
11071       flp->length = 0;
11072       flp->head = NULL;
11073       i = fip->nfnfields++;
11074     }
11075
11076   /* Create a new member function field and chain it to the field list
11077      entry.  */
11078   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
11079   make_cleanup (xfree, new_fnfield);
11080   memset (new_fnfield, 0, sizeof (struct nextfnfield));
11081   new_fnfield->next = flp->head;
11082   flp->head = new_fnfield;
11083   flp->length++;
11084
11085   /* Fill in the member function field info.  */
11086   fnp = &new_fnfield->fnfield;
11087
11088   /* Delay processing of the physname until later.  */
11089   if (cu->language == language_cplus || cu->language == language_java)
11090     {
11091       add_to_method_list (type, i, flp->length - 1, fieldname,
11092                           die, cu);
11093     }
11094   else
11095     {
11096       const char *physname = dwarf2_physname (fieldname, die, cu);
11097       fnp->physname = physname ? physname : "";
11098     }
11099
11100   fnp->type = alloc_type (objfile);
11101   this_type = read_type_die (die, cu);
11102   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
11103     {
11104       int nparams = TYPE_NFIELDS (this_type);
11105
11106       /* TYPE is the domain of this method, and THIS_TYPE is the type
11107            of the method itself (TYPE_CODE_METHOD).  */
11108       smash_to_method_type (fnp->type, type,
11109                             TYPE_TARGET_TYPE (this_type),
11110                             TYPE_FIELDS (this_type),
11111                             TYPE_NFIELDS (this_type),
11112                             TYPE_VARARGS (this_type));
11113
11114       /* Handle static member functions.
11115          Dwarf2 has no clean way to discern C++ static and non-static
11116          member functions.  G++ helps GDB by marking the first
11117          parameter for non-static member functions (which is the this
11118          pointer) as artificial.  We obtain this information from
11119          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
11120       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11121         fnp->voffset = VOFFSET_STATIC;
11122     }
11123   else
11124     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11125                dwarf2_full_name (fieldname, die, cu));
11126
11127   /* Get fcontext from DW_AT_containing_type if present.  */
11128   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11129     fnp->fcontext = die_containing_type (die, cu);
11130
11131   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11132      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11133
11134   /* Get accessibility.  */
11135   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11136   if (attr)
11137     accessibility = DW_UNSND (attr);
11138   else
11139     accessibility = dwarf2_default_access_attribute (die, cu);
11140   switch (accessibility)
11141     {
11142     case DW_ACCESS_private:
11143       fnp->is_private = 1;
11144       break;
11145     case DW_ACCESS_protected:
11146       fnp->is_protected = 1;
11147       break;
11148     }
11149
11150   /* Check for artificial methods.  */
11151   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11152   if (attr && DW_UNSND (attr) != 0)
11153     fnp->is_artificial = 1;
11154
11155   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11156
11157   /* Get index in virtual function table if it is a virtual member
11158      function.  For older versions of GCC, this is an offset in the
11159      appropriate virtual table, as specified by DW_AT_containing_type.
11160      For everyone else, it is an expression to be evaluated relative
11161      to the object address.  */
11162
11163   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11164   if (attr)
11165     {
11166       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11167         {
11168           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11169             {
11170               /* Old-style GCC.  */
11171               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11172             }
11173           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11174                    || (DW_BLOCK (attr)->size > 1
11175                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11176                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11177             {
11178               struct dwarf_block blk;
11179               int offset;
11180
11181               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11182                         ? 1 : 2);
11183               blk.size = DW_BLOCK (attr)->size - offset;
11184               blk.data = DW_BLOCK (attr)->data + offset;
11185               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11186               if ((fnp->voffset % cu->header.addr_size) != 0)
11187                 dwarf2_complex_location_expr_complaint ();
11188               else
11189                 fnp->voffset /= cu->header.addr_size;
11190               fnp->voffset += 2;
11191             }
11192           else
11193             dwarf2_complex_location_expr_complaint ();
11194
11195           if (!fnp->fcontext)
11196             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11197         }
11198       else if (attr_form_is_section_offset (attr))
11199         {
11200           dwarf2_complex_location_expr_complaint ();
11201         }
11202       else
11203         {
11204           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11205                                                  fieldname);
11206         }
11207     }
11208   else
11209     {
11210       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11211       if (attr && DW_UNSND (attr))
11212         {
11213           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11214           complaint (&symfile_complaints,
11215                      _("Member function \"%s\" (offset %d) is virtual "
11216                        "but the vtable offset is not specified"),
11217                      fieldname, die->offset.sect_off);
11218           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11219           TYPE_CPLUS_DYNAMIC (type) = 1;
11220         }
11221     }
11222 }
11223
11224 /* Create the vector of member function fields, and attach it to the type.  */
11225
11226 static void
11227 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11228                                  struct dwarf2_cu *cu)
11229 {
11230   struct fnfieldlist *flp;
11231   int i;
11232
11233   if (cu->language == language_ada)
11234     error (_("unexpected member functions in Ada type"));
11235
11236   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11237   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11238     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11239
11240   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11241     {
11242       struct nextfnfield *nfp = flp->head;
11243       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11244       int k;
11245
11246       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11247       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11248       fn_flp->fn_fields = (struct fn_field *)
11249         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11250       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11251         fn_flp->fn_fields[k] = nfp->fnfield;
11252     }
11253
11254   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11255 }
11256
11257 /* Returns non-zero if NAME is the name of a vtable member in CU's
11258    language, zero otherwise.  */
11259 static int
11260 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11261 {
11262   static const char vptr[] = "_vptr";
11263   static const char vtable[] = "vtable";
11264
11265   /* Look for the C++ and Java forms of the vtable.  */
11266   if ((cu->language == language_java
11267        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11268        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11269        && is_cplus_marker (name[sizeof (vptr) - 1])))
11270     return 1;
11271
11272   return 0;
11273 }
11274
11275 /* GCC outputs unnamed structures that are really pointers to member
11276    functions, with the ABI-specified layout.  If TYPE describes
11277    such a structure, smash it into a member function type.
11278
11279    GCC shouldn't do this; it should just output pointer to member DIEs.
11280    This is GCC PR debug/28767.  */
11281
11282 static void
11283 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11284 {
11285   struct type *pfn_type, *domain_type, *new_type;
11286
11287   /* Check for a structure with no name and two children.  */
11288   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11289     return;
11290
11291   /* Check for __pfn and __delta members.  */
11292   if (TYPE_FIELD_NAME (type, 0) == NULL
11293       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11294       || TYPE_FIELD_NAME (type, 1) == NULL
11295       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11296     return;
11297
11298   /* Find the type of the method.  */
11299   pfn_type = TYPE_FIELD_TYPE (type, 0);
11300   if (pfn_type == NULL
11301       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11302       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11303     return;
11304
11305   /* Look for the "this" argument.  */
11306   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11307   if (TYPE_NFIELDS (pfn_type) == 0
11308       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11309       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11310     return;
11311
11312   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11313   new_type = alloc_type (objfile);
11314   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11315                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11316                         TYPE_VARARGS (pfn_type));
11317   smash_to_methodptr_type (type, new_type);
11318 }
11319
11320 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11321    (icc).  */
11322
11323 static int
11324 producer_is_icc (struct dwarf2_cu *cu)
11325 {
11326   if (!cu->checked_producer)
11327     check_producer (cu);
11328
11329   return cu->producer_is_icc;
11330 }
11331
11332 /* Called when we find the DIE that starts a structure or union scope
11333    (definition) to create a type for the structure or union.  Fill in
11334    the type's name and general properties; the members will not be
11335    processed until process_structure_scope.
11336
11337    NOTE: we need to call these functions regardless of whether or not the
11338    DIE has a DW_AT_name attribute, since it might be an anonymous
11339    structure or union.  This gets the type entered into our set of
11340    user defined types.
11341
11342    However, if the structure is incomplete (an opaque struct/union)
11343    then suppress creating a symbol table entry for it since gdb only
11344    wants to find the one with the complete definition.  Note that if
11345    it is complete, we just call new_symbol, which does it's own
11346    checking about whether the struct/union is anonymous or not (and
11347    suppresses creating a symbol table entry itself).  */
11348
11349 static struct type *
11350 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11351 {
11352   struct objfile *objfile = cu->objfile;
11353   struct type *type;
11354   struct attribute *attr;
11355   const char *name;
11356
11357   /* If the definition of this type lives in .debug_types, read that type.
11358      Don't follow DW_AT_specification though, that will take us back up
11359      the chain and we want to go down.  */
11360   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11361   if (attr)
11362     {
11363       struct dwarf2_cu *type_cu = cu;
11364       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11365
11366       /* We could just recurse on read_structure_type, but we need to call
11367          get_die_type to ensure only one type for this DIE is created.
11368          This is important, for example, because for c++ classes we need
11369          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11370       type = read_type_die (type_die, type_cu);
11371
11372       /* TYPE_CU may not be the same as CU.
11373          Ensure TYPE is recorded with CU in die_type_hash.  */
11374       return set_die_type (die, type, cu);
11375     }
11376
11377   type = alloc_type (objfile);
11378   INIT_CPLUS_SPECIFIC (type);
11379
11380   name = dwarf2_name (die, cu);
11381   if (name != NULL)
11382     {
11383       if (cu->language == language_cplus
11384           || cu->language == language_java)
11385         {
11386           const char *full_name = dwarf2_full_name (name, die, cu);
11387
11388           /* dwarf2_full_name might have already finished building the DIE's
11389              type.  If so, there is no need to continue.  */
11390           if (get_die_type (die, cu) != NULL)
11391             return get_die_type (die, cu);
11392
11393           TYPE_TAG_NAME (type) = full_name;
11394           if (die->tag == DW_TAG_structure_type
11395               || die->tag == DW_TAG_class_type)
11396             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11397         }
11398       else
11399         {
11400           /* The name is already allocated along with this objfile, so
11401              we don't need to duplicate it for the type.  */
11402           TYPE_TAG_NAME (type) = name;
11403           if (die->tag == DW_TAG_class_type)
11404             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11405         }
11406     }
11407
11408   if (die->tag == DW_TAG_structure_type)
11409     {
11410       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11411     }
11412   else if (die->tag == DW_TAG_union_type)
11413     {
11414       TYPE_CODE (type) = TYPE_CODE_UNION;
11415     }
11416   else
11417     {
11418       TYPE_CODE (type) = TYPE_CODE_CLASS;
11419     }
11420
11421   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11422     TYPE_DECLARED_CLASS (type) = 1;
11423
11424   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11425   if (attr)
11426     {
11427       TYPE_LENGTH (type) = DW_UNSND (attr);
11428     }
11429   else
11430     {
11431       TYPE_LENGTH (type) = 0;
11432     }
11433
11434   if (producer_is_icc (cu))
11435     {
11436       /* ICC does not output the required DW_AT_declaration
11437          on incomplete types, but gives them a size of zero.  */
11438     }
11439   else
11440     TYPE_STUB_SUPPORTED (type) = 1;
11441
11442   if (die_is_declaration (die, cu))
11443     TYPE_STUB (type) = 1;
11444   else if (attr == NULL && die->child == NULL
11445            && producer_is_realview (cu->producer))
11446     /* RealView does not output the required DW_AT_declaration
11447        on incomplete types.  */
11448     TYPE_STUB (type) = 1;
11449
11450   /* We need to add the type field to the die immediately so we don't
11451      infinitely recurse when dealing with pointers to the structure
11452      type within the structure itself.  */
11453   set_die_type (die, type, cu);
11454
11455   /* set_die_type should be already done.  */
11456   set_descriptive_type (type, die, cu);
11457
11458   return type;
11459 }
11460
11461 /* Finish creating a structure or union type, including filling in
11462    its members and creating a symbol for it.  */
11463
11464 static void
11465 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11466 {
11467   struct objfile *objfile = cu->objfile;
11468   struct die_info *child_die = die->child;
11469   struct type *type;
11470
11471   type = get_die_type (die, cu);
11472   if (type == NULL)
11473     type = read_structure_type (die, cu);
11474
11475   if (die->child != NULL && ! die_is_declaration (die, cu))
11476     {
11477       struct field_info fi;
11478       struct die_info *child_die;
11479       VEC (symbolp) *template_args = NULL;
11480       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11481
11482       memset (&fi, 0, sizeof (struct field_info));
11483
11484       child_die = die->child;
11485
11486       while (child_die && child_die->tag)
11487         {
11488           if (child_die->tag == DW_TAG_member
11489               || child_die->tag == DW_TAG_variable)
11490             {
11491               /* NOTE: carlton/2002-11-05: A C++ static data member
11492                  should be a DW_TAG_member that is a declaration, but
11493                  all versions of G++ as of this writing (so through at
11494                  least 3.2.1) incorrectly generate DW_TAG_variable
11495                  tags for them instead.  */
11496               dwarf2_add_field (&fi, child_die, cu);
11497             }
11498           else if (child_die->tag == DW_TAG_subprogram)
11499             {
11500               /* C++ member function.  */
11501               dwarf2_add_member_fn (&fi, child_die, type, cu);
11502             }
11503           else if (child_die->tag == DW_TAG_inheritance)
11504             {
11505               /* C++ base class field.  */
11506               dwarf2_add_field (&fi, child_die, cu);
11507             }
11508           else if (child_die->tag == DW_TAG_typedef)
11509             dwarf2_add_typedef (&fi, child_die, cu);
11510           else if (child_die->tag == DW_TAG_template_type_param
11511                    || child_die->tag == DW_TAG_template_value_param)
11512             {
11513               struct symbol *arg = new_symbol (child_die, NULL, cu);
11514
11515               if (arg != NULL)
11516                 VEC_safe_push (symbolp, template_args, arg);
11517             }
11518
11519           child_die = sibling_die (child_die);
11520         }
11521
11522       /* Attach template arguments to type.  */
11523       if (! VEC_empty (symbolp, template_args))
11524         {
11525           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11526           TYPE_N_TEMPLATE_ARGUMENTS (type)
11527             = VEC_length (symbolp, template_args);
11528           TYPE_TEMPLATE_ARGUMENTS (type)
11529             = obstack_alloc (&objfile->objfile_obstack,
11530                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11531                               * sizeof (struct symbol *)));
11532           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11533                   VEC_address (symbolp, template_args),
11534                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11535                    * sizeof (struct symbol *)));
11536           VEC_free (symbolp, template_args);
11537         }
11538
11539       /* Attach fields and member functions to the type.  */
11540       if (fi.nfields)
11541         dwarf2_attach_fields_to_type (&fi, type, cu);
11542       if (fi.nfnfields)
11543         {
11544           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11545
11546           /* Get the type which refers to the base class (possibly this
11547              class itself) which contains the vtable pointer for the current
11548              class from the DW_AT_containing_type attribute.  This use of
11549              DW_AT_containing_type is a GNU extension.  */
11550
11551           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11552             {
11553               struct type *t = die_containing_type (die, cu);
11554
11555               TYPE_VPTR_BASETYPE (type) = t;
11556               if (type == t)
11557                 {
11558                   int i;
11559
11560                   /* Our own class provides vtbl ptr.  */
11561                   for (i = TYPE_NFIELDS (t) - 1;
11562                        i >= TYPE_N_BASECLASSES (t);
11563                        --i)
11564                     {
11565                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11566
11567                       if (is_vtable_name (fieldname, cu))
11568                         {
11569                           TYPE_VPTR_FIELDNO (type) = i;
11570                           break;
11571                         }
11572                     }
11573
11574                   /* Complain if virtual function table field not found.  */
11575                   if (i < TYPE_N_BASECLASSES (t))
11576                     complaint (&symfile_complaints,
11577                                _("virtual function table pointer "
11578                                  "not found when defining class '%s'"),
11579                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11580                                "");
11581                 }
11582               else
11583                 {
11584                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11585                 }
11586             }
11587           else if (cu->producer
11588                    && strncmp (cu->producer,
11589                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11590             {
11591               /* The IBM XLC compiler does not provide direct indication
11592                  of the containing type, but the vtable pointer is
11593                  always named __vfp.  */
11594
11595               int i;
11596
11597               for (i = TYPE_NFIELDS (type) - 1;
11598                    i >= TYPE_N_BASECLASSES (type);
11599                    --i)
11600                 {
11601                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11602                     {
11603                       TYPE_VPTR_FIELDNO (type) = i;
11604                       TYPE_VPTR_BASETYPE (type) = type;
11605                       break;
11606                     }
11607                 }
11608             }
11609         }
11610
11611       /* Copy fi.typedef_field_list linked list elements content into the
11612          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11613       if (fi.typedef_field_list)
11614         {
11615           int i = fi.typedef_field_list_count;
11616
11617           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11618           TYPE_TYPEDEF_FIELD_ARRAY (type)
11619             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11620           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11621
11622           /* Reverse the list order to keep the debug info elements order.  */
11623           while (--i >= 0)
11624             {
11625               struct typedef_field *dest, *src;
11626
11627               dest = &TYPE_TYPEDEF_FIELD (type, i);
11628               src = &fi.typedef_field_list->field;
11629               fi.typedef_field_list = fi.typedef_field_list->next;
11630               *dest = *src;
11631             }
11632         }
11633
11634       do_cleanups (back_to);
11635
11636       if (HAVE_CPLUS_STRUCT (type))
11637         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11638     }
11639
11640   quirk_gcc_member_function_pointer (type, objfile);
11641
11642   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11643      snapshots) has been known to create a die giving a declaration
11644      for a class that has, as a child, a die giving a definition for a
11645      nested class.  So we have to process our children even if the
11646      current die is a declaration.  Normally, of course, a declaration
11647      won't have any children at all.  */
11648
11649   while (child_die != NULL && child_die->tag)
11650     {
11651       if (child_die->tag == DW_TAG_member
11652           || child_die->tag == DW_TAG_variable
11653           || child_die->tag == DW_TAG_inheritance
11654           || child_die->tag == DW_TAG_template_value_param
11655           || child_die->tag == DW_TAG_template_type_param)
11656         {
11657           /* Do nothing.  */
11658         }
11659       else
11660         process_die (child_die, cu);
11661
11662       child_die = sibling_die (child_die);
11663     }
11664
11665   /* Do not consider external references.  According to the DWARF standard,
11666      these DIEs are identified by the fact that they have no byte_size
11667      attribute, and a declaration attribute.  */
11668   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11669       || !die_is_declaration (die, cu))
11670     new_symbol (die, type, cu);
11671 }
11672
11673 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11674    complete the type's fields yet, or create any symbols.  */
11675
11676 static struct type *
11677 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11678 {
11679   struct objfile *objfile = cu->objfile;
11680   struct type *type;
11681   struct attribute *attr;
11682   const char *name;
11683
11684   /* If the definition of this type lives in .debug_types, read that type.
11685      Don't follow DW_AT_specification though, that will take us back up
11686      the chain and we want to go down.  */
11687   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11688   if (attr)
11689     {
11690       struct dwarf2_cu *type_cu = cu;
11691       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11692
11693       type = read_type_die (type_die, type_cu);
11694
11695       /* TYPE_CU may not be the same as CU.
11696          Ensure TYPE is recorded with CU in die_type_hash.  */
11697       return set_die_type (die, type, cu);
11698     }
11699
11700   type = alloc_type (objfile);
11701
11702   TYPE_CODE (type) = TYPE_CODE_ENUM;
11703   name = dwarf2_full_name (NULL, die, cu);
11704   if (name != NULL)
11705     TYPE_TAG_NAME (type) = name;
11706
11707   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11708   if (attr)
11709     {
11710       TYPE_LENGTH (type) = DW_UNSND (attr);
11711     }
11712   else
11713     {
11714       TYPE_LENGTH (type) = 0;
11715     }
11716
11717   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11718      declared as private in the package spec, and then defined only
11719      inside the package body.  Such types are known as Taft Amendment
11720      Types.  When another package uses such a type, an incomplete DIE
11721      may be generated by the compiler.  */
11722   if (die_is_declaration (die, cu))
11723     TYPE_STUB (type) = 1;
11724
11725   return set_die_type (die, type, cu);
11726 }
11727
11728 /* Given a pointer to a die which begins an enumeration, process all
11729    the dies that define the members of the enumeration, and create the
11730    symbol for the enumeration type.
11731
11732    NOTE: We reverse the order of the element list.  */
11733
11734 static void
11735 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11736 {
11737   struct type *this_type;
11738
11739   this_type = get_die_type (die, cu);
11740   if (this_type == NULL)
11741     this_type = read_enumeration_type (die, cu);
11742
11743   if (die->child != NULL)
11744     {
11745       struct die_info *child_die;
11746       struct symbol *sym;
11747       struct field *fields = NULL;
11748       int num_fields = 0;
11749       int unsigned_enum = 1;
11750       const char *name;
11751       int flag_enum = 1;
11752       ULONGEST mask = 0;
11753
11754       child_die = die->child;
11755       while (child_die && child_die->tag)
11756         {
11757           if (child_die->tag != DW_TAG_enumerator)
11758             {
11759               process_die (child_die, cu);
11760             }
11761           else
11762             {
11763               name = dwarf2_name (child_die, cu);
11764               if (name)
11765                 {
11766                   sym = new_symbol (child_die, this_type, cu);
11767                   if (SYMBOL_VALUE (sym) < 0)
11768                     {
11769                       unsigned_enum = 0;
11770                       flag_enum = 0;
11771                     }
11772                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11773                     flag_enum = 0;
11774                   else
11775                     mask |= SYMBOL_VALUE (sym);
11776
11777                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11778                     {
11779                       fields = (struct field *)
11780                         xrealloc (fields,
11781                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11782                                   * sizeof (struct field));
11783                     }
11784
11785                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11786                   FIELD_TYPE (fields[num_fields]) = NULL;
11787                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11788                   FIELD_BITSIZE (fields[num_fields]) = 0;
11789
11790                   num_fields++;
11791                 }
11792             }
11793
11794           child_die = sibling_die (child_die);
11795         }
11796
11797       if (num_fields)
11798         {
11799           TYPE_NFIELDS (this_type) = num_fields;
11800           TYPE_FIELDS (this_type) = (struct field *)
11801             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11802           memcpy (TYPE_FIELDS (this_type), fields,
11803                   sizeof (struct field) * num_fields);
11804           xfree (fields);
11805         }
11806       if (unsigned_enum)
11807         TYPE_UNSIGNED (this_type) = 1;
11808       if (flag_enum)
11809         TYPE_FLAG_ENUM (this_type) = 1;
11810     }
11811
11812   /* If we are reading an enum from a .debug_types unit, and the enum
11813      is a declaration, and the enum is not the signatured type in the
11814      unit, then we do not want to add a symbol for it.  Adding a
11815      symbol would in some cases obscure the true definition of the
11816      enum, giving users an incomplete type when the definition is
11817      actually available.  Note that we do not want to do this for all
11818      enums which are just declarations, because C++0x allows forward
11819      enum declarations.  */
11820   if (cu->per_cu->is_debug_types
11821       && die_is_declaration (die, cu))
11822     {
11823       struct signatured_type *sig_type;
11824
11825       sig_type = (struct signatured_type *) cu->per_cu;
11826       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11827       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11828         return;
11829     }
11830
11831   new_symbol (die, this_type, cu);
11832 }
11833
11834 /* Extract all information from a DW_TAG_array_type DIE and put it in
11835    the DIE's type field.  For now, this only handles one dimensional
11836    arrays.  */
11837
11838 static struct type *
11839 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11840 {
11841   struct objfile *objfile = cu->objfile;
11842   struct die_info *child_die;
11843   struct type *type;
11844   struct type *element_type, *range_type, *index_type;
11845   struct type **range_types = NULL;
11846   struct attribute *attr;
11847   int ndim = 0;
11848   struct cleanup *back_to;
11849   const char *name;
11850
11851   element_type = die_type (die, cu);
11852
11853   /* The die_type call above may have already set the type for this DIE.  */
11854   type = get_die_type (die, cu);
11855   if (type)
11856     return type;
11857
11858   /* Irix 6.2 native cc creates array types without children for
11859      arrays with unspecified length.  */
11860   if (die->child == NULL)
11861     {
11862       index_type = objfile_type (objfile)->builtin_int;
11863       range_type = create_range_type (NULL, index_type, 0, -1);
11864       type = create_array_type (NULL, element_type, range_type);
11865       return set_die_type (die, type, cu);
11866     }
11867
11868   back_to = make_cleanup (null_cleanup, NULL);
11869   child_die = die->child;
11870   while (child_die && child_die->tag)
11871     {
11872       if (child_die->tag == DW_TAG_subrange_type)
11873         {
11874           struct type *child_type = read_type_die (child_die, cu);
11875
11876           if (child_type != NULL)
11877             {
11878               /* The range type was succesfully read.  Save it for the
11879                  array type creation.  */
11880               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11881                 {
11882                   range_types = (struct type **)
11883                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11884                               * sizeof (struct type *));
11885                   if (ndim == 0)
11886                     make_cleanup (free_current_contents, &range_types);
11887                 }
11888               range_types[ndim++] = child_type;
11889             }
11890         }
11891       child_die = sibling_die (child_die);
11892     }
11893
11894   /* Dwarf2 dimensions are output from left to right, create the
11895      necessary array types in backwards order.  */
11896
11897   type = element_type;
11898
11899   if (read_array_order (die, cu) == DW_ORD_col_major)
11900     {
11901       int i = 0;
11902
11903       while (i < ndim)
11904         type = create_array_type (NULL, type, range_types[i++]);
11905     }
11906   else
11907     {
11908       while (ndim-- > 0)
11909         type = create_array_type (NULL, type, range_types[ndim]);
11910     }
11911
11912   /* Understand Dwarf2 support for vector types (like they occur on
11913      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11914      array type.  This is not part of the Dwarf2/3 standard yet, but a
11915      custom vendor extension.  The main difference between a regular
11916      array and the vector variant is that vectors are passed by value
11917      to functions.  */
11918   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11919   if (attr)
11920     make_vector_type (type);
11921
11922   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11923      implementation may choose to implement triple vectors using this
11924      attribute.  */
11925   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11926   if (attr)
11927     {
11928       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11929         TYPE_LENGTH (type) = DW_UNSND (attr);
11930       else
11931         complaint (&symfile_complaints,
11932                    _("DW_AT_byte_size for array type smaller "
11933                      "than the total size of elements"));
11934     }
11935
11936   name = dwarf2_name (die, cu);
11937   if (name)
11938     TYPE_NAME (type) = name;
11939
11940   /* Install the type in the die.  */
11941   set_die_type (die, type, cu);
11942
11943   /* set_die_type should be already done.  */
11944   set_descriptive_type (type, die, cu);
11945
11946   do_cleanups (back_to);
11947
11948   return type;
11949 }
11950
11951 static enum dwarf_array_dim_ordering
11952 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11953 {
11954   struct attribute *attr;
11955
11956   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11957
11958   if (attr) return DW_SND (attr);
11959
11960   /* GNU F77 is a special case, as at 08/2004 array type info is the
11961      opposite order to the dwarf2 specification, but data is still
11962      laid out as per normal fortran.
11963
11964      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11965      version checking.  */
11966
11967   if (cu->language == language_fortran
11968       && cu->producer && strstr (cu->producer, "GNU F77"))
11969     {
11970       return DW_ORD_row_major;
11971     }
11972
11973   switch (cu->language_defn->la_array_ordering)
11974     {
11975     case array_column_major:
11976       return DW_ORD_col_major;
11977     case array_row_major:
11978     default:
11979       return DW_ORD_row_major;
11980     };
11981 }
11982
11983 /* Extract all information from a DW_TAG_set_type DIE and put it in
11984    the DIE's type field.  */
11985
11986 static struct type *
11987 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11988 {
11989   struct type *domain_type, *set_type;
11990   struct attribute *attr;
11991
11992   domain_type = die_type (die, cu);
11993
11994   /* The die_type call above may have already set the type for this DIE.  */
11995   set_type = get_die_type (die, cu);
11996   if (set_type)
11997     return set_type;
11998
11999   set_type = create_set_type (NULL, domain_type);
12000
12001   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12002   if (attr)
12003     TYPE_LENGTH (set_type) = DW_UNSND (attr);
12004
12005   return set_die_type (die, set_type, cu);
12006 }
12007
12008 /* A helper for read_common_block that creates a locexpr baton.
12009    SYM is the symbol which we are marking as computed.
12010    COMMON_DIE is the DIE for the common block.
12011    COMMON_LOC is the location expression attribute for the common
12012    block itself.
12013    MEMBER_LOC is the location expression attribute for the particular
12014    member of the common block that we are processing.
12015    CU is the CU from which the above come.  */
12016
12017 static void
12018 mark_common_block_symbol_computed (struct symbol *sym,
12019                                    struct die_info *common_die,
12020                                    struct attribute *common_loc,
12021                                    struct attribute *member_loc,
12022                                    struct dwarf2_cu *cu)
12023 {
12024   struct objfile *objfile = dwarf2_per_objfile->objfile;
12025   struct dwarf2_locexpr_baton *baton;
12026   gdb_byte *ptr;
12027   unsigned int cu_off;
12028   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
12029   LONGEST offset = 0;
12030
12031   gdb_assert (common_loc && member_loc);
12032   gdb_assert (attr_form_is_block (common_loc));
12033   gdb_assert (attr_form_is_block (member_loc)
12034               || attr_form_is_constant (member_loc));
12035
12036   baton = obstack_alloc (&objfile->objfile_obstack,
12037                          sizeof (struct dwarf2_locexpr_baton));
12038   baton->per_cu = cu->per_cu;
12039   gdb_assert (baton->per_cu);
12040
12041   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
12042
12043   if (attr_form_is_constant (member_loc))
12044     {
12045       offset = dwarf2_get_attr_constant_value (member_loc, 0);
12046       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
12047     }
12048   else
12049     baton->size += DW_BLOCK (member_loc)->size;
12050
12051   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
12052   baton->data = ptr;
12053
12054   *ptr++ = DW_OP_call4;
12055   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
12056   store_unsigned_integer (ptr, 4, byte_order, cu_off);
12057   ptr += 4;
12058
12059   if (attr_form_is_constant (member_loc))
12060     {
12061       *ptr++ = DW_OP_addr;
12062       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
12063       ptr += cu->header.addr_size;
12064     }
12065   else
12066     {
12067       /* We have to copy the data here, because DW_OP_call4 will only
12068          use a DW_AT_location attribute.  */
12069       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
12070       ptr += DW_BLOCK (member_loc)->size;
12071     }
12072
12073   *ptr++ = DW_OP_plus;
12074   gdb_assert (ptr - baton->data == baton->size);
12075
12076   SYMBOL_LOCATION_BATON (sym) = baton;
12077   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
12078 }
12079
12080 /* Create appropriate locally-scoped variables for all the
12081    DW_TAG_common_block entries.  Also create a struct common_block
12082    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
12083    is used to sepate the common blocks name namespace from regular
12084    variable names.  */
12085
12086 static void
12087 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
12088 {
12089   struct attribute *attr;
12090
12091   attr = dwarf2_attr (die, DW_AT_location, cu);
12092   if (attr)
12093     {
12094       /* Support the .debug_loc offsets.  */
12095       if (attr_form_is_block (attr))
12096         {
12097           /* Ok.  */
12098         }
12099       else if (attr_form_is_section_offset (attr))
12100         {
12101           dwarf2_complex_location_expr_complaint ();
12102           attr = NULL;
12103         }
12104       else
12105         {
12106           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
12107                                                  "common block member");
12108           attr = NULL;
12109         }
12110     }
12111
12112   if (die->child != NULL)
12113     {
12114       struct objfile *objfile = cu->objfile;
12115       struct die_info *child_die;
12116       size_t n_entries = 0, size;
12117       struct common_block *common_block;
12118       struct symbol *sym;
12119
12120       for (child_die = die->child;
12121            child_die && child_die->tag;
12122            child_die = sibling_die (child_die))
12123         ++n_entries;
12124
12125       size = (sizeof (struct common_block)
12126               + (n_entries - 1) * sizeof (struct symbol *));
12127       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12128       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12129       common_block->n_entries = 0;
12130
12131       for (child_die = die->child;
12132            child_die && child_die->tag;
12133            child_die = sibling_die (child_die))
12134         {
12135           /* Create the symbol in the DW_TAG_common_block block in the current
12136              symbol scope.  */
12137           sym = new_symbol (child_die, NULL, cu);
12138           if (sym != NULL)
12139             {
12140               struct attribute *member_loc;
12141
12142               common_block->contents[common_block->n_entries++] = sym;
12143
12144               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12145                                         cu);
12146               if (member_loc)
12147                 {
12148                   /* GDB has handled this for a long time, but it is
12149                      not specified by DWARF.  It seems to have been
12150                      emitted by gfortran at least as recently as:
12151                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12152                   complaint (&symfile_complaints,
12153                              _("Variable in common block has "
12154                                "DW_AT_data_member_location "
12155                                "- DIE at 0x%x [in module %s]"),
12156                              child_die->offset.sect_off, cu->objfile->name);
12157
12158                   if (attr_form_is_section_offset (member_loc))
12159                     dwarf2_complex_location_expr_complaint ();
12160                   else if (attr_form_is_constant (member_loc)
12161                            || attr_form_is_block (member_loc))
12162                     {
12163                       if (attr)
12164                         mark_common_block_symbol_computed (sym, die, attr,
12165                                                            member_loc, cu);
12166                     }
12167                   else
12168                     dwarf2_complex_location_expr_complaint ();
12169                 }
12170             }
12171         }
12172
12173       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12174       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12175     }
12176 }
12177
12178 /* Create a type for a C++ namespace.  */
12179
12180 static struct type *
12181 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12182 {
12183   struct objfile *objfile = cu->objfile;
12184   const char *previous_prefix, *name;
12185   int is_anonymous;
12186   struct type *type;
12187
12188   /* For extensions, reuse the type of the original namespace.  */
12189   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12190     {
12191       struct die_info *ext_die;
12192       struct dwarf2_cu *ext_cu = cu;
12193
12194       ext_die = dwarf2_extension (die, &ext_cu);
12195       type = read_type_die (ext_die, ext_cu);
12196
12197       /* EXT_CU may not be the same as CU.
12198          Ensure TYPE is recorded with CU in die_type_hash.  */
12199       return set_die_type (die, type, cu);
12200     }
12201
12202   name = namespace_name (die, &is_anonymous, cu);
12203
12204   /* Now build the name of the current namespace.  */
12205
12206   previous_prefix = determine_prefix (die, cu);
12207   if (previous_prefix[0] != '\0')
12208     name = typename_concat (&objfile->objfile_obstack,
12209                             previous_prefix, name, 0, cu);
12210
12211   /* Create the type.  */
12212   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12213                     objfile);
12214   TYPE_NAME (type) = name;
12215   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12216
12217   return set_die_type (die, type, cu);
12218 }
12219
12220 /* Read a C++ namespace.  */
12221
12222 static void
12223 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12224 {
12225   struct objfile *objfile = cu->objfile;
12226   int is_anonymous;
12227
12228   /* Add a symbol associated to this if we haven't seen the namespace
12229      before.  Also, add a using directive if it's an anonymous
12230      namespace.  */
12231
12232   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12233     {
12234       struct type *type;
12235
12236       type = read_type_die (die, cu);
12237       new_symbol (die, type, cu);
12238
12239       namespace_name (die, &is_anonymous, cu);
12240       if (is_anonymous)
12241         {
12242           const char *previous_prefix = determine_prefix (die, cu);
12243
12244           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12245                                   NULL, NULL, 0, &objfile->objfile_obstack);
12246         }
12247     }
12248
12249   if (die->child != NULL)
12250     {
12251       struct die_info *child_die = die->child;
12252
12253       while (child_die && child_die->tag)
12254         {
12255           process_die (child_die, cu);
12256           child_die = sibling_die (child_die);
12257         }
12258     }
12259 }
12260
12261 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12262    imported module.  Still we need that type as local Fortran "use ... only"
12263    declaration imports depend on the created type in determine_prefix.  */
12264
12265 static struct type *
12266 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12267 {
12268   struct objfile *objfile = cu->objfile;
12269   const char *module_name;
12270   struct type *type;
12271
12272   module_name = dwarf2_name (die, cu);
12273   if (!module_name)
12274     complaint (&symfile_complaints,
12275                _("DW_TAG_module has no name, offset 0x%x"),
12276                die->offset.sect_off);
12277   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12278
12279   /* determine_prefix uses TYPE_TAG_NAME.  */
12280   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12281
12282   return set_die_type (die, type, cu);
12283 }
12284
12285 /* Read a Fortran module.  */
12286
12287 static void
12288 read_module (struct die_info *die, struct dwarf2_cu *cu)
12289 {
12290   struct die_info *child_die = die->child;
12291
12292   while (child_die && child_die->tag)
12293     {
12294       process_die (child_die, cu);
12295       child_die = sibling_die (child_die);
12296     }
12297 }
12298
12299 /* Return the name of the namespace represented by DIE.  Set
12300    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12301    namespace.  */
12302
12303 static const char *
12304 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12305 {
12306   struct die_info *current_die;
12307   const char *name = NULL;
12308
12309   /* Loop through the extensions until we find a name.  */
12310
12311   for (current_die = die;
12312        current_die != NULL;
12313        current_die = dwarf2_extension (die, &cu))
12314     {
12315       name = dwarf2_name (current_die, cu);
12316       if (name != NULL)
12317         break;
12318     }
12319
12320   /* Is it an anonymous namespace?  */
12321
12322   *is_anonymous = (name == NULL);
12323   if (*is_anonymous)
12324     name = CP_ANONYMOUS_NAMESPACE_STR;
12325
12326   return name;
12327 }
12328
12329 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12330    the user defined type vector.  */
12331
12332 static struct type *
12333 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12334 {
12335   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12336   struct comp_unit_head *cu_header = &cu->header;
12337   struct type *type;
12338   struct attribute *attr_byte_size;
12339   struct attribute *attr_address_class;
12340   int byte_size, addr_class;
12341   struct type *target_type;
12342
12343   target_type = die_type (die, cu);
12344
12345   /* The die_type call above may have already set the type for this DIE.  */
12346   type = get_die_type (die, cu);
12347   if (type)
12348     return type;
12349
12350   type = lookup_pointer_type (target_type);
12351
12352   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12353   if (attr_byte_size)
12354     byte_size = DW_UNSND (attr_byte_size);
12355   else
12356     byte_size = cu_header->addr_size;
12357
12358   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12359   if (attr_address_class)
12360     addr_class = DW_UNSND (attr_address_class);
12361   else
12362     addr_class = DW_ADDR_none;
12363
12364   /* If the pointer size or address class is different than the
12365      default, create a type variant marked as such and set the
12366      length accordingly.  */
12367   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12368     {
12369       if (gdbarch_address_class_type_flags_p (gdbarch))
12370         {
12371           int type_flags;
12372
12373           type_flags = gdbarch_address_class_type_flags
12374                          (gdbarch, byte_size, addr_class);
12375           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12376                       == 0);
12377           type = make_type_with_address_space (type, type_flags);
12378         }
12379       else if (TYPE_LENGTH (type) != byte_size)
12380         {
12381           complaint (&symfile_complaints,
12382                      _("invalid pointer size %d"), byte_size);
12383         }
12384       else
12385         {
12386           /* Should we also complain about unhandled address classes?  */
12387         }
12388     }
12389
12390   TYPE_LENGTH (type) = byte_size;
12391   return set_die_type (die, type, cu);
12392 }
12393
12394 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12395    the user defined type vector.  */
12396
12397 static struct type *
12398 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12399 {
12400   struct type *type;
12401   struct type *to_type;
12402   struct type *domain;
12403
12404   to_type = die_type (die, cu);
12405   domain = die_containing_type (die, cu);
12406
12407   /* The calls above may have already set the type for this DIE.  */
12408   type = get_die_type (die, cu);
12409   if (type)
12410     return type;
12411
12412   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12413     type = lookup_methodptr_type (to_type);
12414   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12415     {
12416       struct type *new_type = alloc_type (cu->objfile);
12417
12418       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12419                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12420                             TYPE_VARARGS (to_type));
12421       type = lookup_methodptr_type (new_type);
12422     }
12423   else
12424     type = lookup_memberptr_type (to_type, domain);
12425
12426   return set_die_type (die, type, cu);
12427 }
12428
12429 /* Extract all information from a DW_TAG_reference_type DIE and add to
12430    the user defined type vector.  */
12431
12432 static struct type *
12433 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12434 {
12435   struct comp_unit_head *cu_header = &cu->header;
12436   struct type *type, *target_type;
12437   struct attribute *attr;
12438
12439   target_type = die_type (die, cu);
12440
12441   /* The die_type call above may have already set the type for this DIE.  */
12442   type = get_die_type (die, cu);
12443   if (type)
12444     return type;
12445
12446   type = lookup_reference_type (target_type);
12447   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12448   if (attr)
12449     {
12450       TYPE_LENGTH (type) = DW_UNSND (attr);
12451     }
12452   else
12453     {
12454       TYPE_LENGTH (type) = cu_header->addr_size;
12455     }
12456   return set_die_type (die, type, cu);
12457 }
12458
12459 static struct type *
12460 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12461 {
12462   struct type *base_type, *cv_type;
12463
12464   base_type = die_type (die, cu);
12465
12466   /* The die_type call above may have already set the type for this DIE.  */
12467   cv_type = get_die_type (die, cu);
12468   if (cv_type)
12469     return cv_type;
12470
12471   /* In case the const qualifier is applied to an array type, the element type
12472      is so qualified, not the array type (section 6.7.3 of C99).  */
12473   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12474     {
12475       struct type *el_type, *inner_array;
12476
12477       base_type = copy_type (base_type);
12478       inner_array = base_type;
12479
12480       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12481         {
12482           TYPE_TARGET_TYPE (inner_array) =
12483             copy_type (TYPE_TARGET_TYPE (inner_array));
12484           inner_array = TYPE_TARGET_TYPE (inner_array);
12485         }
12486
12487       el_type = TYPE_TARGET_TYPE (inner_array);
12488       TYPE_TARGET_TYPE (inner_array) =
12489         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12490
12491       return set_die_type (die, base_type, cu);
12492     }
12493
12494   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12495   return set_die_type (die, cv_type, cu);
12496 }
12497
12498 static struct type *
12499 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12500 {
12501   struct type *base_type, *cv_type;
12502
12503   base_type = die_type (die, cu);
12504
12505   /* The die_type call above may have already set the type for this DIE.  */
12506   cv_type = get_die_type (die, cu);
12507   if (cv_type)
12508     return cv_type;
12509
12510   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12511   return set_die_type (die, cv_type, cu);
12512 }
12513
12514 /* Handle DW_TAG_restrict_type.  */
12515
12516 static struct type *
12517 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12518 {
12519   struct type *base_type, *cv_type;
12520
12521   base_type = die_type (die, cu);
12522
12523   /* The die_type call above may have already set the type for this DIE.  */
12524   cv_type = get_die_type (die, cu);
12525   if (cv_type)
12526     return cv_type;
12527
12528   cv_type = make_restrict_type (base_type);
12529   return set_die_type (die, cv_type, cu);
12530 }
12531
12532 /* Extract all information from a DW_TAG_string_type DIE and add to
12533    the user defined type vector.  It isn't really a user defined type,
12534    but it behaves like one, with other DIE's using an AT_user_def_type
12535    attribute to reference it.  */
12536
12537 static struct type *
12538 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12539 {
12540   struct objfile *objfile = cu->objfile;
12541   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12542   struct type *type, *range_type, *index_type, *char_type;
12543   struct attribute *attr;
12544   unsigned int length;
12545
12546   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12547   if (attr)
12548     {
12549       length = DW_UNSND (attr);
12550     }
12551   else
12552     {
12553       /* Check for the DW_AT_byte_size attribute.  */
12554       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12555       if (attr)
12556         {
12557           length = DW_UNSND (attr);
12558         }
12559       else
12560         {
12561           length = 1;
12562         }
12563     }
12564
12565   index_type = objfile_type (objfile)->builtin_int;
12566   range_type = create_range_type (NULL, index_type, 1, length);
12567   char_type = language_string_char_type (cu->language_defn, gdbarch);
12568   type = create_string_type (NULL, char_type, range_type);
12569
12570   return set_die_type (die, type, cu);
12571 }
12572
12573 /* Handle DIES due to C code like:
12574
12575    struct foo
12576    {
12577    int (*funcp)(int a, long l);
12578    int b;
12579    };
12580
12581    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12582
12583 static struct type *
12584 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12585 {
12586   struct objfile *objfile = cu->objfile;
12587   struct type *type;            /* Type that this function returns.  */
12588   struct type *ftype;           /* Function that returns above type.  */
12589   struct attribute *attr;
12590
12591   type = die_type (die, cu);
12592
12593   /* The die_type call above may have already set the type for this DIE.  */
12594   ftype = get_die_type (die, cu);
12595   if (ftype)
12596     return ftype;
12597
12598   ftype = lookup_function_type (type);
12599
12600   /* All functions in C++, Pascal and Java have prototypes.  */
12601   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12602   if ((attr && (DW_UNSND (attr) != 0))
12603       || cu->language == language_cplus
12604       || cu->language == language_java
12605       || cu->language == language_pascal)
12606     TYPE_PROTOTYPED (ftype) = 1;
12607   else if (producer_is_realview (cu->producer))
12608     /* RealView does not emit DW_AT_prototyped.  We can not
12609        distinguish prototyped and unprototyped functions; default to
12610        prototyped, since that is more common in modern code (and
12611        RealView warns about unprototyped functions).  */
12612     TYPE_PROTOTYPED (ftype) = 1;
12613
12614   /* Store the calling convention in the type if it's available in
12615      the subroutine die.  Otherwise set the calling convention to
12616      the default value DW_CC_normal.  */
12617   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12618   if (attr)
12619     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12620   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12621     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12622   else
12623     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12624
12625   /* We need to add the subroutine type to the die immediately so
12626      we don't infinitely recurse when dealing with parameters
12627      declared as the same subroutine type.  */
12628   set_die_type (die, ftype, cu);
12629
12630   if (die->child != NULL)
12631     {
12632       struct type *void_type = objfile_type (objfile)->builtin_void;
12633       struct die_info *child_die;
12634       int nparams, iparams;
12635
12636       /* Count the number of parameters.
12637          FIXME: GDB currently ignores vararg functions, but knows about
12638          vararg member functions.  */
12639       nparams = 0;
12640       child_die = die->child;
12641       while (child_die && child_die->tag)
12642         {
12643           if (child_die->tag == DW_TAG_formal_parameter)
12644             nparams++;
12645           else if (child_die->tag == DW_TAG_unspecified_parameters)
12646             TYPE_VARARGS (ftype) = 1;
12647           child_die = sibling_die (child_die);
12648         }
12649
12650       /* Allocate storage for parameters and fill them in.  */
12651       TYPE_NFIELDS (ftype) = nparams;
12652       TYPE_FIELDS (ftype) = (struct field *)
12653         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12654
12655       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12656          even if we error out during the parameters reading below.  */
12657       for (iparams = 0; iparams < nparams; iparams++)
12658         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12659
12660       iparams = 0;
12661       child_die = die->child;
12662       while (child_die && child_die->tag)
12663         {
12664           if (child_die->tag == DW_TAG_formal_parameter)
12665             {
12666               struct type *arg_type;
12667
12668               /* DWARF version 2 has no clean way to discern C++
12669                  static and non-static member functions.  G++ helps
12670                  GDB by marking the first parameter for non-static
12671                  member functions (which is the this pointer) as
12672                  artificial.  We pass this information to
12673                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12674
12675                  DWARF version 3 added DW_AT_object_pointer, which GCC
12676                  4.5 does not yet generate.  */
12677               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12678               if (attr)
12679                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12680               else
12681                 {
12682                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12683
12684                   /* GCC/43521: In java, the formal parameter
12685                      "this" is sometimes not marked with DW_AT_artificial.  */
12686                   if (cu->language == language_java)
12687                     {
12688                       const char *name = dwarf2_name (child_die, cu);
12689
12690                       if (name && !strcmp (name, "this"))
12691                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12692                     }
12693                 }
12694               arg_type = die_type (child_die, cu);
12695
12696               /* RealView does not mark THIS as const, which the testsuite
12697                  expects.  GCC marks THIS as const in method definitions,
12698                  but not in the class specifications (GCC PR 43053).  */
12699               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12700                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12701                 {
12702                   int is_this = 0;
12703                   struct dwarf2_cu *arg_cu = cu;
12704                   const char *name = dwarf2_name (child_die, cu);
12705
12706                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12707                   if (attr)
12708                     {
12709                       /* If the compiler emits this, use it.  */
12710                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12711                         is_this = 1;
12712                     }
12713                   else if (name && strcmp (name, "this") == 0)
12714                     /* Function definitions will have the argument names.  */
12715                     is_this = 1;
12716                   else if (name == NULL && iparams == 0)
12717                     /* Declarations may not have the names, so like
12718                        elsewhere in GDB, assume an artificial first
12719                        argument is "this".  */
12720                     is_this = 1;
12721
12722                   if (is_this)
12723                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12724                                              arg_type, 0);
12725                 }
12726
12727               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12728               iparams++;
12729             }
12730           child_die = sibling_die (child_die);
12731         }
12732     }
12733
12734   return ftype;
12735 }
12736
12737 static struct type *
12738 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12739 {
12740   struct objfile *objfile = cu->objfile;
12741   const char *name = NULL;
12742   struct type *this_type, *target_type;
12743
12744   name = dwarf2_full_name (NULL, die, cu);
12745   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12746                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12747   TYPE_NAME (this_type) = name;
12748   set_die_type (die, this_type, cu);
12749   target_type = die_type (die, cu);
12750   if (target_type != this_type)
12751     TYPE_TARGET_TYPE (this_type) = target_type;
12752   else
12753     {
12754       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12755          spec and cause infinite loops in GDB.  */
12756       complaint (&symfile_complaints,
12757                  _("Self-referential DW_TAG_typedef "
12758                    "- DIE at 0x%x [in module %s]"),
12759                  die->offset.sect_off, objfile->name);
12760       TYPE_TARGET_TYPE (this_type) = NULL;
12761     }
12762   return this_type;
12763 }
12764
12765 /* Find a representation of a given base type and install
12766    it in the TYPE field of the die.  */
12767
12768 static struct type *
12769 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12770 {
12771   struct objfile *objfile = cu->objfile;
12772   struct type *type;
12773   struct attribute *attr;
12774   int encoding = 0, size = 0;
12775   const char *name;
12776   enum type_code code = TYPE_CODE_INT;
12777   int type_flags = 0;
12778   struct type *target_type = NULL;
12779
12780   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12781   if (attr)
12782     {
12783       encoding = DW_UNSND (attr);
12784     }
12785   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12786   if (attr)
12787     {
12788       size = DW_UNSND (attr);
12789     }
12790   name = dwarf2_name (die, cu);
12791   if (!name)
12792     {
12793       complaint (&symfile_complaints,
12794                  _("DW_AT_name missing from DW_TAG_base_type"));
12795     }
12796
12797   switch (encoding)
12798     {
12799       case DW_ATE_address:
12800         /* Turn DW_ATE_address into a void * pointer.  */
12801         code = TYPE_CODE_PTR;
12802         type_flags |= TYPE_FLAG_UNSIGNED;
12803         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12804         break;
12805       case DW_ATE_boolean:
12806         code = TYPE_CODE_BOOL;
12807         type_flags |= TYPE_FLAG_UNSIGNED;
12808         break;
12809       case DW_ATE_complex_float:
12810         code = TYPE_CODE_COMPLEX;
12811         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12812         break;
12813       case DW_ATE_decimal_float:
12814         code = TYPE_CODE_DECFLOAT;
12815         break;
12816       case DW_ATE_float:
12817         code = TYPE_CODE_FLT;
12818         break;
12819       case DW_ATE_signed:
12820         break;
12821       case DW_ATE_unsigned:
12822         type_flags |= TYPE_FLAG_UNSIGNED;
12823         if (cu->language == language_fortran
12824             && name
12825             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12826           code = TYPE_CODE_CHAR;
12827         break;
12828       case DW_ATE_signed_char:
12829         if (cu->language == language_ada || cu->language == language_m2
12830             || cu->language == language_pascal
12831             || cu->language == language_fortran)
12832           code = TYPE_CODE_CHAR;
12833         break;
12834       case DW_ATE_unsigned_char:
12835         if (cu->language == language_ada || cu->language == language_m2
12836             || cu->language == language_pascal
12837             || cu->language == language_fortran)
12838           code = TYPE_CODE_CHAR;
12839         type_flags |= TYPE_FLAG_UNSIGNED;
12840         break;
12841       case DW_ATE_UTF:
12842         /* We just treat this as an integer and then recognize the
12843            type by name elsewhere.  */
12844         break;
12845
12846       default:
12847         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12848                    dwarf_type_encoding_name (encoding));
12849         break;
12850     }
12851
12852   type = init_type (code, size, type_flags, NULL, objfile);
12853   TYPE_NAME (type) = name;
12854   TYPE_TARGET_TYPE (type) = target_type;
12855
12856   if (name && strcmp (name, "char") == 0)
12857     TYPE_NOSIGN (type) = 1;
12858
12859   return set_die_type (die, type, cu);
12860 }
12861
12862 /* Read the given DW_AT_subrange DIE.  */
12863
12864 static struct type *
12865 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12866 {
12867   struct type *base_type, *orig_base_type;
12868   struct type *range_type;
12869   struct attribute *attr;
12870   LONGEST low, high;
12871   int low_default_is_valid;
12872   const char *name;
12873   LONGEST negative_mask;
12874
12875   orig_base_type = die_type (die, cu);
12876   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
12877      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
12878      creating the range type, but we use the result of check_typedef
12879      when examining properties of the type.  */
12880   base_type = check_typedef (orig_base_type);
12881
12882   /* The die_type call above may have already set the type for this DIE.  */
12883   range_type = get_die_type (die, cu);
12884   if (range_type)
12885     return range_type;
12886
12887   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12888      omitting DW_AT_lower_bound.  */
12889   switch (cu->language)
12890     {
12891     case language_c:
12892     case language_cplus:
12893       low = 0;
12894       low_default_is_valid = 1;
12895       break;
12896     case language_fortran:
12897       low = 1;
12898       low_default_is_valid = 1;
12899       break;
12900     case language_d:
12901     case language_java:
12902     case language_objc:
12903       low = 0;
12904       low_default_is_valid = (cu->header.version >= 4);
12905       break;
12906     case language_ada:
12907     case language_m2:
12908     case language_pascal:
12909       low = 1;
12910       low_default_is_valid = (cu->header.version >= 4);
12911       break;
12912     default:
12913       low = 0;
12914       low_default_is_valid = 0;
12915       break;
12916     }
12917
12918   /* FIXME: For variable sized arrays either of these could be
12919      a variable rather than a constant value.  We'll allow it,
12920      but we don't know how to handle it.  */
12921   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12922   if (attr)
12923     low = dwarf2_get_attr_constant_value (attr, low);
12924   else if (!low_default_is_valid)
12925     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12926                                       "- DIE at 0x%x [in module %s]"),
12927                die->offset.sect_off, cu->objfile->name);
12928
12929   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12930   if (attr)
12931     {
12932       if (attr_form_is_block (attr) || is_ref_attr (attr))
12933         {
12934           /* GCC encodes arrays with unspecified or dynamic length
12935              with a DW_FORM_block1 attribute or a reference attribute.
12936              FIXME: GDB does not yet know how to handle dynamic
12937              arrays properly, treat them as arrays with unspecified
12938              length for now.
12939
12940              FIXME: jimb/2003-09-22: GDB does not really know
12941              how to handle arrays of unspecified length
12942              either; we just represent them as zero-length
12943              arrays.  Choose an appropriate upper bound given
12944              the lower bound we've computed above.  */
12945           high = low - 1;
12946         }
12947       else
12948         high = dwarf2_get_attr_constant_value (attr, 1);
12949     }
12950   else
12951     {
12952       attr = dwarf2_attr (die, DW_AT_count, cu);
12953       if (attr)
12954         {
12955           int count = dwarf2_get_attr_constant_value (attr, 1);
12956           high = low + count - 1;
12957         }
12958       else
12959         {
12960           /* Unspecified array length.  */
12961           high = low - 1;
12962         }
12963     }
12964
12965   /* Dwarf-2 specifications explicitly allows to create subrange types
12966      without specifying a base type.
12967      In that case, the base type must be set to the type of
12968      the lower bound, upper bound or count, in that order, if any of these
12969      three attributes references an object that has a type.
12970      If no base type is found, the Dwarf-2 specifications say that
12971      a signed integer type of size equal to the size of an address should
12972      be used.
12973      For the following C code: `extern char gdb_int [];'
12974      GCC produces an empty range DIE.
12975      FIXME: muller/2010-05-28: Possible references to object for low bound,
12976      high bound or count are not yet handled by this code.  */
12977   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12978     {
12979       struct objfile *objfile = cu->objfile;
12980       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12981       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12982       struct type *int_type = objfile_type (objfile)->builtin_int;
12983
12984       /* Test "int", "long int", and "long long int" objfile types,
12985          and select the first one having a size above or equal to the
12986          architecture address size.  */
12987       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12988         base_type = int_type;
12989       else
12990         {
12991           int_type = objfile_type (objfile)->builtin_long;
12992           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12993             base_type = int_type;
12994           else
12995             {
12996               int_type = objfile_type (objfile)->builtin_long_long;
12997               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12998                 base_type = int_type;
12999             }
13000         }
13001     }
13002
13003   negative_mask =
13004     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
13005   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
13006     low |= negative_mask;
13007   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
13008     high |= negative_mask;
13009
13010   range_type = create_range_type (NULL, orig_base_type, low, high);
13011
13012   /* Mark arrays with dynamic length at least as an array of unspecified
13013      length.  GDB could check the boundary but before it gets implemented at
13014      least allow accessing the array elements.  */
13015   if (attr && attr_form_is_block (attr))
13016     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13017
13018   /* Ada expects an empty array on no boundary attributes.  */
13019   if (attr == NULL && cu->language != language_ada)
13020     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
13021
13022   name = dwarf2_name (die, cu);
13023   if (name)
13024     TYPE_NAME (range_type) = name;
13025
13026   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13027   if (attr)
13028     TYPE_LENGTH (range_type) = DW_UNSND (attr);
13029
13030   set_die_type (die, range_type, cu);
13031
13032   /* set_die_type should be already done.  */
13033   set_descriptive_type (range_type, die, cu);
13034
13035   return range_type;
13036 }
13037
13038 static struct type *
13039 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
13040 {
13041   struct type *type;
13042
13043   /* For now, we only support the C meaning of an unspecified type: void.  */
13044
13045   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
13046   TYPE_NAME (type) = dwarf2_name (die, cu);
13047
13048   return set_die_type (die, type, cu);
13049 }
13050
13051 /* Read a single die and all its descendents.  Set the die's sibling
13052    field to NULL; set other fields in the die correctly, and set all
13053    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
13054    location of the info_ptr after reading all of those dies.  PARENT
13055    is the parent of the die in question.  */
13056
13057 static struct die_info *
13058 read_die_and_children (const struct die_reader_specs *reader,
13059                        const gdb_byte *info_ptr,
13060                        const gdb_byte **new_info_ptr,
13061                        struct die_info *parent)
13062 {
13063   struct die_info *die;
13064   const gdb_byte *cur_ptr;
13065   int has_children;
13066
13067   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
13068   if (die == NULL)
13069     {
13070       *new_info_ptr = cur_ptr;
13071       return NULL;
13072     }
13073   store_in_ref_table (die, reader->cu);
13074
13075   if (has_children)
13076     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
13077   else
13078     {
13079       die->child = NULL;
13080       *new_info_ptr = cur_ptr;
13081     }
13082
13083   die->sibling = NULL;
13084   die->parent = parent;
13085   return die;
13086 }
13087
13088 /* Read a die, all of its descendents, and all of its siblings; set
13089    all of the fields of all of the dies correctly.  Arguments are as
13090    in read_die_and_children.  */
13091
13092 static struct die_info *
13093 read_die_and_siblings_1 (const struct die_reader_specs *reader,
13094                          const gdb_byte *info_ptr,
13095                          const gdb_byte **new_info_ptr,
13096                          struct die_info *parent)
13097 {
13098   struct die_info *first_die, *last_sibling;
13099   const gdb_byte *cur_ptr;
13100
13101   cur_ptr = info_ptr;
13102   first_die = last_sibling = NULL;
13103
13104   while (1)
13105     {
13106       struct die_info *die
13107         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
13108
13109       if (die == NULL)
13110         {
13111           *new_info_ptr = cur_ptr;
13112           return first_die;
13113         }
13114
13115       if (!first_die)
13116         first_die = die;
13117       else
13118         last_sibling->sibling = die;
13119
13120       last_sibling = die;
13121     }
13122 }
13123
13124 /* Read a die, all of its descendents, and all of its siblings; set
13125    all of the fields of all of the dies correctly.  Arguments are as
13126    in read_die_and_children.
13127    This the main entry point for reading a DIE and all its children.  */
13128
13129 static struct die_info *
13130 read_die_and_siblings (const struct die_reader_specs *reader,
13131                        const gdb_byte *info_ptr,
13132                        const gdb_byte **new_info_ptr,
13133                        struct die_info *parent)
13134 {
13135   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
13136                                                   new_info_ptr, parent);
13137
13138   if (dwarf2_die_debug)
13139     {
13140       fprintf_unfiltered (gdb_stdlog,
13141                           "Read die from %s@0x%x of %s:\n",
13142                           bfd_section_name (reader->abfd,
13143                                             reader->die_section->asection),
13144                           (unsigned) (info_ptr - reader->die_section->buffer),
13145                           bfd_get_filename (reader->abfd));
13146       dump_die (die, dwarf2_die_debug);
13147     }
13148
13149   return die;
13150 }
13151
13152 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13153    attributes.
13154    The caller is responsible for filling in the extra attributes
13155    and updating (*DIEP)->num_attrs.
13156    Set DIEP to point to a newly allocated die with its information,
13157    except for its child, sibling, and parent fields.
13158    Set HAS_CHILDREN to tell whether the die has children or not.  */
13159
13160 static const gdb_byte *
13161 read_full_die_1 (const struct die_reader_specs *reader,
13162                  struct die_info **diep, const gdb_byte *info_ptr,
13163                  int *has_children, int num_extra_attrs)
13164 {
13165   unsigned int abbrev_number, bytes_read, i;
13166   sect_offset offset;
13167   struct abbrev_info *abbrev;
13168   struct die_info *die;
13169   struct dwarf2_cu *cu = reader->cu;
13170   bfd *abfd = reader->abfd;
13171
13172   offset.sect_off = info_ptr - reader->buffer;
13173   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13174   info_ptr += bytes_read;
13175   if (!abbrev_number)
13176     {
13177       *diep = NULL;
13178       *has_children = 0;
13179       return info_ptr;
13180     }
13181
13182   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13183   if (!abbrev)
13184     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13185            abbrev_number,
13186            bfd_get_filename (abfd));
13187
13188   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13189   die->offset = offset;
13190   die->tag = abbrev->tag;
13191   die->abbrev = abbrev_number;
13192
13193   /* Make the result usable.
13194      The caller needs to update num_attrs after adding the extra
13195      attributes.  */
13196   die->num_attrs = abbrev->num_attrs;
13197
13198   for (i = 0; i < abbrev->num_attrs; ++i)
13199     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13200                                info_ptr);
13201
13202   *diep = die;
13203   *has_children = abbrev->has_children;
13204   return info_ptr;
13205 }
13206
13207 /* Read a die and all its attributes.
13208    Set DIEP to point to a newly allocated die with its information,
13209    except for its child, sibling, and parent fields.
13210    Set HAS_CHILDREN to tell whether the die has children or not.  */
13211
13212 static const gdb_byte *
13213 read_full_die (const struct die_reader_specs *reader,
13214                struct die_info **diep, const gdb_byte *info_ptr,
13215                int *has_children)
13216 {
13217   const gdb_byte *result;
13218
13219   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13220
13221   if (dwarf2_die_debug)
13222     {
13223       fprintf_unfiltered (gdb_stdlog,
13224                           "Read die from %s@0x%x of %s:\n",
13225                           bfd_section_name (reader->abfd,
13226                                             reader->die_section->asection),
13227                           (unsigned) (info_ptr - reader->die_section->buffer),
13228                           bfd_get_filename (reader->abfd));
13229       dump_die (*diep, dwarf2_die_debug);
13230     }
13231
13232   return result;
13233 }
13234 \f
13235 /* Abbreviation tables.
13236
13237    In DWARF version 2, the description of the debugging information is
13238    stored in a separate .debug_abbrev section.  Before we read any
13239    dies from a section we read in all abbreviations and install them
13240    in a hash table.  */
13241
13242 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13243
13244 static struct abbrev_info *
13245 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13246 {
13247   struct abbrev_info *abbrev;
13248
13249   abbrev = (struct abbrev_info *)
13250     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13251   memset (abbrev, 0, sizeof (struct abbrev_info));
13252   return abbrev;
13253 }
13254
13255 /* Add an abbreviation to the table.  */
13256
13257 static void
13258 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13259                          unsigned int abbrev_number,
13260                          struct abbrev_info *abbrev)
13261 {
13262   unsigned int hash_number;
13263
13264   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13265   abbrev->next = abbrev_table->abbrevs[hash_number];
13266   abbrev_table->abbrevs[hash_number] = abbrev;
13267 }
13268
13269 /* Look up an abbrev in the table.
13270    Returns NULL if the abbrev is not found.  */
13271
13272 static struct abbrev_info *
13273 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13274                             unsigned int abbrev_number)
13275 {
13276   unsigned int hash_number;
13277   struct abbrev_info *abbrev;
13278
13279   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13280   abbrev = abbrev_table->abbrevs[hash_number];
13281
13282   while (abbrev)
13283     {
13284       if (abbrev->number == abbrev_number)
13285         return abbrev;
13286       abbrev = abbrev->next;
13287     }
13288   return NULL;
13289 }
13290
13291 /* Read in an abbrev table.  */
13292
13293 static struct abbrev_table *
13294 abbrev_table_read_table (struct dwarf2_section_info *section,
13295                          sect_offset offset)
13296 {
13297   struct objfile *objfile = dwarf2_per_objfile->objfile;
13298   bfd *abfd = section->asection->owner;
13299   struct abbrev_table *abbrev_table;
13300   const gdb_byte *abbrev_ptr;
13301   struct abbrev_info *cur_abbrev;
13302   unsigned int abbrev_number, bytes_read, abbrev_name;
13303   unsigned int abbrev_form;
13304   struct attr_abbrev *cur_attrs;
13305   unsigned int allocated_attrs;
13306
13307   abbrev_table = XMALLOC (struct abbrev_table);
13308   abbrev_table->offset = offset;
13309   obstack_init (&abbrev_table->abbrev_obstack);
13310   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13311                                          (ABBREV_HASH_SIZE
13312                                           * sizeof (struct abbrev_info *)));
13313   memset (abbrev_table->abbrevs, 0,
13314           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13315
13316   dwarf2_read_section (objfile, section);
13317   abbrev_ptr = section->buffer + offset.sect_off;
13318   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13319   abbrev_ptr += bytes_read;
13320
13321   allocated_attrs = ATTR_ALLOC_CHUNK;
13322   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13323
13324   /* Loop until we reach an abbrev number of 0.  */
13325   while (abbrev_number)
13326     {
13327       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13328
13329       /* read in abbrev header */
13330       cur_abbrev->number = abbrev_number;
13331       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13332       abbrev_ptr += bytes_read;
13333       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13334       abbrev_ptr += 1;
13335
13336       /* now read in declarations */
13337       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13338       abbrev_ptr += bytes_read;
13339       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13340       abbrev_ptr += bytes_read;
13341       while (abbrev_name)
13342         {
13343           if (cur_abbrev->num_attrs == allocated_attrs)
13344             {
13345               allocated_attrs += ATTR_ALLOC_CHUNK;
13346               cur_attrs
13347                 = xrealloc (cur_attrs, (allocated_attrs
13348                                         * sizeof (struct attr_abbrev)));
13349             }
13350
13351           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13352           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13353           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13354           abbrev_ptr += bytes_read;
13355           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13356           abbrev_ptr += bytes_read;
13357         }
13358
13359       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13360                                          (cur_abbrev->num_attrs
13361                                           * sizeof (struct attr_abbrev)));
13362       memcpy (cur_abbrev->attrs, cur_attrs,
13363               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13364
13365       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13366
13367       /* Get next abbreviation.
13368          Under Irix6 the abbreviations for a compilation unit are not
13369          always properly terminated with an abbrev number of 0.
13370          Exit loop if we encounter an abbreviation which we have
13371          already read (which means we are about to read the abbreviations
13372          for the next compile unit) or if the end of the abbreviation
13373          table is reached.  */
13374       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13375         break;
13376       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13377       abbrev_ptr += bytes_read;
13378       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13379         break;
13380     }
13381
13382   xfree (cur_attrs);
13383   return abbrev_table;
13384 }
13385
13386 /* Free the resources held by ABBREV_TABLE.  */
13387
13388 static void
13389 abbrev_table_free (struct abbrev_table *abbrev_table)
13390 {
13391   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13392   xfree (abbrev_table);
13393 }
13394
13395 /* Same as abbrev_table_free but as a cleanup.
13396    We pass in a pointer to the pointer to the table so that we can
13397    set the pointer to NULL when we're done.  It also simplifies
13398    build_type_unit_groups.  */
13399
13400 static void
13401 abbrev_table_free_cleanup (void *table_ptr)
13402 {
13403   struct abbrev_table **abbrev_table_ptr = table_ptr;
13404
13405   if (*abbrev_table_ptr != NULL)
13406     abbrev_table_free (*abbrev_table_ptr);
13407   *abbrev_table_ptr = NULL;
13408 }
13409
13410 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13411
13412 static void
13413 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13414                      struct dwarf2_section_info *abbrev_section)
13415 {
13416   cu->abbrev_table =
13417     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13418 }
13419
13420 /* Release the memory used by the abbrev table for a compilation unit.  */
13421
13422 static void
13423 dwarf2_free_abbrev_table (void *ptr_to_cu)
13424 {
13425   struct dwarf2_cu *cu = ptr_to_cu;
13426
13427   abbrev_table_free (cu->abbrev_table);
13428   /* Set this to NULL so that we SEGV if we try to read it later,
13429      and also because free_comp_unit verifies this is NULL.  */
13430   cu->abbrev_table = NULL;
13431 }
13432 \f
13433 /* Returns nonzero if TAG represents a type that we might generate a partial
13434    symbol for.  */
13435
13436 static int
13437 is_type_tag_for_partial (int tag)
13438 {
13439   switch (tag)
13440     {
13441 #if 0
13442     /* Some types that would be reasonable to generate partial symbols for,
13443        that we don't at present.  */
13444     case DW_TAG_array_type:
13445     case DW_TAG_file_type:
13446     case DW_TAG_ptr_to_member_type:
13447     case DW_TAG_set_type:
13448     case DW_TAG_string_type:
13449     case DW_TAG_subroutine_type:
13450 #endif
13451     case DW_TAG_base_type:
13452     case DW_TAG_class_type:
13453     case DW_TAG_interface_type:
13454     case DW_TAG_enumeration_type:
13455     case DW_TAG_structure_type:
13456     case DW_TAG_subrange_type:
13457     case DW_TAG_typedef:
13458     case DW_TAG_union_type:
13459       return 1;
13460     default:
13461       return 0;
13462     }
13463 }
13464
13465 /* Load all DIEs that are interesting for partial symbols into memory.  */
13466
13467 static struct partial_die_info *
13468 load_partial_dies (const struct die_reader_specs *reader,
13469                    const gdb_byte *info_ptr, int building_psymtab)
13470 {
13471   struct dwarf2_cu *cu = reader->cu;
13472   struct objfile *objfile = cu->objfile;
13473   struct partial_die_info *part_die;
13474   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13475   struct abbrev_info *abbrev;
13476   unsigned int bytes_read;
13477   unsigned int load_all = 0;
13478   int nesting_level = 1;
13479
13480   parent_die = NULL;
13481   last_die = NULL;
13482
13483   gdb_assert (cu->per_cu != NULL);
13484   if (cu->per_cu->load_all_dies)
13485     load_all = 1;
13486
13487   cu->partial_dies
13488     = htab_create_alloc_ex (cu->header.length / 12,
13489                             partial_die_hash,
13490                             partial_die_eq,
13491                             NULL,
13492                             &cu->comp_unit_obstack,
13493                             hashtab_obstack_allocate,
13494                             dummy_obstack_deallocate);
13495
13496   part_die = obstack_alloc (&cu->comp_unit_obstack,
13497                             sizeof (struct partial_die_info));
13498
13499   while (1)
13500     {
13501       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13502
13503       /* A NULL abbrev means the end of a series of children.  */
13504       if (abbrev == NULL)
13505         {
13506           if (--nesting_level == 0)
13507             {
13508               /* PART_DIE was probably the last thing allocated on the
13509                  comp_unit_obstack, so we could call obstack_free
13510                  here.  We don't do that because the waste is small,
13511                  and will be cleaned up when we're done with this
13512                  compilation unit.  This way, we're also more robust
13513                  against other users of the comp_unit_obstack.  */
13514               return first_die;
13515             }
13516           info_ptr += bytes_read;
13517           last_die = parent_die;
13518           parent_die = parent_die->die_parent;
13519           continue;
13520         }
13521
13522       /* Check for template arguments.  We never save these; if
13523          they're seen, we just mark the parent, and go on our way.  */
13524       if (parent_die != NULL
13525           && cu->language == language_cplus
13526           && (abbrev->tag == DW_TAG_template_type_param
13527               || abbrev->tag == DW_TAG_template_value_param))
13528         {
13529           parent_die->has_template_arguments = 1;
13530
13531           if (!load_all)
13532             {
13533               /* We don't need a partial DIE for the template argument.  */
13534               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13535               continue;
13536             }
13537         }
13538
13539       /* We only recurse into c++ subprograms looking for template arguments.
13540          Skip their other children.  */
13541       if (!load_all
13542           && cu->language == language_cplus
13543           && parent_die != NULL
13544           && parent_die->tag == DW_TAG_subprogram)
13545         {
13546           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13547           continue;
13548         }
13549
13550       /* Check whether this DIE is interesting enough to save.  Normally
13551          we would not be interested in members here, but there may be
13552          later variables referencing them via DW_AT_specification (for
13553          static members).  */
13554       if (!load_all
13555           && !is_type_tag_for_partial (abbrev->tag)
13556           && abbrev->tag != DW_TAG_constant
13557           && abbrev->tag != DW_TAG_enumerator
13558           && abbrev->tag != DW_TAG_subprogram
13559           && abbrev->tag != DW_TAG_lexical_block
13560           && abbrev->tag != DW_TAG_variable
13561           && abbrev->tag != DW_TAG_namespace
13562           && abbrev->tag != DW_TAG_module
13563           && abbrev->tag != DW_TAG_member
13564           && abbrev->tag != DW_TAG_imported_unit)
13565         {
13566           /* Otherwise we skip to the next sibling, if any.  */
13567           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13568           continue;
13569         }
13570
13571       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13572                                    info_ptr);
13573
13574       /* This two-pass algorithm for processing partial symbols has a
13575          high cost in cache pressure.  Thus, handle some simple cases
13576          here which cover the majority of C partial symbols.  DIEs
13577          which neither have specification tags in them, nor could have
13578          specification tags elsewhere pointing at them, can simply be
13579          processed and discarded.
13580
13581          This segment is also optional; scan_partial_symbols and
13582          add_partial_symbol will handle these DIEs if we chain
13583          them in normally.  When compilers which do not emit large
13584          quantities of duplicate debug information are more common,
13585          this code can probably be removed.  */
13586
13587       /* Any complete simple types at the top level (pretty much all
13588          of them, for a language without namespaces), can be processed
13589          directly.  */
13590       if (parent_die == NULL
13591           && part_die->has_specification == 0
13592           && part_die->is_declaration == 0
13593           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13594               || part_die->tag == DW_TAG_base_type
13595               || part_die->tag == DW_TAG_subrange_type))
13596         {
13597           if (building_psymtab && part_die->name != NULL)
13598             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13599                                  VAR_DOMAIN, LOC_TYPEDEF,
13600                                  &objfile->static_psymbols,
13601                                  0, (CORE_ADDR) 0, cu->language, objfile);
13602           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13603           continue;
13604         }
13605
13606       /* The exception for DW_TAG_typedef with has_children above is
13607          a workaround of GCC PR debug/47510.  In the case of this complaint
13608          type_name_no_tag_or_error will error on such types later.
13609
13610          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13611          it could not find the child DIEs referenced later, this is checked
13612          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13613
13614       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13615         complaint (&symfile_complaints,
13616                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13617                      "- DIE at 0x%x [in module %s]"),
13618                    part_die->offset.sect_off, objfile->name);
13619
13620       /* If we're at the second level, and we're an enumerator, and
13621          our parent has no specification (meaning possibly lives in a
13622          namespace elsewhere), then we can add the partial symbol now
13623          instead of queueing it.  */
13624       if (part_die->tag == DW_TAG_enumerator
13625           && parent_die != NULL
13626           && parent_die->die_parent == NULL
13627           && parent_die->tag == DW_TAG_enumeration_type
13628           && parent_die->has_specification == 0)
13629         {
13630           if (part_die->name == NULL)
13631             complaint (&symfile_complaints,
13632                        _("malformed enumerator DIE ignored"));
13633           else if (building_psymtab)
13634             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13635                                  VAR_DOMAIN, LOC_CONST,
13636                                  (cu->language == language_cplus
13637                                   || cu->language == language_java)
13638                                  ? &objfile->global_psymbols
13639                                  : &objfile->static_psymbols,
13640                                  0, (CORE_ADDR) 0, cu->language, objfile);
13641
13642           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13643           continue;
13644         }
13645
13646       /* We'll save this DIE so link it in.  */
13647       part_die->die_parent = parent_die;
13648       part_die->die_sibling = NULL;
13649       part_die->die_child = NULL;
13650
13651       if (last_die && last_die == parent_die)
13652         last_die->die_child = part_die;
13653       else if (last_die)
13654         last_die->die_sibling = part_die;
13655
13656       last_die = part_die;
13657
13658       if (first_die == NULL)
13659         first_die = part_die;
13660
13661       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13662          find interesting need to be in the hash table, because we
13663          also have the parent/sibling/child chains; only those that we
13664          might refer to by offset later during partial symbol reading.
13665
13666          For now this means things that might have be the target of a
13667          DW_AT_specification, DW_AT_abstract_origin, or
13668          DW_AT_extension.  DW_AT_extension will refer only to
13669          namespaces; DW_AT_abstract_origin refers to functions (and
13670          many things under the function DIE, but we do not recurse
13671          into function DIEs during partial symbol reading) and
13672          possibly variables as well; DW_AT_specification refers to
13673          declarations.  Declarations ought to have the DW_AT_declaration
13674          flag.  It happens that GCC forgets to put it in sometimes, but
13675          only for functions, not for types.
13676
13677          Adding more things than necessary to the hash table is harmless
13678          except for the performance cost.  Adding too few will result in
13679          wasted time in find_partial_die, when we reread the compilation
13680          unit with load_all_dies set.  */
13681
13682       if (load_all
13683           || abbrev->tag == DW_TAG_constant
13684           || abbrev->tag == DW_TAG_subprogram
13685           || abbrev->tag == DW_TAG_variable
13686           || abbrev->tag == DW_TAG_namespace
13687           || part_die->is_declaration)
13688         {
13689           void **slot;
13690
13691           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13692                                            part_die->offset.sect_off, INSERT);
13693           *slot = part_die;
13694         }
13695
13696       part_die = obstack_alloc (&cu->comp_unit_obstack,
13697                                 sizeof (struct partial_die_info));
13698
13699       /* For some DIEs we want to follow their children (if any).  For C
13700          we have no reason to follow the children of structures; for other
13701          languages we have to, so that we can get at method physnames
13702          to infer fully qualified class names, for DW_AT_specification,
13703          and for C++ template arguments.  For C++, we also look one level
13704          inside functions to find template arguments (if the name of the
13705          function does not already contain the template arguments).
13706
13707          For Ada, we need to scan the children of subprograms and lexical
13708          blocks as well because Ada allows the definition of nested
13709          entities that could be interesting for the debugger, such as
13710          nested subprograms for instance.  */
13711       if (last_die->has_children
13712           && (load_all
13713               || last_die->tag == DW_TAG_namespace
13714               || last_die->tag == DW_TAG_module
13715               || last_die->tag == DW_TAG_enumeration_type
13716               || (cu->language == language_cplus
13717                   && last_die->tag == DW_TAG_subprogram
13718                   && (last_die->name == NULL
13719                       || strchr (last_die->name, '<') == NULL))
13720               || (cu->language != language_c
13721                   && (last_die->tag == DW_TAG_class_type
13722                       || last_die->tag == DW_TAG_interface_type
13723                       || last_die->tag == DW_TAG_structure_type
13724                       || last_die->tag == DW_TAG_union_type))
13725               || (cu->language == language_ada
13726                   && (last_die->tag == DW_TAG_subprogram
13727                       || last_die->tag == DW_TAG_lexical_block))))
13728         {
13729           nesting_level++;
13730           parent_die = last_die;
13731           continue;
13732         }
13733
13734       /* Otherwise we skip to the next sibling, if any.  */
13735       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13736
13737       /* Back to the top, do it again.  */
13738     }
13739 }
13740
13741 /* Read a minimal amount of information into the minimal die structure.  */
13742
13743 static const gdb_byte *
13744 read_partial_die (const struct die_reader_specs *reader,
13745                   struct partial_die_info *part_die,
13746                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13747                   const gdb_byte *info_ptr)
13748 {
13749   struct dwarf2_cu *cu = reader->cu;
13750   struct objfile *objfile = cu->objfile;
13751   const gdb_byte *buffer = reader->buffer;
13752   unsigned int i;
13753   struct attribute attr;
13754   int has_low_pc_attr = 0;
13755   int has_high_pc_attr = 0;
13756   int high_pc_relative = 0;
13757
13758   memset (part_die, 0, sizeof (struct partial_die_info));
13759
13760   part_die->offset.sect_off = info_ptr - buffer;
13761
13762   info_ptr += abbrev_len;
13763
13764   if (abbrev == NULL)
13765     return info_ptr;
13766
13767   part_die->tag = abbrev->tag;
13768   part_die->has_children = abbrev->has_children;
13769
13770   for (i = 0; i < abbrev->num_attrs; ++i)
13771     {
13772       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13773
13774       /* Store the data if it is of an attribute we want to keep in a
13775          partial symbol table.  */
13776       switch (attr.name)
13777         {
13778         case DW_AT_name:
13779           switch (part_die->tag)
13780             {
13781             case DW_TAG_compile_unit:
13782             case DW_TAG_partial_unit:
13783             case DW_TAG_type_unit:
13784               /* Compilation units have a DW_AT_name that is a filename, not
13785                  a source language identifier.  */
13786             case DW_TAG_enumeration_type:
13787             case DW_TAG_enumerator:
13788               /* These tags always have simple identifiers already; no need
13789                  to canonicalize them.  */
13790               part_die->name = DW_STRING (&attr);
13791               break;
13792             default:
13793               part_die->name
13794                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13795                                             &objfile->objfile_obstack);
13796               break;
13797             }
13798           break;
13799         case DW_AT_linkage_name:
13800         case DW_AT_MIPS_linkage_name:
13801           /* Note that both forms of linkage name might appear.  We
13802              assume they will be the same, and we only store the last
13803              one we see.  */
13804           if (cu->language == language_ada)
13805             part_die->name = DW_STRING (&attr);
13806           part_die->linkage_name = DW_STRING (&attr);
13807           break;
13808         case DW_AT_low_pc:
13809           has_low_pc_attr = 1;
13810           part_die->lowpc = DW_ADDR (&attr);
13811           break;
13812         case DW_AT_high_pc:
13813           has_high_pc_attr = 1;
13814           if (attr.form == DW_FORM_addr
13815               || attr.form == DW_FORM_GNU_addr_index)
13816             part_die->highpc = DW_ADDR (&attr);
13817           else
13818             {
13819               high_pc_relative = 1;
13820               part_die->highpc = DW_UNSND (&attr);
13821             }
13822           break;
13823         case DW_AT_location:
13824           /* Support the .debug_loc offsets.  */
13825           if (attr_form_is_block (&attr))
13826             {
13827                part_die->d.locdesc = DW_BLOCK (&attr);
13828             }
13829           else if (attr_form_is_section_offset (&attr))
13830             {
13831               dwarf2_complex_location_expr_complaint ();
13832             }
13833           else
13834             {
13835               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13836                                                      "partial symbol information");
13837             }
13838           break;
13839         case DW_AT_external:
13840           part_die->is_external = DW_UNSND (&attr);
13841           break;
13842         case DW_AT_declaration:
13843           part_die->is_declaration = DW_UNSND (&attr);
13844           break;
13845         case DW_AT_type:
13846           part_die->has_type = 1;
13847           break;
13848         case DW_AT_abstract_origin:
13849         case DW_AT_specification:
13850         case DW_AT_extension:
13851           part_die->has_specification = 1;
13852           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13853           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13854                                    || cu->per_cu->is_dwz);
13855           break;
13856         case DW_AT_sibling:
13857           /* Ignore absolute siblings, they might point outside of
13858              the current compile unit.  */
13859           if (attr.form == DW_FORM_ref_addr)
13860             complaint (&symfile_complaints,
13861                        _("ignoring absolute DW_AT_sibling"));
13862           else
13863             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13864           break;
13865         case DW_AT_byte_size:
13866           part_die->has_byte_size = 1;
13867           break;
13868         case DW_AT_calling_convention:
13869           /* DWARF doesn't provide a way to identify a program's source-level
13870              entry point.  DW_AT_calling_convention attributes are only meant
13871              to describe functions' calling conventions.
13872
13873              However, because it's a necessary piece of information in
13874              Fortran, and because DW_CC_program is the only piece of debugging
13875              information whose definition refers to a 'main program' at all,
13876              several compilers have begun marking Fortran main programs with
13877              DW_CC_program --- even when those functions use the standard
13878              calling conventions.
13879
13880              So until DWARF specifies a way to provide this information and
13881              compilers pick up the new representation, we'll support this
13882              practice.  */
13883           if (DW_UNSND (&attr) == DW_CC_program
13884               && cu->language == language_fortran)
13885             {
13886               set_main_name (part_die->name);
13887
13888               /* As this DIE has a static linkage the name would be difficult
13889                  to look up later.  */
13890               language_of_main = language_fortran;
13891             }
13892           break;
13893         case DW_AT_inline:
13894           if (DW_UNSND (&attr) == DW_INL_inlined
13895               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13896             part_die->may_be_inlined = 1;
13897           break;
13898
13899         case DW_AT_import:
13900           if (part_die->tag == DW_TAG_imported_unit)
13901             {
13902               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13903               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13904                                   || cu->per_cu->is_dwz);
13905             }
13906           break;
13907
13908         default:
13909           break;
13910         }
13911     }
13912
13913   if (high_pc_relative)
13914     part_die->highpc += part_die->lowpc;
13915
13916   if (has_low_pc_attr && has_high_pc_attr)
13917     {
13918       /* When using the GNU linker, .gnu.linkonce. sections are used to
13919          eliminate duplicate copies of functions and vtables and such.
13920          The linker will arbitrarily choose one and discard the others.
13921          The AT_*_pc values for such functions refer to local labels in
13922          these sections.  If the section from that file was discarded, the
13923          labels are not in the output, so the relocs get a value of 0.
13924          If this is a discarded function, mark the pc bounds as invalid,
13925          so that GDB will ignore it.  */
13926       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13927         {
13928           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13929
13930           complaint (&symfile_complaints,
13931                      _("DW_AT_low_pc %s is zero "
13932                        "for DIE at 0x%x [in module %s]"),
13933                      paddress (gdbarch, part_die->lowpc),
13934                      part_die->offset.sect_off, objfile->name);
13935         }
13936       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13937       else if (part_die->lowpc >= part_die->highpc)
13938         {
13939           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13940
13941           complaint (&symfile_complaints,
13942                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13943                        "for DIE at 0x%x [in module %s]"),
13944                      paddress (gdbarch, part_die->lowpc),
13945                      paddress (gdbarch, part_die->highpc),
13946                      part_die->offset.sect_off, objfile->name);
13947         }
13948       else
13949         part_die->has_pc_info = 1;
13950     }
13951
13952   return info_ptr;
13953 }
13954
13955 /* Find a cached partial DIE at OFFSET in CU.  */
13956
13957 static struct partial_die_info *
13958 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13959 {
13960   struct partial_die_info *lookup_die = NULL;
13961   struct partial_die_info part_die;
13962
13963   part_die.offset = offset;
13964   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13965                                     offset.sect_off);
13966
13967   return lookup_die;
13968 }
13969
13970 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13971    except in the case of .debug_types DIEs which do not reference
13972    outside their CU (they do however referencing other types via
13973    DW_FORM_ref_sig8).  */
13974
13975 static struct partial_die_info *
13976 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13977 {
13978   struct objfile *objfile = cu->objfile;
13979   struct dwarf2_per_cu_data *per_cu = NULL;
13980   struct partial_die_info *pd = NULL;
13981
13982   if (offset_in_dwz == cu->per_cu->is_dwz
13983       && offset_in_cu_p (&cu->header, offset))
13984     {
13985       pd = find_partial_die_in_comp_unit (offset, cu);
13986       if (pd != NULL)
13987         return pd;
13988       /* We missed recording what we needed.
13989          Load all dies and try again.  */
13990       per_cu = cu->per_cu;
13991     }
13992   else
13993     {
13994       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13995       if (cu->per_cu->is_debug_types)
13996         {
13997           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13998                    " external reference to offset 0x%lx [in module %s].\n"),
13999                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
14000                  bfd_get_filename (objfile->obfd));
14001         }
14002       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
14003                                                  objfile);
14004
14005       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
14006         load_partial_comp_unit (per_cu);
14007
14008       per_cu->cu->last_used = 0;
14009       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14010     }
14011
14012   /* If we didn't find it, and not all dies have been loaded,
14013      load them all and try again.  */
14014
14015   if (pd == NULL && per_cu->load_all_dies == 0)
14016     {
14017       per_cu->load_all_dies = 1;
14018
14019       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
14020          THIS_CU->cu may already be in use.  So we can't just free it and
14021          replace its DIEs with the ones we read in.  Instead, we leave those
14022          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
14023          and clobber THIS_CU->cu->partial_dies with the hash table for the new
14024          set.  */
14025       load_partial_comp_unit (per_cu);
14026
14027       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
14028     }
14029
14030   if (pd == NULL)
14031     internal_error (__FILE__, __LINE__,
14032                     _("could not find partial DIE 0x%x "
14033                       "in cache [from module %s]\n"),
14034                     offset.sect_off, bfd_get_filename (objfile->obfd));
14035   return pd;
14036 }
14037
14038 /* See if we can figure out if the class lives in a namespace.  We do
14039    this by looking for a member function; its demangled name will
14040    contain namespace info, if there is any.  */
14041
14042 static void
14043 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
14044                                   struct dwarf2_cu *cu)
14045 {
14046   /* NOTE: carlton/2003-10-07: Getting the info this way changes
14047      what template types look like, because the demangler
14048      frequently doesn't give the same name as the debug info.  We
14049      could fix this by only using the demangled name to get the
14050      prefix (but see comment in read_structure_type).  */
14051
14052   struct partial_die_info *real_pdi;
14053   struct partial_die_info *child_pdi;
14054
14055   /* If this DIE (this DIE's specification, if any) has a parent, then
14056      we should not do this.  We'll prepend the parent's fully qualified
14057      name when we create the partial symbol.  */
14058
14059   real_pdi = struct_pdi;
14060   while (real_pdi->has_specification)
14061     real_pdi = find_partial_die (real_pdi->spec_offset,
14062                                  real_pdi->spec_is_dwz, cu);
14063
14064   if (real_pdi->die_parent != NULL)
14065     return;
14066
14067   for (child_pdi = struct_pdi->die_child;
14068        child_pdi != NULL;
14069        child_pdi = child_pdi->die_sibling)
14070     {
14071       if (child_pdi->tag == DW_TAG_subprogram
14072           && child_pdi->linkage_name != NULL)
14073         {
14074           char *actual_class_name
14075             = language_class_name_from_physname (cu->language_defn,
14076                                                  child_pdi->linkage_name);
14077           if (actual_class_name != NULL)
14078             {
14079               struct_pdi->name
14080                 = obstack_copy0 (&cu->objfile->objfile_obstack,
14081                                  actual_class_name,
14082                                  strlen (actual_class_name));
14083               xfree (actual_class_name);
14084             }
14085           break;
14086         }
14087     }
14088 }
14089
14090 /* Adjust PART_DIE before generating a symbol for it.  This function
14091    may set the is_external flag or change the DIE's name.  */
14092
14093 static void
14094 fixup_partial_die (struct partial_die_info *part_die,
14095                    struct dwarf2_cu *cu)
14096 {
14097   /* Once we've fixed up a die, there's no point in doing so again.
14098      This also avoids a memory leak if we were to call
14099      guess_partial_die_structure_name multiple times.  */
14100   if (part_die->fixup_called)
14101     return;
14102
14103   /* If we found a reference attribute and the DIE has no name, try
14104      to find a name in the referred to DIE.  */
14105
14106   if (part_die->name == NULL && part_die->has_specification)
14107     {
14108       struct partial_die_info *spec_die;
14109
14110       spec_die = find_partial_die (part_die->spec_offset,
14111                                    part_die->spec_is_dwz, cu);
14112
14113       fixup_partial_die (spec_die, cu);
14114
14115       if (spec_die->name)
14116         {
14117           part_die->name = spec_die->name;
14118
14119           /* Copy DW_AT_external attribute if it is set.  */
14120           if (spec_die->is_external)
14121             part_die->is_external = spec_die->is_external;
14122         }
14123     }
14124
14125   /* Set default names for some unnamed DIEs.  */
14126
14127   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
14128     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
14129
14130   /* If there is no parent die to provide a namespace, and there are
14131      children, see if we can determine the namespace from their linkage
14132      name.  */
14133   if (cu->language == language_cplus
14134       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
14135       && part_die->die_parent == NULL
14136       && part_die->has_children
14137       && (part_die->tag == DW_TAG_class_type
14138           || part_die->tag == DW_TAG_structure_type
14139           || part_die->tag == DW_TAG_union_type))
14140     guess_partial_die_structure_name (part_die, cu);
14141
14142   /* GCC might emit a nameless struct or union that has a linkage
14143      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
14144   if (part_die->name == NULL
14145       && (part_die->tag == DW_TAG_class_type
14146           || part_die->tag == DW_TAG_interface_type
14147           || part_die->tag == DW_TAG_structure_type
14148           || part_die->tag == DW_TAG_union_type)
14149       && part_die->linkage_name != NULL)
14150     {
14151       char *demangled;
14152
14153       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
14154       if (demangled)
14155         {
14156           const char *base;
14157
14158           /* Strip any leading namespaces/classes, keep only the base name.
14159              DW_AT_name for named DIEs does not contain the prefixes.  */
14160           base = strrchr (demangled, ':');
14161           if (base && base > demangled && base[-1] == ':')
14162             base++;
14163           else
14164             base = demangled;
14165
14166           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14167                                           base, strlen (base));
14168           xfree (demangled);
14169         }
14170     }
14171
14172   part_die->fixup_called = 1;
14173 }
14174
14175 /* Read an attribute value described by an attribute form.  */
14176
14177 static const gdb_byte *
14178 read_attribute_value (const struct die_reader_specs *reader,
14179                       struct attribute *attr, unsigned form,
14180                       const gdb_byte *info_ptr)
14181 {
14182   struct dwarf2_cu *cu = reader->cu;
14183   bfd *abfd = reader->abfd;
14184   struct comp_unit_head *cu_header = &cu->header;
14185   unsigned int bytes_read;
14186   struct dwarf_block *blk;
14187
14188   attr->form = form;
14189   switch (form)
14190     {
14191     case DW_FORM_ref_addr:
14192       if (cu->header.version == 2)
14193         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14194       else
14195         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14196                                        &cu->header, &bytes_read);
14197       info_ptr += bytes_read;
14198       break;
14199     case DW_FORM_GNU_ref_alt:
14200       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14201       info_ptr += bytes_read;
14202       break;
14203     case DW_FORM_addr:
14204       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14205       info_ptr += bytes_read;
14206       break;
14207     case DW_FORM_block2:
14208       blk = dwarf_alloc_block (cu);
14209       blk->size = read_2_bytes (abfd, info_ptr);
14210       info_ptr += 2;
14211       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14212       info_ptr += blk->size;
14213       DW_BLOCK (attr) = blk;
14214       break;
14215     case DW_FORM_block4:
14216       blk = dwarf_alloc_block (cu);
14217       blk->size = read_4_bytes (abfd, info_ptr);
14218       info_ptr += 4;
14219       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14220       info_ptr += blk->size;
14221       DW_BLOCK (attr) = blk;
14222       break;
14223     case DW_FORM_data2:
14224       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14225       info_ptr += 2;
14226       break;
14227     case DW_FORM_data4:
14228       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14229       info_ptr += 4;
14230       break;
14231     case DW_FORM_data8:
14232       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14233       info_ptr += 8;
14234       break;
14235     case DW_FORM_sec_offset:
14236       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14237       info_ptr += bytes_read;
14238       break;
14239     case DW_FORM_string:
14240       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14241       DW_STRING_IS_CANONICAL (attr) = 0;
14242       info_ptr += bytes_read;
14243       break;
14244     case DW_FORM_strp:
14245       if (!cu->per_cu->is_dwz)
14246         {
14247           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14248                                                    &bytes_read);
14249           DW_STRING_IS_CANONICAL (attr) = 0;
14250           info_ptr += bytes_read;
14251           break;
14252         }
14253       /* FALLTHROUGH */
14254     case DW_FORM_GNU_strp_alt:
14255       {
14256         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14257         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14258                                           &bytes_read);
14259
14260         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14261         DW_STRING_IS_CANONICAL (attr) = 0;
14262         info_ptr += bytes_read;
14263       }
14264       break;
14265     case DW_FORM_exprloc:
14266     case DW_FORM_block:
14267       blk = dwarf_alloc_block (cu);
14268       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14269       info_ptr += bytes_read;
14270       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14271       info_ptr += blk->size;
14272       DW_BLOCK (attr) = blk;
14273       break;
14274     case DW_FORM_block1:
14275       blk = dwarf_alloc_block (cu);
14276       blk->size = read_1_byte (abfd, info_ptr);
14277       info_ptr += 1;
14278       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14279       info_ptr += blk->size;
14280       DW_BLOCK (attr) = blk;
14281       break;
14282     case DW_FORM_data1:
14283       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14284       info_ptr += 1;
14285       break;
14286     case DW_FORM_flag:
14287       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14288       info_ptr += 1;
14289       break;
14290     case DW_FORM_flag_present:
14291       DW_UNSND (attr) = 1;
14292       break;
14293     case DW_FORM_sdata:
14294       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14295       info_ptr += bytes_read;
14296       break;
14297     case DW_FORM_udata:
14298       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14299       info_ptr += bytes_read;
14300       break;
14301     case DW_FORM_ref1:
14302       DW_UNSND (attr) = (cu->header.offset.sect_off
14303                          + read_1_byte (abfd, info_ptr));
14304       info_ptr += 1;
14305       break;
14306     case DW_FORM_ref2:
14307       DW_UNSND (attr) = (cu->header.offset.sect_off
14308                          + read_2_bytes (abfd, info_ptr));
14309       info_ptr += 2;
14310       break;
14311     case DW_FORM_ref4:
14312       DW_UNSND (attr) = (cu->header.offset.sect_off
14313                          + read_4_bytes (abfd, info_ptr));
14314       info_ptr += 4;
14315       break;
14316     case DW_FORM_ref8:
14317       DW_UNSND (attr) = (cu->header.offset.sect_off
14318                          + read_8_bytes (abfd, info_ptr));
14319       info_ptr += 8;
14320       break;
14321     case DW_FORM_ref_sig8:
14322       /* Convert the signature to something we can record in DW_UNSND
14323          for later lookup.
14324          NOTE: This is NULL if the type wasn't found.  */
14325       DW_SIGNATURED_TYPE (attr) =
14326         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14327       info_ptr += 8;
14328       break;
14329     case DW_FORM_ref_udata:
14330       DW_UNSND (attr) = (cu->header.offset.sect_off
14331                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14332       info_ptr += bytes_read;
14333       break;
14334     case DW_FORM_indirect:
14335       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14336       info_ptr += bytes_read;
14337       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14338       break;
14339     case DW_FORM_GNU_addr_index:
14340       if (reader->dwo_file == NULL)
14341         {
14342           /* For now flag a hard error.
14343              Later we can turn this into a complaint.  */
14344           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14345                  dwarf_form_name (form),
14346                  bfd_get_filename (abfd));
14347         }
14348       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14349       info_ptr += bytes_read;
14350       break;
14351     case DW_FORM_GNU_str_index:
14352       if (reader->dwo_file == NULL)
14353         {
14354           /* For now flag a hard error.
14355              Later we can turn this into a complaint if warranted.  */
14356           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14357                  dwarf_form_name (form),
14358                  bfd_get_filename (abfd));
14359         }
14360       {
14361         ULONGEST str_index =
14362           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14363
14364         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14365         DW_STRING_IS_CANONICAL (attr) = 0;
14366         info_ptr += bytes_read;
14367       }
14368       break;
14369     default:
14370       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14371              dwarf_form_name (form),
14372              bfd_get_filename (abfd));
14373     }
14374
14375   /* Super hack.  */
14376   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14377     attr->form = DW_FORM_GNU_ref_alt;
14378
14379   /* We have seen instances where the compiler tried to emit a byte
14380      size attribute of -1 which ended up being encoded as an unsigned
14381      0xffffffff.  Although 0xffffffff is technically a valid size value,
14382      an object of this size seems pretty unlikely so we can relatively
14383      safely treat these cases as if the size attribute was invalid and
14384      treat them as zero by default.  */
14385   if (attr->name == DW_AT_byte_size
14386       && form == DW_FORM_data4
14387       && DW_UNSND (attr) >= 0xffffffff)
14388     {
14389       complaint
14390         (&symfile_complaints,
14391          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14392          hex_string (DW_UNSND (attr)));
14393       DW_UNSND (attr) = 0;
14394     }
14395
14396   return info_ptr;
14397 }
14398
14399 /* Read an attribute described by an abbreviated attribute.  */
14400
14401 static const gdb_byte *
14402 read_attribute (const struct die_reader_specs *reader,
14403                 struct attribute *attr, struct attr_abbrev *abbrev,
14404                 const gdb_byte *info_ptr)
14405 {
14406   attr->name = abbrev->name;
14407   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14408 }
14409
14410 /* Read dwarf information from a buffer.  */
14411
14412 static unsigned int
14413 read_1_byte (bfd *abfd, const gdb_byte *buf)
14414 {
14415   return bfd_get_8 (abfd, buf);
14416 }
14417
14418 static int
14419 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14420 {
14421   return bfd_get_signed_8 (abfd, buf);
14422 }
14423
14424 static unsigned int
14425 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14426 {
14427   return bfd_get_16 (abfd, buf);
14428 }
14429
14430 static int
14431 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14432 {
14433   return bfd_get_signed_16 (abfd, buf);
14434 }
14435
14436 static unsigned int
14437 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14438 {
14439   return bfd_get_32 (abfd, buf);
14440 }
14441
14442 static int
14443 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14444 {
14445   return bfd_get_signed_32 (abfd, buf);
14446 }
14447
14448 static ULONGEST
14449 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14450 {
14451   return bfd_get_64 (abfd, buf);
14452 }
14453
14454 static CORE_ADDR
14455 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
14456               unsigned int *bytes_read)
14457 {
14458   struct comp_unit_head *cu_header = &cu->header;
14459   CORE_ADDR retval = 0;
14460
14461   if (cu_header->signed_addr_p)
14462     {
14463       switch (cu_header->addr_size)
14464         {
14465         case 2:
14466           retval = bfd_get_signed_16 (abfd, buf);
14467           break;
14468         case 4:
14469           retval = bfd_get_signed_32 (abfd, buf);
14470           break;
14471         case 8:
14472           retval = bfd_get_signed_64 (abfd, buf);
14473           break;
14474         default:
14475           internal_error (__FILE__, __LINE__,
14476                           _("read_address: bad switch, signed [in module %s]"),
14477                           bfd_get_filename (abfd));
14478         }
14479     }
14480   else
14481     {
14482       switch (cu_header->addr_size)
14483         {
14484         case 2:
14485           retval = bfd_get_16 (abfd, buf);
14486           break;
14487         case 4:
14488           retval = bfd_get_32 (abfd, buf);
14489           break;
14490         case 8:
14491           retval = bfd_get_64 (abfd, buf);
14492           break;
14493         default:
14494           internal_error (__FILE__, __LINE__,
14495                           _("read_address: bad switch, "
14496                             "unsigned [in module %s]"),
14497                           bfd_get_filename (abfd));
14498         }
14499     }
14500
14501   *bytes_read = cu_header->addr_size;
14502   return retval;
14503 }
14504
14505 /* Read the initial length from a section.  The (draft) DWARF 3
14506    specification allows the initial length to take up either 4 bytes
14507    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14508    bytes describe the length and all offsets will be 8 bytes in length
14509    instead of 4.
14510
14511    An older, non-standard 64-bit format is also handled by this
14512    function.  The older format in question stores the initial length
14513    as an 8-byte quantity without an escape value.  Lengths greater
14514    than 2^32 aren't very common which means that the initial 4 bytes
14515    is almost always zero.  Since a length value of zero doesn't make
14516    sense for the 32-bit format, this initial zero can be considered to
14517    be an escape value which indicates the presence of the older 64-bit
14518    format.  As written, the code can't detect (old format) lengths
14519    greater than 4GB.  If it becomes necessary to handle lengths
14520    somewhat larger than 4GB, we could allow other small values (such
14521    as the non-sensical values of 1, 2, and 3) to also be used as
14522    escape values indicating the presence of the old format.
14523
14524    The value returned via bytes_read should be used to increment the
14525    relevant pointer after calling read_initial_length().
14526
14527    [ Note:  read_initial_length() and read_offset() are based on the
14528      document entitled "DWARF Debugging Information Format", revision
14529      3, draft 8, dated November 19, 2001.  This document was obtained
14530      from:
14531
14532         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14533
14534      This document is only a draft and is subject to change.  (So beware.)
14535
14536      Details regarding the older, non-standard 64-bit format were
14537      determined empirically by examining 64-bit ELF files produced by
14538      the SGI toolchain on an IRIX 6.5 machine.
14539
14540      - Kevin, July 16, 2002
14541    ] */
14542
14543 static LONGEST
14544 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
14545 {
14546   LONGEST length = bfd_get_32 (abfd, buf);
14547
14548   if (length == 0xffffffff)
14549     {
14550       length = bfd_get_64 (abfd, buf + 4);
14551       *bytes_read = 12;
14552     }
14553   else if (length == 0)
14554     {
14555       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14556       length = bfd_get_64 (abfd, buf);
14557       *bytes_read = 8;
14558     }
14559   else
14560     {
14561       *bytes_read = 4;
14562     }
14563
14564   return length;
14565 }
14566
14567 /* Cover function for read_initial_length.
14568    Returns the length of the object at BUF, and stores the size of the
14569    initial length in *BYTES_READ and stores the size that offsets will be in
14570    *OFFSET_SIZE.
14571    If the initial length size is not equivalent to that specified in
14572    CU_HEADER then issue a complaint.
14573    This is useful when reading non-comp-unit headers.  */
14574
14575 static LONGEST
14576 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
14577                                         const struct comp_unit_head *cu_header,
14578                                         unsigned int *bytes_read,
14579                                         unsigned int *offset_size)
14580 {
14581   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14582
14583   gdb_assert (cu_header->initial_length_size == 4
14584               || cu_header->initial_length_size == 8
14585               || cu_header->initial_length_size == 12);
14586
14587   if (cu_header->initial_length_size != *bytes_read)
14588     complaint (&symfile_complaints,
14589                _("intermixed 32-bit and 64-bit DWARF sections"));
14590
14591   *offset_size = (*bytes_read == 4) ? 4 : 8;
14592   return length;
14593 }
14594
14595 /* Read an offset from the data stream.  The size of the offset is
14596    given by cu_header->offset_size.  */
14597
14598 static LONGEST
14599 read_offset (bfd *abfd, const gdb_byte *buf,
14600              const struct comp_unit_head *cu_header,
14601              unsigned int *bytes_read)
14602 {
14603   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14604
14605   *bytes_read = cu_header->offset_size;
14606   return offset;
14607 }
14608
14609 /* Read an offset from the data stream.  */
14610
14611 static LONGEST
14612 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
14613 {
14614   LONGEST retval = 0;
14615
14616   switch (offset_size)
14617     {
14618     case 4:
14619       retval = bfd_get_32 (abfd, buf);
14620       break;
14621     case 8:
14622       retval = bfd_get_64 (abfd, buf);
14623       break;
14624     default:
14625       internal_error (__FILE__, __LINE__,
14626                       _("read_offset_1: bad switch [in module %s]"),
14627                       bfd_get_filename (abfd));
14628     }
14629
14630   return retval;
14631 }
14632
14633 static const gdb_byte *
14634 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
14635 {
14636   /* If the size of a host char is 8 bits, we can return a pointer
14637      to the buffer, otherwise we have to copy the data to a buffer
14638      allocated on the temporary obstack.  */
14639   gdb_assert (HOST_CHAR_BIT == 8);
14640   return buf;
14641 }
14642
14643 static const char *
14644 read_direct_string (bfd *abfd, const gdb_byte *buf,
14645                     unsigned int *bytes_read_ptr)
14646 {
14647   /* If the size of a host char is 8 bits, we can return a pointer
14648      to the string, otherwise we have to copy the string to a buffer
14649      allocated on the temporary obstack.  */
14650   gdb_assert (HOST_CHAR_BIT == 8);
14651   if (*buf == '\0')
14652     {
14653       *bytes_read_ptr = 1;
14654       return NULL;
14655     }
14656   *bytes_read_ptr = strlen ((const char *) buf) + 1;
14657   return (const char *) buf;
14658 }
14659
14660 static const char *
14661 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14662 {
14663   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14664   if (dwarf2_per_objfile->str.buffer == NULL)
14665     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14666            bfd_get_filename (abfd));
14667   if (str_offset >= dwarf2_per_objfile->str.size)
14668     error (_("DW_FORM_strp pointing outside of "
14669              ".debug_str section [in module %s]"),
14670            bfd_get_filename (abfd));
14671   gdb_assert (HOST_CHAR_BIT == 8);
14672   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14673     return NULL;
14674   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
14675 }
14676
14677 /* Read a string at offset STR_OFFSET in the .debug_str section from
14678    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14679    the string consists of a single NUL byte, return NULL; otherwise
14680    return a pointer to the string.  */
14681
14682 static const char *
14683 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14684 {
14685   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14686
14687   if (dwz->str.buffer == NULL)
14688     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14689              "section [in module %s]"),
14690            bfd_get_filename (dwz->dwz_bfd));
14691   if (str_offset >= dwz->str.size)
14692     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14693              ".debug_str section [in module %s]"),
14694            bfd_get_filename (dwz->dwz_bfd));
14695   gdb_assert (HOST_CHAR_BIT == 8);
14696   if (dwz->str.buffer[str_offset] == '\0')
14697     return NULL;
14698   return (const char *) (dwz->str.buffer + str_offset);
14699 }
14700
14701 static const char *
14702 read_indirect_string (bfd *abfd, const gdb_byte *buf,
14703                       const struct comp_unit_head *cu_header,
14704                       unsigned int *bytes_read_ptr)
14705 {
14706   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14707
14708   return read_indirect_string_at_offset (abfd, str_offset);
14709 }
14710
14711 static ULONGEST
14712 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
14713                       unsigned int *bytes_read_ptr)
14714 {
14715   ULONGEST result;
14716   unsigned int num_read;
14717   int i, shift;
14718   unsigned char byte;
14719
14720   result = 0;
14721   shift = 0;
14722   num_read = 0;
14723   i = 0;
14724   while (1)
14725     {
14726       byte = bfd_get_8 (abfd, buf);
14727       buf++;
14728       num_read++;
14729       result |= ((ULONGEST) (byte & 127) << shift);
14730       if ((byte & 128) == 0)
14731         {
14732           break;
14733         }
14734       shift += 7;
14735     }
14736   *bytes_read_ptr = num_read;
14737   return result;
14738 }
14739
14740 static LONGEST
14741 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
14742                     unsigned int *bytes_read_ptr)
14743 {
14744   LONGEST result;
14745   int i, shift, num_read;
14746   unsigned char byte;
14747
14748   result = 0;
14749   shift = 0;
14750   num_read = 0;
14751   i = 0;
14752   while (1)
14753     {
14754       byte = bfd_get_8 (abfd, buf);
14755       buf++;
14756       num_read++;
14757       result |= ((LONGEST) (byte & 127) << shift);
14758       shift += 7;
14759       if ((byte & 128) == 0)
14760         {
14761           break;
14762         }
14763     }
14764   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14765     result |= -(((LONGEST) 1) << shift);
14766   *bytes_read_ptr = num_read;
14767   return result;
14768 }
14769
14770 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14771    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14772    ADDR_SIZE is the size of addresses from the CU header.  */
14773
14774 static CORE_ADDR
14775 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14776 {
14777   struct objfile *objfile = dwarf2_per_objfile->objfile;
14778   bfd *abfd = objfile->obfd;
14779   const gdb_byte *info_ptr;
14780
14781   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14782   if (dwarf2_per_objfile->addr.buffer == NULL)
14783     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14784            objfile->name);
14785   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14786     error (_("DW_FORM_addr_index pointing outside of "
14787              ".debug_addr section [in module %s]"),
14788            objfile->name);
14789   info_ptr = (dwarf2_per_objfile->addr.buffer
14790               + addr_base + addr_index * addr_size);
14791   if (addr_size == 4)
14792     return bfd_get_32 (abfd, info_ptr);
14793   else
14794     return bfd_get_64 (abfd, info_ptr);
14795 }
14796
14797 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14798
14799 static CORE_ADDR
14800 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14801 {
14802   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14803 }
14804
14805 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14806
14807 static CORE_ADDR
14808 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
14809                              unsigned int *bytes_read)
14810 {
14811   bfd *abfd = cu->objfile->obfd;
14812   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14813
14814   return read_addr_index (cu, addr_index);
14815 }
14816
14817 /* Data structure to pass results from dwarf2_read_addr_index_reader
14818    back to dwarf2_read_addr_index.  */
14819
14820 struct dwarf2_read_addr_index_data
14821 {
14822   ULONGEST addr_base;
14823   int addr_size;
14824 };
14825
14826 /* die_reader_func for dwarf2_read_addr_index.  */
14827
14828 static void
14829 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14830                                const gdb_byte *info_ptr,
14831                                struct die_info *comp_unit_die,
14832                                int has_children,
14833                                void *data)
14834 {
14835   struct dwarf2_cu *cu = reader->cu;
14836   struct dwarf2_read_addr_index_data *aidata =
14837     (struct dwarf2_read_addr_index_data *) data;
14838
14839   aidata->addr_base = cu->addr_base;
14840   aidata->addr_size = cu->header.addr_size;
14841 }
14842
14843 /* Given an index in .debug_addr, fetch the value.
14844    NOTE: This can be called during dwarf expression evaluation,
14845    long after the debug information has been read, and thus per_cu->cu
14846    may no longer exist.  */
14847
14848 CORE_ADDR
14849 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14850                         unsigned int addr_index)
14851 {
14852   struct objfile *objfile = per_cu->objfile;
14853   struct dwarf2_cu *cu = per_cu->cu;
14854   ULONGEST addr_base;
14855   int addr_size;
14856
14857   /* This is intended to be called from outside this file.  */
14858   dw2_setup (objfile);
14859
14860   /* We need addr_base and addr_size.
14861      If we don't have PER_CU->cu, we have to get it.
14862      Nasty, but the alternative is storing the needed info in PER_CU,
14863      which at this point doesn't seem justified: it's not clear how frequently
14864      it would get used and it would increase the size of every PER_CU.
14865      Entry points like dwarf2_per_cu_addr_size do a similar thing
14866      so we're not in uncharted territory here.
14867      Alas we need to be a bit more complicated as addr_base is contained
14868      in the DIE.
14869
14870      We don't need to read the entire CU(/TU).
14871      We just need the header and top level die.
14872
14873      IWBN to use the aging mechanism to let us lazily later discard the CU.
14874      For now we skip this optimization.  */
14875
14876   if (cu != NULL)
14877     {
14878       addr_base = cu->addr_base;
14879       addr_size = cu->header.addr_size;
14880     }
14881   else
14882     {
14883       struct dwarf2_read_addr_index_data aidata;
14884
14885       /* Note: We can't use init_cutu_and_read_dies_simple here,
14886          we need addr_base.  */
14887       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14888                                dwarf2_read_addr_index_reader, &aidata);
14889       addr_base = aidata.addr_base;
14890       addr_size = aidata.addr_size;
14891     }
14892
14893   return read_addr_index_1 (addr_index, addr_base, addr_size);
14894 }
14895
14896 /* Given a DW_AT_str_index, fetch the string.  */
14897
14898 static const char *
14899 read_str_index (const struct die_reader_specs *reader,
14900                 struct dwarf2_cu *cu, ULONGEST str_index)
14901 {
14902   struct objfile *objfile = dwarf2_per_objfile->objfile;
14903   const char *dwo_name = objfile->name;
14904   bfd *abfd = objfile->obfd;
14905   struct dwo_sections *sections = &reader->dwo_file->sections;
14906   const gdb_byte *info_ptr;
14907   ULONGEST str_offset;
14908
14909   dwarf2_read_section (objfile, &sections->str);
14910   dwarf2_read_section (objfile, &sections->str_offsets);
14911   if (sections->str.buffer == NULL)
14912     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14913              " in CU at offset 0x%lx [in module %s]"),
14914            (long) cu->header.offset.sect_off, dwo_name);
14915   if (sections->str_offsets.buffer == NULL)
14916     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14917              " in CU at offset 0x%lx [in module %s]"),
14918            (long) cu->header.offset.sect_off, dwo_name);
14919   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14920     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14921              " section in CU at offset 0x%lx [in module %s]"),
14922            (long) cu->header.offset.sect_off, dwo_name);
14923   info_ptr = (sections->str_offsets.buffer
14924               + str_index * cu->header.offset_size);
14925   if (cu->header.offset_size == 4)
14926     str_offset = bfd_get_32 (abfd, info_ptr);
14927   else
14928     str_offset = bfd_get_64 (abfd, info_ptr);
14929   if (str_offset >= sections->str.size)
14930     error (_("Offset from DW_FORM_str_index pointing outside of"
14931              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14932            (long) cu->header.offset.sect_off, dwo_name);
14933   return (const char *) (sections->str.buffer + str_offset);
14934 }
14935
14936 /* Return the length of an LEB128 number in BUF.  */
14937
14938 static int
14939 leb128_size (const gdb_byte *buf)
14940 {
14941   const gdb_byte *begin = buf;
14942   gdb_byte byte;
14943
14944   while (1)
14945     {
14946       byte = *buf++;
14947       if ((byte & 128) == 0)
14948         return buf - begin;
14949     }
14950 }
14951
14952 static void
14953 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14954 {
14955   switch (lang)
14956     {
14957     case DW_LANG_C89:
14958     case DW_LANG_C99:
14959     case DW_LANG_C:
14960       cu->language = language_c;
14961       break;
14962     case DW_LANG_C_plus_plus:
14963       cu->language = language_cplus;
14964       break;
14965     case DW_LANG_D:
14966       cu->language = language_d;
14967       break;
14968     case DW_LANG_Fortran77:
14969     case DW_LANG_Fortran90:
14970     case DW_LANG_Fortran95:
14971       cu->language = language_fortran;
14972       break;
14973     case DW_LANG_Go:
14974       cu->language = language_go;
14975       break;
14976     case DW_LANG_Mips_Assembler:
14977       cu->language = language_asm;
14978       break;
14979     case DW_LANG_Java:
14980       cu->language = language_java;
14981       break;
14982     case DW_LANG_Ada83:
14983     case DW_LANG_Ada95:
14984       cu->language = language_ada;
14985       break;
14986     case DW_LANG_Modula2:
14987       cu->language = language_m2;
14988       break;
14989     case DW_LANG_Pascal83:
14990       cu->language = language_pascal;
14991       break;
14992     case DW_LANG_ObjC:
14993       cu->language = language_objc;
14994       break;
14995     case DW_LANG_Cobol74:
14996     case DW_LANG_Cobol85:
14997     default:
14998       cu->language = language_minimal;
14999       break;
15000     }
15001   cu->language_defn = language_def (cu->language);
15002 }
15003
15004 /* Return the named attribute or NULL if not there.  */
15005
15006 static struct attribute *
15007 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
15008 {
15009   for (;;)
15010     {
15011       unsigned int i;
15012       struct attribute *spec = NULL;
15013
15014       for (i = 0; i < die->num_attrs; ++i)
15015         {
15016           if (die->attrs[i].name == name)
15017             return &die->attrs[i];
15018           if (die->attrs[i].name == DW_AT_specification
15019               || die->attrs[i].name == DW_AT_abstract_origin)
15020             spec = &die->attrs[i];
15021         }
15022
15023       if (!spec)
15024         break;
15025
15026       die = follow_die_ref (die, spec, &cu);
15027     }
15028
15029   return NULL;
15030 }
15031
15032 /* Return the named attribute or NULL if not there,
15033    but do not follow DW_AT_specification, etc.
15034    This is for use in contexts where we're reading .debug_types dies.
15035    Following DW_AT_specification, DW_AT_abstract_origin will take us
15036    back up the chain, and we want to go down.  */
15037
15038 static struct attribute *
15039 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
15040 {
15041   unsigned int i;
15042
15043   for (i = 0; i < die->num_attrs; ++i)
15044     if (die->attrs[i].name == name)
15045       return &die->attrs[i];
15046
15047   return NULL;
15048 }
15049
15050 /* Return non-zero iff the attribute NAME is defined for the given DIE,
15051    and holds a non-zero value.  This function should only be used for
15052    DW_FORM_flag or DW_FORM_flag_present attributes.  */
15053
15054 static int
15055 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
15056 {
15057   struct attribute *attr = dwarf2_attr (die, name, cu);
15058
15059   return (attr && DW_UNSND (attr));
15060 }
15061
15062 static int
15063 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
15064 {
15065   /* A DIE is a declaration if it has a DW_AT_declaration attribute
15066      which value is non-zero.  However, we have to be careful with
15067      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
15068      (via dwarf2_flag_true_p) follows this attribute.  So we may
15069      end up accidently finding a declaration attribute that belongs
15070      to a different DIE referenced by the specification attribute,
15071      even though the given DIE does not have a declaration attribute.  */
15072   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
15073           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
15074 }
15075
15076 /* Return the die giving the specification for DIE, if there is
15077    one.  *SPEC_CU is the CU containing DIE on input, and the CU
15078    containing the return value on output.  If there is no
15079    specification, but there is an abstract origin, that is
15080    returned.  */
15081
15082 static struct die_info *
15083 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
15084 {
15085   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
15086                                              *spec_cu);
15087
15088   if (spec_attr == NULL)
15089     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
15090
15091   if (spec_attr == NULL)
15092     return NULL;
15093   else
15094     return follow_die_ref (die, spec_attr, spec_cu);
15095 }
15096
15097 /* Free the line_header structure *LH, and any arrays and strings it
15098    refers to.
15099    NOTE: This is also used as a "cleanup" function.  */
15100
15101 static void
15102 free_line_header (struct line_header *lh)
15103 {
15104   if (lh->standard_opcode_lengths)
15105     xfree (lh->standard_opcode_lengths);
15106
15107   /* Remember that all the lh->file_names[i].name pointers are
15108      pointers into debug_line_buffer, and don't need to be freed.  */
15109   if (lh->file_names)
15110     xfree (lh->file_names);
15111
15112   /* Similarly for the include directory names.  */
15113   if (lh->include_dirs)
15114     xfree (lh->include_dirs);
15115
15116   xfree (lh);
15117 }
15118
15119 /* Add an entry to LH's include directory table.  */
15120
15121 static void
15122 add_include_dir (struct line_header *lh, const char *include_dir)
15123 {
15124   /* Grow the array if necessary.  */
15125   if (lh->include_dirs_size == 0)
15126     {
15127       lh->include_dirs_size = 1; /* for testing */
15128       lh->include_dirs = xmalloc (lh->include_dirs_size
15129                                   * sizeof (*lh->include_dirs));
15130     }
15131   else if (lh->num_include_dirs >= lh->include_dirs_size)
15132     {
15133       lh->include_dirs_size *= 2;
15134       lh->include_dirs = xrealloc (lh->include_dirs,
15135                                    (lh->include_dirs_size
15136                                     * sizeof (*lh->include_dirs)));
15137     }
15138
15139   lh->include_dirs[lh->num_include_dirs++] = include_dir;
15140 }
15141
15142 /* Add an entry to LH's file name table.  */
15143
15144 static void
15145 add_file_name (struct line_header *lh,
15146                const char *name,
15147                unsigned int dir_index,
15148                unsigned int mod_time,
15149                unsigned int length)
15150 {
15151   struct file_entry *fe;
15152
15153   /* Grow the array if necessary.  */
15154   if (lh->file_names_size == 0)
15155     {
15156       lh->file_names_size = 1; /* for testing */
15157       lh->file_names = xmalloc (lh->file_names_size
15158                                 * sizeof (*lh->file_names));
15159     }
15160   else if (lh->num_file_names >= lh->file_names_size)
15161     {
15162       lh->file_names_size *= 2;
15163       lh->file_names = xrealloc (lh->file_names,
15164                                  (lh->file_names_size
15165                                   * sizeof (*lh->file_names)));
15166     }
15167
15168   fe = &lh->file_names[lh->num_file_names++];
15169   fe->name = name;
15170   fe->dir_index = dir_index;
15171   fe->mod_time = mod_time;
15172   fe->length = length;
15173   fe->included_p = 0;
15174   fe->symtab = NULL;
15175 }
15176
15177 /* A convenience function to find the proper .debug_line section for a
15178    CU.  */
15179
15180 static struct dwarf2_section_info *
15181 get_debug_line_section (struct dwarf2_cu *cu)
15182 {
15183   struct dwarf2_section_info *section;
15184
15185   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15186      DWO file.  */
15187   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15188     section = &cu->dwo_unit->dwo_file->sections.line;
15189   else if (cu->per_cu->is_dwz)
15190     {
15191       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15192
15193       section = &dwz->line;
15194     }
15195   else
15196     section = &dwarf2_per_objfile->line;
15197
15198   return section;
15199 }
15200
15201 /* Read the statement program header starting at OFFSET in
15202    .debug_line, or .debug_line.dwo.  Return a pointer
15203    to a struct line_header, allocated using xmalloc.
15204
15205    NOTE: the strings in the include directory and file name tables of
15206    the returned object point into the dwarf line section buffer,
15207    and must not be freed.  */
15208
15209 static struct line_header *
15210 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15211 {
15212   struct cleanup *back_to;
15213   struct line_header *lh;
15214   const gdb_byte *line_ptr;
15215   unsigned int bytes_read, offset_size;
15216   int i;
15217   const char *cur_dir, *cur_file;
15218   struct dwarf2_section_info *section;
15219   bfd *abfd;
15220
15221   section = get_debug_line_section (cu);
15222   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15223   if (section->buffer == NULL)
15224     {
15225       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15226         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15227       else
15228         complaint (&symfile_complaints, _("missing .debug_line section"));
15229       return 0;
15230     }
15231
15232   /* We can't do this until we know the section is non-empty.
15233      Only then do we know we have such a section.  */
15234   abfd = section->asection->owner;
15235
15236   /* Make sure that at least there's room for the total_length field.
15237      That could be 12 bytes long, but we're just going to fudge that.  */
15238   if (offset + 4 >= section->size)
15239     {
15240       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15241       return 0;
15242     }
15243
15244   lh = xmalloc (sizeof (*lh));
15245   memset (lh, 0, sizeof (*lh));
15246   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15247                           (void *) lh);
15248
15249   line_ptr = section->buffer + offset;
15250
15251   /* Read in the header.  */
15252   lh->total_length =
15253     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15254                                             &bytes_read, &offset_size);
15255   line_ptr += bytes_read;
15256   if (line_ptr + lh->total_length > (section->buffer + section->size))
15257     {
15258       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15259       return 0;
15260     }
15261   lh->statement_program_end = line_ptr + lh->total_length;
15262   lh->version = read_2_bytes (abfd, line_ptr);
15263   line_ptr += 2;
15264   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15265   line_ptr += offset_size;
15266   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15267   line_ptr += 1;
15268   if (lh->version >= 4)
15269     {
15270       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15271       line_ptr += 1;
15272     }
15273   else
15274     lh->maximum_ops_per_instruction = 1;
15275
15276   if (lh->maximum_ops_per_instruction == 0)
15277     {
15278       lh->maximum_ops_per_instruction = 1;
15279       complaint (&symfile_complaints,
15280                  _("invalid maximum_ops_per_instruction "
15281                    "in `.debug_line' section"));
15282     }
15283
15284   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15285   line_ptr += 1;
15286   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15287   line_ptr += 1;
15288   lh->line_range = read_1_byte (abfd, line_ptr);
15289   line_ptr += 1;
15290   lh->opcode_base = read_1_byte (abfd, line_ptr);
15291   line_ptr += 1;
15292   lh->standard_opcode_lengths
15293     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15294
15295   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15296   for (i = 1; i < lh->opcode_base; ++i)
15297     {
15298       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15299       line_ptr += 1;
15300     }
15301
15302   /* Read directory table.  */
15303   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15304     {
15305       line_ptr += bytes_read;
15306       add_include_dir (lh, cur_dir);
15307     }
15308   line_ptr += bytes_read;
15309
15310   /* Read file name table.  */
15311   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15312     {
15313       unsigned int dir_index, mod_time, length;
15314
15315       line_ptr += bytes_read;
15316       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15317       line_ptr += bytes_read;
15318       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15319       line_ptr += bytes_read;
15320       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15321       line_ptr += bytes_read;
15322
15323       add_file_name (lh, cur_file, dir_index, mod_time, length);
15324     }
15325   line_ptr += bytes_read;
15326   lh->statement_program_start = line_ptr;
15327
15328   if (line_ptr > (section->buffer + section->size))
15329     complaint (&symfile_complaints,
15330                _("line number info header doesn't "
15331                  "fit in `.debug_line' section"));
15332
15333   discard_cleanups (back_to);
15334   return lh;
15335 }
15336
15337 /* Subroutine of dwarf_decode_lines to simplify it.
15338    Return the file name of the psymtab for included file FILE_INDEX
15339    in line header LH of PST.
15340    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15341    If space for the result is malloc'd, it will be freed by a cleanup.
15342    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15343
15344    The function creates dangling cleanup registration.  */
15345
15346 static const char *
15347 psymtab_include_file_name (const struct line_header *lh, int file_index,
15348                            const struct partial_symtab *pst,
15349                            const char *comp_dir)
15350 {
15351   const struct file_entry fe = lh->file_names [file_index];
15352   const char *include_name = fe.name;
15353   const char *include_name_to_compare = include_name;
15354   const char *dir_name = NULL;
15355   const char *pst_filename;
15356   char *copied_name = NULL;
15357   int file_is_pst;
15358
15359   if (fe.dir_index)
15360     dir_name = lh->include_dirs[fe.dir_index - 1];
15361
15362   if (!IS_ABSOLUTE_PATH (include_name)
15363       && (dir_name != NULL || comp_dir != NULL))
15364     {
15365       /* Avoid creating a duplicate psymtab for PST.
15366          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15367          Before we do the comparison, however, we need to account
15368          for DIR_NAME and COMP_DIR.
15369          First prepend dir_name (if non-NULL).  If we still don't
15370          have an absolute path prepend comp_dir (if non-NULL).
15371          However, the directory we record in the include-file's
15372          psymtab does not contain COMP_DIR (to match the
15373          corresponding symtab(s)).
15374
15375          Example:
15376
15377          bash$ cd /tmp
15378          bash$ gcc -g ./hello.c
15379          include_name = "hello.c"
15380          dir_name = "."
15381          DW_AT_comp_dir = comp_dir = "/tmp"
15382          DW_AT_name = "./hello.c"  */
15383
15384       if (dir_name != NULL)
15385         {
15386           char *tem = concat (dir_name, SLASH_STRING,
15387                               include_name, (char *)NULL);
15388
15389           make_cleanup (xfree, tem);
15390           include_name = tem;
15391           include_name_to_compare = include_name;
15392         }
15393       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15394         {
15395           char *tem = concat (comp_dir, SLASH_STRING,
15396                               include_name, (char *)NULL);
15397
15398           make_cleanup (xfree, tem);
15399           include_name_to_compare = tem;
15400         }
15401     }
15402
15403   pst_filename = pst->filename;
15404   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15405     {
15406       copied_name = concat (pst->dirname, SLASH_STRING,
15407                             pst_filename, (char *)NULL);
15408       pst_filename = copied_name;
15409     }
15410
15411   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15412
15413   if (copied_name != NULL)
15414     xfree (copied_name);
15415
15416   if (file_is_pst)
15417     return NULL;
15418   return include_name;
15419 }
15420
15421 /* Ignore this record_line request.  */
15422
15423 static void
15424 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15425 {
15426   return;
15427 }
15428
15429 /* Subroutine of dwarf_decode_lines to simplify it.
15430    Process the line number information in LH.  */
15431
15432 static void
15433 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15434                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15435 {
15436   const gdb_byte *line_ptr, *extended_end;
15437   const gdb_byte *line_end;
15438   unsigned int bytes_read, extended_len;
15439   unsigned char op_code, extended_op, adj_opcode;
15440   CORE_ADDR baseaddr;
15441   struct objfile *objfile = cu->objfile;
15442   bfd *abfd = objfile->obfd;
15443   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15444   const int decode_for_pst_p = (pst != NULL);
15445   struct subfile *last_subfile = NULL;
15446   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15447     = record_line;
15448
15449   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15450
15451   line_ptr = lh->statement_program_start;
15452   line_end = lh->statement_program_end;
15453
15454   /* Read the statement sequences until there's nothing left.  */
15455   while (line_ptr < line_end)
15456     {
15457       /* state machine registers  */
15458       CORE_ADDR address = 0;
15459       unsigned int file = 1;
15460       unsigned int line = 1;
15461       unsigned int column = 0;
15462       int is_stmt = lh->default_is_stmt;
15463       int basic_block = 0;
15464       int end_sequence = 0;
15465       CORE_ADDR addr;
15466       unsigned char op_index = 0;
15467
15468       if (!decode_for_pst_p && lh->num_file_names >= file)
15469         {
15470           /* Start a subfile for the current file of the state machine.  */
15471           /* lh->include_dirs and lh->file_names are 0-based, but the
15472              directory and file name numbers in the statement program
15473              are 1-based.  */
15474           struct file_entry *fe = &lh->file_names[file - 1];
15475           const char *dir = NULL;
15476
15477           if (fe->dir_index)
15478             dir = lh->include_dirs[fe->dir_index - 1];
15479
15480           dwarf2_start_subfile (fe->name, dir, comp_dir);
15481         }
15482
15483       /* Decode the table.  */
15484       while (!end_sequence)
15485         {
15486           op_code = read_1_byte (abfd, line_ptr);
15487           line_ptr += 1;
15488           if (line_ptr > line_end)
15489             {
15490               dwarf2_debug_line_missing_end_sequence_complaint ();
15491               break;
15492             }
15493
15494           if (op_code >= lh->opcode_base)
15495             {
15496               /* Special operand.  */
15497               adj_opcode = op_code - lh->opcode_base;
15498               address += (((op_index + (adj_opcode / lh->line_range))
15499                            / lh->maximum_ops_per_instruction)
15500                           * lh->minimum_instruction_length);
15501               op_index = ((op_index + (adj_opcode / lh->line_range))
15502                           % lh->maximum_ops_per_instruction);
15503               line += lh->line_base + (adj_opcode % lh->line_range);
15504               if (lh->num_file_names < file || file == 0)
15505                 dwarf2_debug_line_missing_file_complaint ();
15506               /* For now we ignore lines not starting on an
15507                  instruction boundary.  */
15508               else if (op_index == 0)
15509                 {
15510                   lh->file_names[file - 1].included_p = 1;
15511                   if (!decode_for_pst_p && is_stmt)
15512                     {
15513                       if (last_subfile != current_subfile)
15514                         {
15515                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15516                           if (last_subfile)
15517                             (*p_record_line) (last_subfile, 0, addr);
15518                           last_subfile = current_subfile;
15519                         }
15520                       /* Append row to matrix using current values.  */
15521                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15522                       (*p_record_line) (current_subfile, line, addr);
15523                     }
15524                 }
15525               basic_block = 0;
15526             }
15527           else switch (op_code)
15528             {
15529             case DW_LNS_extended_op:
15530               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15531                                                    &bytes_read);
15532               line_ptr += bytes_read;
15533               extended_end = line_ptr + extended_len;
15534               extended_op = read_1_byte (abfd, line_ptr);
15535               line_ptr += 1;
15536               switch (extended_op)
15537                 {
15538                 case DW_LNE_end_sequence:
15539                   p_record_line = record_line;
15540                   end_sequence = 1;
15541                   break;
15542                 case DW_LNE_set_address:
15543                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15544
15545                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15546                     {
15547                       /* This line table is for a function which has been
15548                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15549
15550                       long line_offset
15551                         = line_ptr - get_debug_line_section (cu)->buffer;
15552
15553                       complaint (&symfile_complaints,
15554                                  _(".debug_line address at offset 0x%lx is 0 "
15555                                    "[in module %s]"),
15556                                  line_offset, objfile->name);
15557                       p_record_line = noop_record_line;
15558                     }
15559
15560                   op_index = 0;
15561                   line_ptr += bytes_read;
15562                   address += baseaddr;
15563                   break;
15564                 case DW_LNE_define_file:
15565                   {
15566                     const char *cur_file;
15567                     unsigned int dir_index, mod_time, length;
15568
15569                     cur_file = read_direct_string (abfd, line_ptr,
15570                                                    &bytes_read);
15571                     line_ptr += bytes_read;
15572                     dir_index =
15573                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15574                     line_ptr += bytes_read;
15575                     mod_time =
15576                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15577                     line_ptr += bytes_read;
15578                     length =
15579                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15580                     line_ptr += bytes_read;
15581                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15582                   }
15583                   break;
15584                 case DW_LNE_set_discriminator:
15585                   /* The discriminator is not interesting to the debugger;
15586                      just ignore it.  */
15587                   line_ptr = extended_end;
15588                   break;
15589                 default:
15590                   complaint (&symfile_complaints,
15591                              _("mangled .debug_line section"));
15592                   return;
15593                 }
15594               /* Make sure that we parsed the extended op correctly.  If e.g.
15595                  we expected a different address size than the producer used,
15596                  we may have read the wrong number of bytes.  */
15597               if (line_ptr != extended_end)
15598                 {
15599                   complaint (&symfile_complaints,
15600                              _("mangled .debug_line section"));
15601                   return;
15602                 }
15603               break;
15604             case DW_LNS_copy:
15605               if (lh->num_file_names < file || file == 0)
15606                 dwarf2_debug_line_missing_file_complaint ();
15607               else
15608                 {
15609                   lh->file_names[file - 1].included_p = 1;
15610                   if (!decode_for_pst_p && is_stmt)
15611                     {
15612                       if (last_subfile != current_subfile)
15613                         {
15614                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15615                           if (last_subfile)
15616                             (*p_record_line) (last_subfile, 0, addr);
15617                           last_subfile = current_subfile;
15618                         }
15619                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15620                       (*p_record_line) (current_subfile, line, addr);
15621                     }
15622                 }
15623               basic_block = 0;
15624               break;
15625             case DW_LNS_advance_pc:
15626               {
15627                 CORE_ADDR adjust
15628                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15629
15630                 address += (((op_index + adjust)
15631                              / lh->maximum_ops_per_instruction)
15632                             * lh->minimum_instruction_length);
15633                 op_index = ((op_index + adjust)
15634                             % lh->maximum_ops_per_instruction);
15635                 line_ptr += bytes_read;
15636               }
15637               break;
15638             case DW_LNS_advance_line:
15639               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15640               line_ptr += bytes_read;
15641               break;
15642             case DW_LNS_set_file:
15643               {
15644                 /* The arrays lh->include_dirs and lh->file_names are
15645                    0-based, but the directory and file name numbers in
15646                    the statement program are 1-based.  */
15647                 struct file_entry *fe;
15648                 const char *dir = NULL;
15649
15650                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15651                 line_ptr += bytes_read;
15652                 if (lh->num_file_names < file || file == 0)
15653                   dwarf2_debug_line_missing_file_complaint ();
15654                 else
15655                   {
15656                     fe = &lh->file_names[file - 1];
15657                     if (fe->dir_index)
15658                       dir = lh->include_dirs[fe->dir_index - 1];
15659                     if (!decode_for_pst_p)
15660                       {
15661                         last_subfile = current_subfile;
15662                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15663                       }
15664                   }
15665               }
15666               break;
15667             case DW_LNS_set_column:
15668               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15669               line_ptr += bytes_read;
15670               break;
15671             case DW_LNS_negate_stmt:
15672               is_stmt = (!is_stmt);
15673               break;
15674             case DW_LNS_set_basic_block:
15675               basic_block = 1;
15676               break;
15677             /* Add to the address register of the state machine the
15678                address increment value corresponding to special opcode
15679                255.  I.e., this value is scaled by the minimum
15680                instruction length since special opcode 255 would have
15681                scaled the increment.  */
15682             case DW_LNS_const_add_pc:
15683               {
15684                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15685
15686                 address += (((op_index + adjust)
15687                              / lh->maximum_ops_per_instruction)
15688                             * lh->minimum_instruction_length);
15689                 op_index = ((op_index + adjust)
15690                             % lh->maximum_ops_per_instruction);
15691               }
15692               break;
15693             case DW_LNS_fixed_advance_pc:
15694               address += read_2_bytes (abfd, line_ptr);
15695               op_index = 0;
15696               line_ptr += 2;
15697               break;
15698             default:
15699               {
15700                 /* Unknown standard opcode, ignore it.  */
15701                 int i;
15702
15703                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15704                   {
15705                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15706                     line_ptr += bytes_read;
15707                   }
15708               }
15709             }
15710         }
15711       if (lh->num_file_names < file || file == 0)
15712         dwarf2_debug_line_missing_file_complaint ();
15713       else
15714         {
15715           lh->file_names[file - 1].included_p = 1;
15716           if (!decode_for_pst_p)
15717             {
15718               addr = gdbarch_addr_bits_remove (gdbarch, address);
15719               (*p_record_line) (current_subfile, 0, addr);
15720             }
15721         }
15722     }
15723 }
15724
15725 /* Decode the Line Number Program (LNP) for the given line_header
15726    structure and CU.  The actual information extracted and the type
15727    of structures created from the LNP depends on the value of PST.
15728
15729    1. If PST is NULL, then this procedure uses the data from the program
15730       to create all necessary symbol tables, and their linetables.
15731
15732    2. If PST is not NULL, this procedure reads the program to determine
15733       the list of files included by the unit represented by PST, and
15734       builds all the associated partial symbol tables.
15735
15736    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15737    It is used for relative paths in the line table.
15738    NOTE: When processing partial symtabs (pst != NULL),
15739    comp_dir == pst->dirname.
15740
15741    NOTE: It is important that psymtabs have the same file name (via strcmp)
15742    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15743    symtab we don't use it in the name of the psymtabs we create.
15744    E.g. expand_line_sal requires this when finding psymtabs to expand.
15745    A good testcase for this is mb-inline.exp.  */
15746
15747 static void
15748 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15749                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15750                     int want_line_info)
15751 {
15752   struct objfile *objfile = cu->objfile;
15753   const int decode_for_pst_p = (pst != NULL);
15754   struct subfile *first_subfile = current_subfile;
15755
15756   if (want_line_info)
15757     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15758
15759   if (decode_for_pst_p)
15760     {
15761       int file_index;
15762
15763       /* Now that we're done scanning the Line Header Program, we can
15764          create the psymtab of each included file.  */
15765       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15766         if (lh->file_names[file_index].included_p == 1)
15767           {
15768             const char *include_name =
15769               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15770             if (include_name != NULL)
15771               dwarf2_create_include_psymtab (include_name, pst, objfile);
15772           }
15773     }
15774   else
15775     {
15776       /* Make sure a symtab is created for every file, even files
15777          which contain only variables (i.e. no code with associated
15778          line numbers).  */
15779       int i;
15780
15781       for (i = 0; i < lh->num_file_names; i++)
15782         {
15783           const char *dir = NULL;
15784           struct file_entry *fe;
15785
15786           fe = &lh->file_names[i];
15787           if (fe->dir_index)
15788             dir = lh->include_dirs[fe->dir_index - 1];
15789           dwarf2_start_subfile (fe->name, dir, comp_dir);
15790
15791           /* Skip the main file; we don't need it, and it must be
15792              allocated last, so that it will show up before the
15793              non-primary symtabs in the objfile's symtab list.  */
15794           if (current_subfile == first_subfile)
15795             continue;
15796
15797           if (current_subfile->symtab == NULL)
15798             current_subfile->symtab = allocate_symtab (current_subfile->name,
15799                                                        objfile);
15800           fe->symtab = current_subfile->symtab;
15801         }
15802     }
15803 }
15804
15805 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15806    DIRNAME the name of the source directory which contains FILENAME
15807    or NULL if not known.  COMP_DIR is the compilation directory for the
15808    linetable's compilation unit or NULL if not known.
15809    This routine tries to keep line numbers from identical absolute and
15810    relative file names in a common subfile.
15811
15812    Using the `list' example from the GDB testsuite, which resides in
15813    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15814    of /srcdir/list0.c yields the following debugging information for list0.c:
15815
15816    DW_AT_name:          /srcdir/list0.c
15817    DW_AT_comp_dir:              /compdir
15818    files.files[0].name: list0.h
15819    files.files[0].dir:  /srcdir
15820    files.files[1].name: list0.c
15821    files.files[1].dir:  /srcdir
15822
15823    The line number information for list0.c has to end up in a single
15824    subfile, so that `break /srcdir/list0.c:1' works as expected.
15825    start_subfile will ensure that this happens provided that we pass the
15826    concatenation of files.files[1].dir and files.files[1].name as the
15827    subfile's name.  */
15828
15829 static void
15830 dwarf2_start_subfile (const char *filename, const char *dirname,
15831                       const char *comp_dir)
15832 {
15833   char *copy = NULL;
15834
15835   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15836      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15837      second argument to start_subfile.  To be consistent, we do the
15838      same here.  In order not to lose the line information directory,
15839      we concatenate it to the filename when it makes sense.
15840      Note that the Dwarf3 standard says (speaking of filenames in line
15841      information): ``The directory index is ignored for file names
15842      that represent full path names''.  Thus ignoring dirname in the
15843      `else' branch below isn't an issue.  */
15844
15845   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15846     {
15847       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15848       filename = copy;
15849     }
15850
15851   start_subfile (filename, comp_dir);
15852
15853   if (copy != NULL)
15854     xfree (copy);
15855 }
15856
15857 /* Start a symtab for DWARF.
15858    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15859
15860 static void
15861 dwarf2_start_symtab (struct dwarf2_cu *cu,
15862                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15863 {
15864   start_symtab (name, comp_dir, low_pc);
15865   record_debugformat ("DWARF 2");
15866   record_producer (cu->producer);
15867
15868   /* We assume that we're processing GCC output.  */
15869   processing_gcc_compilation = 2;
15870
15871   cu->processing_has_namespace_info = 0;
15872 }
15873
15874 static void
15875 var_decode_location (struct attribute *attr, struct symbol *sym,
15876                      struct dwarf2_cu *cu)
15877 {
15878   struct objfile *objfile = cu->objfile;
15879   struct comp_unit_head *cu_header = &cu->header;
15880
15881   /* NOTE drow/2003-01-30: There used to be a comment and some special
15882      code here to turn a symbol with DW_AT_external and a
15883      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15884      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15885      with some versions of binutils) where shared libraries could have
15886      relocations against symbols in their debug information - the
15887      minimal symbol would have the right address, but the debug info
15888      would not.  It's no longer necessary, because we will explicitly
15889      apply relocations when we read in the debug information now.  */
15890
15891   /* A DW_AT_location attribute with no contents indicates that a
15892      variable has been optimized away.  */
15893   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15894     {
15895       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15896       return;
15897     }
15898
15899   /* Handle one degenerate form of location expression specially, to
15900      preserve GDB's previous behavior when section offsets are
15901      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15902      then mark this symbol as LOC_STATIC.  */
15903
15904   if (attr_form_is_block (attr)
15905       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15906            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15907           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15908               && (DW_BLOCK (attr)->size
15909                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15910     {
15911       unsigned int dummy;
15912
15913       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15914         SYMBOL_VALUE_ADDRESS (sym) =
15915           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15916       else
15917         SYMBOL_VALUE_ADDRESS (sym) =
15918           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15919       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
15920       fixup_symbol_section (sym, objfile);
15921       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15922                                               SYMBOL_SECTION (sym));
15923       return;
15924     }
15925
15926   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15927      expression evaluator, and use LOC_COMPUTED only when necessary
15928      (i.e. when the value of a register or memory location is
15929      referenced, or a thread-local block, etc.).  Then again, it might
15930      not be worthwhile.  I'm assuming that it isn't unless performance
15931      or memory numbers show me otherwise.  */
15932
15933   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
15934
15935   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
15936     cu->has_loclist = 1;
15937 }
15938
15939 /* Given a pointer to a DWARF information entry, figure out if we need
15940    to make a symbol table entry for it, and if so, create a new entry
15941    and return a pointer to it.
15942    If TYPE is NULL, determine symbol type from the die, otherwise
15943    used the passed type.
15944    If SPACE is not NULL, use it to hold the new symbol.  If it is
15945    NULL, allocate a new symbol on the objfile's obstack.  */
15946
15947 static struct symbol *
15948 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15949                  struct symbol *space)
15950 {
15951   struct objfile *objfile = cu->objfile;
15952   struct symbol *sym = NULL;
15953   const char *name;
15954   struct attribute *attr = NULL;
15955   struct attribute *attr2 = NULL;
15956   CORE_ADDR baseaddr;
15957   struct pending **list_to_add = NULL;
15958
15959   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15960
15961   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15962
15963   name = dwarf2_name (die, cu);
15964   if (name)
15965     {
15966       const char *linkagename;
15967       int suppress_add = 0;
15968
15969       if (space)
15970         sym = space;
15971       else
15972         sym = allocate_symbol (objfile);
15973       OBJSTAT (objfile, n_syms++);
15974
15975       /* Cache this symbol's name and the name's demangled form (if any).  */
15976       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
15977       linkagename = dwarf2_physname (name, die, cu);
15978       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15979
15980       /* Fortran does not have mangling standard and the mangling does differ
15981          between gfortran, iFort etc.  */
15982       if (cu->language == language_fortran
15983           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15984         symbol_set_demangled_name (&(sym->ginfo),
15985                                    dwarf2_full_name (name, die, cu),
15986                                    NULL);
15987
15988       /* Default assumptions.
15989          Use the passed type or decode it from the die.  */
15990       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15991       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15992       if (type != NULL)
15993         SYMBOL_TYPE (sym) = type;
15994       else
15995         SYMBOL_TYPE (sym) = die_type (die, cu);
15996       attr = dwarf2_attr (die,
15997                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15998                           cu);
15999       if (attr)
16000         {
16001           SYMBOL_LINE (sym) = DW_UNSND (attr);
16002         }
16003
16004       attr = dwarf2_attr (die,
16005                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
16006                           cu);
16007       if (attr)
16008         {
16009           int file_index = DW_UNSND (attr);
16010
16011           if (cu->line_header == NULL
16012               || file_index > cu->line_header->num_file_names)
16013             complaint (&symfile_complaints,
16014                        _("file index out of range"));
16015           else if (file_index > 0)
16016             {
16017               struct file_entry *fe;
16018
16019               fe = &cu->line_header->file_names[file_index - 1];
16020               SYMBOL_SYMTAB (sym) = fe->symtab;
16021             }
16022         }
16023
16024       switch (die->tag)
16025         {
16026         case DW_TAG_label:
16027           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
16028           if (attr)
16029             {
16030               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
16031             }
16032           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
16033           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
16034           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
16035           add_symbol_to_list (sym, cu->list_in_scope);
16036           break;
16037         case DW_TAG_subprogram:
16038           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16039              finish_block.  */
16040           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16041           attr2 = dwarf2_attr (die, DW_AT_external, cu);
16042           if ((attr2 && (DW_UNSND (attr2) != 0))
16043               || cu->language == language_ada)
16044             {
16045               /* Subprograms marked external are stored as a global symbol.
16046                  Ada subprograms, whether marked external or not, are always
16047                  stored as a global symbol, because we want to be able to
16048                  access them globally.  For instance, we want to be able
16049                  to break on a nested subprogram without having to
16050                  specify the context.  */
16051               list_to_add = &global_symbols;
16052             }
16053           else
16054             {
16055               list_to_add = cu->list_in_scope;
16056             }
16057           break;
16058         case DW_TAG_inlined_subroutine:
16059           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
16060              finish_block.  */
16061           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
16062           SYMBOL_INLINED (sym) = 1;
16063           list_to_add = cu->list_in_scope;
16064           break;
16065         case DW_TAG_template_value_param:
16066           suppress_add = 1;
16067           /* Fall through.  */
16068         case DW_TAG_constant:
16069         case DW_TAG_variable:
16070         case DW_TAG_member:
16071           /* Compilation with minimal debug info may result in
16072              variables with missing type entries.  Change the
16073              misleading `void' type to something sensible.  */
16074           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
16075             SYMBOL_TYPE (sym)
16076               = objfile_type (objfile)->nodebug_data_symbol;
16077
16078           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16079           /* In the case of DW_TAG_member, we should only be called for
16080              static const members.  */
16081           if (die->tag == DW_TAG_member)
16082             {
16083               /* dwarf2_add_field uses die_is_declaration,
16084                  so we do the same.  */
16085               gdb_assert (die_is_declaration (die, cu));
16086               gdb_assert (attr);
16087             }
16088           if (attr)
16089             {
16090               dwarf2_const_value (attr, sym, cu);
16091               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16092               if (!suppress_add)
16093                 {
16094                   if (attr2 && (DW_UNSND (attr2) != 0))
16095                     list_to_add = &global_symbols;
16096                   else
16097                     list_to_add = cu->list_in_scope;
16098                 }
16099               break;
16100             }
16101           attr = dwarf2_attr (die, DW_AT_location, cu);
16102           if (attr)
16103             {
16104               var_decode_location (attr, sym, cu);
16105               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16106
16107               /* Fortran explicitly imports any global symbols to the local
16108                  scope by DW_TAG_common_block.  */
16109               if (cu->language == language_fortran && die->parent
16110                   && die->parent->tag == DW_TAG_common_block)
16111                 attr2 = NULL;
16112
16113               if (SYMBOL_CLASS (sym) == LOC_STATIC
16114                   && SYMBOL_VALUE_ADDRESS (sym) == 0
16115                   && !dwarf2_per_objfile->has_section_at_zero)
16116                 {
16117                   /* When a static variable is eliminated by the linker,
16118                      the corresponding debug information is not stripped
16119                      out, but the variable address is set to null;
16120                      do not add such variables into symbol table.  */
16121                 }
16122               else if (attr2 && (DW_UNSND (attr2) != 0))
16123                 {
16124                   /* Workaround gfortran PR debug/40040 - it uses
16125                      DW_AT_location for variables in -fPIC libraries which may
16126                      get overriden by other libraries/executable and get
16127                      a different address.  Resolve it by the minimal symbol
16128                      which may come from inferior's executable using copy
16129                      relocation.  Make this workaround only for gfortran as for
16130                      other compilers GDB cannot guess the minimal symbol
16131                      Fortran mangling kind.  */
16132                   if (cu->language == language_fortran && die->parent
16133                       && die->parent->tag == DW_TAG_module
16134                       && cu->producer
16135                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
16136                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16137
16138                   /* A variable with DW_AT_external is never static,
16139                      but it may be block-scoped.  */
16140                   list_to_add = (cu->list_in_scope == &file_symbols
16141                                  ? &global_symbols : cu->list_in_scope);
16142                 }
16143               else
16144                 list_to_add = cu->list_in_scope;
16145             }
16146           else
16147             {
16148               /* We do not know the address of this symbol.
16149                  If it is an external symbol and we have type information
16150                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
16151                  The address of the variable will then be determined from
16152                  the minimal symbol table whenever the variable is
16153                  referenced.  */
16154               attr2 = dwarf2_attr (die, DW_AT_external, cu);
16155
16156               /* Fortran explicitly imports any global symbols to the local
16157                  scope by DW_TAG_common_block.  */
16158               if (cu->language == language_fortran && die->parent
16159                   && die->parent->tag == DW_TAG_common_block)
16160                 {
16161                   /* SYMBOL_CLASS doesn't matter here because
16162                      read_common_block is going to reset it.  */
16163                   if (!suppress_add)
16164                     list_to_add = cu->list_in_scope;
16165                 }
16166               else if (attr2 && (DW_UNSND (attr2) != 0)
16167                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
16168                 {
16169                   /* A variable with DW_AT_external is never static, but it
16170                      may be block-scoped.  */
16171                   list_to_add = (cu->list_in_scope == &file_symbols
16172                                  ? &global_symbols : cu->list_in_scope);
16173
16174                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16175                 }
16176               else if (!die_is_declaration (die, cu))
16177                 {
16178                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16179                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16180                   if (!suppress_add)
16181                     list_to_add = cu->list_in_scope;
16182                 }
16183             }
16184           break;
16185         case DW_TAG_formal_parameter:
16186           /* If we are inside a function, mark this as an argument.  If
16187              not, we might be looking at an argument to an inlined function
16188              when we do not have enough information to show inlined frames;
16189              pretend it's a local variable in that case so that the user can
16190              still see it.  */
16191           if (context_stack_depth > 0
16192               && context_stack[context_stack_depth - 1].name != NULL)
16193             SYMBOL_IS_ARGUMENT (sym) = 1;
16194           attr = dwarf2_attr (die, DW_AT_location, cu);
16195           if (attr)
16196             {
16197               var_decode_location (attr, sym, cu);
16198             }
16199           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16200           if (attr)
16201             {
16202               dwarf2_const_value (attr, sym, cu);
16203             }
16204
16205           list_to_add = cu->list_in_scope;
16206           break;
16207         case DW_TAG_unspecified_parameters:
16208           /* From varargs functions; gdb doesn't seem to have any
16209              interest in this information, so just ignore it for now.
16210              (FIXME?) */
16211           break;
16212         case DW_TAG_template_type_param:
16213           suppress_add = 1;
16214           /* Fall through.  */
16215         case DW_TAG_class_type:
16216         case DW_TAG_interface_type:
16217         case DW_TAG_structure_type:
16218         case DW_TAG_union_type:
16219         case DW_TAG_set_type:
16220         case DW_TAG_enumeration_type:
16221           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16222           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16223
16224           {
16225             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16226                really ever be static objects: otherwise, if you try
16227                to, say, break of a class's method and you're in a file
16228                which doesn't mention that class, it won't work unless
16229                the check for all static symbols in lookup_symbol_aux
16230                saves you.  See the OtherFileClass tests in
16231                gdb.c++/namespace.exp.  */
16232
16233             if (!suppress_add)
16234               {
16235                 list_to_add = (cu->list_in_scope == &file_symbols
16236                                && (cu->language == language_cplus
16237                                    || cu->language == language_java)
16238                                ? &global_symbols : cu->list_in_scope);
16239
16240                 /* The semantics of C++ state that "struct foo {
16241                    ... }" also defines a typedef for "foo".  A Java
16242                    class declaration also defines a typedef for the
16243                    class.  */
16244                 if (cu->language == language_cplus
16245                     || cu->language == language_java
16246                     || cu->language == language_ada)
16247                   {
16248                     /* The symbol's name is already allocated along
16249                        with this objfile, so we don't need to
16250                        duplicate it for the type.  */
16251                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16252                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16253                   }
16254               }
16255           }
16256           break;
16257         case DW_TAG_typedef:
16258           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16259           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16260           list_to_add = cu->list_in_scope;
16261           break;
16262         case DW_TAG_base_type:
16263         case DW_TAG_subrange_type:
16264           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16265           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16266           list_to_add = cu->list_in_scope;
16267           break;
16268         case DW_TAG_enumerator:
16269           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16270           if (attr)
16271             {
16272               dwarf2_const_value (attr, sym, cu);
16273             }
16274           {
16275             /* NOTE: carlton/2003-11-10: See comment above in the
16276                DW_TAG_class_type, etc. block.  */
16277
16278             list_to_add = (cu->list_in_scope == &file_symbols
16279                            && (cu->language == language_cplus
16280                                || cu->language == language_java)
16281                            ? &global_symbols : cu->list_in_scope);
16282           }
16283           break;
16284         case DW_TAG_namespace:
16285           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16286           list_to_add = &global_symbols;
16287           break;
16288         case DW_TAG_common_block:
16289           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16290           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16291           add_symbol_to_list (sym, cu->list_in_scope);
16292           break;
16293         default:
16294           /* Not a tag we recognize.  Hopefully we aren't processing
16295              trash data, but since we must specifically ignore things
16296              we don't recognize, there is nothing else we should do at
16297              this point.  */
16298           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16299                      dwarf_tag_name (die->tag));
16300           break;
16301         }
16302
16303       if (suppress_add)
16304         {
16305           sym->hash_next = objfile->template_symbols;
16306           objfile->template_symbols = sym;
16307           list_to_add = NULL;
16308         }
16309
16310       if (list_to_add != NULL)
16311         add_symbol_to_list (sym, list_to_add);
16312
16313       /* For the benefit of old versions of GCC, check for anonymous
16314          namespaces based on the demangled name.  */
16315       if (!cu->processing_has_namespace_info
16316           && cu->language == language_cplus)
16317         cp_scan_for_anonymous_namespaces (sym, objfile);
16318     }
16319   return (sym);
16320 }
16321
16322 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16323
16324 static struct symbol *
16325 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16326 {
16327   return new_symbol_full (die, type, cu, NULL);
16328 }
16329
16330 /* Given an attr with a DW_FORM_dataN value in host byte order,
16331    zero-extend it as appropriate for the symbol's type.  The DWARF
16332    standard (v4) is not entirely clear about the meaning of using
16333    DW_FORM_dataN for a constant with a signed type, where the type is
16334    wider than the data.  The conclusion of a discussion on the DWARF
16335    list was that this is unspecified.  We choose to always zero-extend
16336    because that is the interpretation long in use by GCC.  */
16337
16338 static gdb_byte *
16339 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16340                          const char *name, struct obstack *obstack,
16341                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16342 {
16343   struct objfile *objfile = cu->objfile;
16344   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16345                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16346   LONGEST l = DW_UNSND (attr);
16347
16348   if (bits < sizeof (*value) * 8)
16349     {
16350       l &= ((LONGEST) 1 << bits) - 1;
16351       *value = l;
16352     }
16353   else if (bits == sizeof (*value) * 8)
16354     *value = l;
16355   else
16356     {
16357       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16358       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16359       return bytes;
16360     }
16361
16362   return NULL;
16363 }
16364
16365 /* Read a constant value from an attribute.  Either set *VALUE, or if
16366    the value does not fit in *VALUE, set *BYTES - either already
16367    allocated on the objfile obstack, or newly allocated on OBSTACK,
16368    or, set *BATON, if we translated the constant to a location
16369    expression.  */
16370
16371 static void
16372 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16373                          const char *name, struct obstack *obstack,
16374                          struct dwarf2_cu *cu,
16375                          LONGEST *value, const gdb_byte **bytes,
16376                          struct dwarf2_locexpr_baton **baton)
16377 {
16378   struct objfile *objfile = cu->objfile;
16379   struct comp_unit_head *cu_header = &cu->header;
16380   struct dwarf_block *blk;
16381   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16382                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16383
16384   *value = 0;
16385   *bytes = NULL;
16386   *baton = NULL;
16387
16388   switch (attr->form)
16389     {
16390     case DW_FORM_addr:
16391     case DW_FORM_GNU_addr_index:
16392       {
16393         gdb_byte *data;
16394
16395         if (TYPE_LENGTH (type) != cu_header->addr_size)
16396           dwarf2_const_value_length_mismatch_complaint (name,
16397                                                         cu_header->addr_size,
16398                                                         TYPE_LENGTH (type));
16399         /* Symbols of this form are reasonably rare, so we just
16400            piggyback on the existing location code rather than writing
16401            a new implementation of symbol_computed_ops.  */
16402         *baton = obstack_alloc (&objfile->objfile_obstack,
16403                                 sizeof (struct dwarf2_locexpr_baton));
16404         (*baton)->per_cu = cu->per_cu;
16405         gdb_assert ((*baton)->per_cu);
16406
16407         (*baton)->size = 2 + cu_header->addr_size;
16408         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16409         (*baton)->data = data;
16410
16411         data[0] = DW_OP_addr;
16412         store_unsigned_integer (&data[1], cu_header->addr_size,
16413                                 byte_order, DW_ADDR (attr));
16414         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16415       }
16416       break;
16417     case DW_FORM_string:
16418     case DW_FORM_strp:
16419     case DW_FORM_GNU_str_index:
16420     case DW_FORM_GNU_strp_alt:
16421       /* DW_STRING is already allocated on the objfile obstack, point
16422          directly to it.  */
16423       *bytes = (const gdb_byte *) DW_STRING (attr);
16424       break;
16425     case DW_FORM_block1:
16426     case DW_FORM_block2:
16427     case DW_FORM_block4:
16428     case DW_FORM_block:
16429     case DW_FORM_exprloc:
16430       blk = DW_BLOCK (attr);
16431       if (TYPE_LENGTH (type) != blk->size)
16432         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16433                                                       TYPE_LENGTH (type));
16434       *bytes = blk->data;
16435       break;
16436
16437       /* The DW_AT_const_value attributes are supposed to carry the
16438          symbol's value "represented as it would be on the target
16439          architecture."  By the time we get here, it's already been
16440          converted to host endianness, so we just need to sign- or
16441          zero-extend it as appropriate.  */
16442     case DW_FORM_data1:
16443       *bytes = dwarf2_const_value_data (attr, type, name,
16444                                         obstack, cu, value, 8);
16445       break;
16446     case DW_FORM_data2:
16447       *bytes = dwarf2_const_value_data (attr, type, name,
16448                                         obstack, cu, value, 16);
16449       break;
16450     case DW_FORM_data4:
16451       *bytes = dwarf2_const_value_data (attr, type, name,
16452                                         obstack, cu, value, 32);
16453       break;
16454     case DW_FORM_data8:
16455       *bytes = dwarf2_const_value_data (attr, type, name,
16456                                         obstack, cu, value, 64);
16457       break;
16458
16459     case DW_FORM_sdata:
16460       *value = DW_SND (attr);
16461       break;
16462
16463     case DW_FORM_udata:
16464       *value = DW_UNSND (attr);
16465       break;
16466
16467     default:
16468       complaint (&symfile_complaints,
16469                  _("unsupported const value attribute form: '%s'"),
16470                  dwarf_form_name (attr->form));
16471       *value = 0;
16472       break;
16473     }
16474 }
16475
16476
16477 /* Copy constant value from an attribute to a symbol.  */
16478
16479 static void
16480 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16481                     struct dwarf2_cu *cu)
16482 {
16483   struct objfile *objfile = cu->objfile;
16484   struct comp_unit_head *cu_header = &cu->header;
16485   LONGEST value;
16486   const gdb_byte *bytes;
16487   struct dwarf2_locexpr_baton *baton;
16488
16489   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16490                            SYMBOL_PRINT_NAME (sym),
16491                            &objfile->objfile_obstack, cu,
16492                            &value, &bytes, &baton);
16493
16494   if (baton != NULL)
16495     {
16496       SYMBOL_LOCATION_BATON (sym) = baton;
16497       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16498     }
16499   else if (bytes != NULL)
16500      {
16501       SYMBOL_VALUE_BYTES (sym) = bytes;
16502       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16503     }
16504   else
16505     {
16506       SYMBOL_VALUE (sym) = value;
16507       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16508     }
16509 }
16510
16511 /* Return the type of the die in question using its DW_AT_type attribute.  */
16512
16513 static struct type *
16514 die_type (struct die_info *die, struct dwarf2_cu *cu)
16515 {
16516   struct attribute *type_attr;
16517
16518   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16519   if (!type_attr)
16520     {
16521       /* A missing DW_AT_type represents a void type.  */
16522       return objfile_type (cu->objfile)->builtin_void;
16523     }
16524
16525   return lookup_die_type (die, type_attr, cu);
16526 }
16527
16528 /* True iff CU's producer generates GNAT Ada auxiliary information
16529    that allows to find parallel types through that information instead
16530    of having to do expensive parallel lookups by type name.  */
16531
16532 static int
16533 need_gnat_info (struct dwarf2_cu *cu)
16534 {
16535   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16536      of GNAT produces this auxiliary information, without any indication
16537      that it is produced.  Part of enhancing the FSF version of GNAT
16538      to produce that information will be to put in place an indicator
16539      that we can use in order to determine whether the descriptive type
16540      info is available or not.  One suggestion that has been made is
16541      to use a new attribute, attached to the CU die.  For now, assume
16542      that the descriptive type info is not available.  */
16543   return 0;
16544 }
16545
16546 /* Return the auxiliary type of the die in question using its
16547    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16548    attribute is not present.  */
16549
16550 static struct type *
16551 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16552 {
16553   struct attribute *type_attr;
16554
16555   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16556   if (!type_attr)
16557     return NULL;
16558
16559   return lookup_die_type (die, type_attr, cu);
16560 }
16561
16562 /* If DIE has a descriptive_type attribute, then set the TYPE's
16563    descriptive type accordingly.  */
16564
16565 static void
16566 set_descriptive_type (struct type *type, struct die_info *die,
16567                       struct dwarf2_cu *cu)
16568 {
16569   struct type *descriptive_type = die_descriptive_type (die, cu);
16570
16571   if (descriptive_type)
16572     {
16573       ALLOCATE_GNAT_AUX_TYPE (type);
16574       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16575     }
16576 }
16577
16578 /* Return the containing type of the die in question using its
16579    DW_AT_containing_type attribute.  */
16580
16581 static struct type *
16582 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16583 {
16584   struct attribute *type_attr;
16585
16586   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16587   if (!type_attr)
16588     error (_("Dwarf Error: Problem turning containing type into gdb type "
16589              "[in module %s]"), cu->objfile->name);
16590
16591   return lookup_die_type (die, type_attr, cu);
16592 }
16593
16594 /* Look up the type of DIE in CU using its type attribute ATTR.
16595    If there is no type substitute an error marker.  */
16596
16597 static struct type *
16598 lookup_die_type (struct die_info *die, struct attribute *attr,
16599                  struct dwarf2_cu *cu)
16600 {
16601   struct objfile *objfile = cu->objfile;
16602   struct type *this_type;
16603
16604   /* First see if we have it cached.  */
16605
16606   if (attr->form == DW_FORM_GNU_ref_alt)
16607     {
16608       struct dwarf2_per_cu_data *per_cu;
16609       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16610
16611       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16612       this_type = get_die_type_at_offset (offset, per_cu);
16613     }
16614   else if (is_ref_attr (attr))
16615     {
16616       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16617
16618       this_type = get_die_type_at_offset (offset, cu->per_cu);
16619     }
16620   else if (attr->form == DW_FORM_ref_sig8)
16621     {
16622       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16623
16624       /* sig_type will be NULL if the signatured type is missing from
16625          the debug info.  */
16626       if (sig_type == NULL)
16627         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16628                  "at 0x%x [in module %s]"),
16629                die->offset.sect_off, objfile->name);
16630
16631       gdb_assert (sig_type->per_cu.is_debug_types);
16632       /* If we haven't filled in type_offset_in_section yet, then we
16633          haven't read the type in yet.  */
16634       this_type = NULL;
16635       if (sig_type->type_offset_in_section.sect_off != 0)
16636         {
16637           this_type =
16638             get_die_type_at_offset (sig_type->type_offset_in_section,
16639                                     &sig_type->per_cu);
16640         }
16641     }
16642   else
16643     {
16644       dump_die_for_error (die);
16645       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16646              dwarf_attr_name (attr->name), objfile->name);
16647     }
16648
16649   /* If not cached we need to read it in.  */
16650
16651   if (this_type == NULL)
16652     {
16653       struct die_info *type_die;
16654       struct dwarf2_cu *type_cu = cu;
16655
16656       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16657       /* If we found the type now, it's probably because the type came
16658          from an inter-CU reference and the type's CU got expanded before
16659          ours.  */
16660       this_type = get_die_type (type_die, type_cu);
16661       if (this_type == NULL)
16662         this_type = read_type_die_1 (type_die, type_cu);
16663     }
16664
16665   /* If we still don't have a type use an error marker.  */
16666
16667   if (this_type == NULL)
16668     {
16669       char *message, *saved;
16670
16671       /* read_type_die already issued a complaint.  */
16672       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16673                             objfile->name,
16674                             cu->header.offset.sect_off,
16675                             die->offset.sect_off);
16676       saved = obstack_copy0 (&objfile->objfile_obstack,
16677                              message, strlen (message));
16678       xfree (message);
16679
16680       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16681     }
16682
16683   return this_type;
16684 }
16685
16686 /* Return the type in DIE, CU.
16687    Returns NULL for invalid types.
16688
16689    This first does a lookup in die_type_hash,
16690    and only reads the die in if necessary.
16691
16692    NOTE: This can be called when reading in partial or full symbols.  */
16693
16694 static struct type *
16695 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16696 {
16697   struct type *this_type;
16698
16699   this_type = get_die_type (die, cu);
16700   if (this_type)
16701     return this_type;
16702
16703   return read_type_die_1 (die, cu);
16704 }
16705
16706 /* Read the type in DIE, CU.
16707    Returns NULL for invalid types.  */
16708
16709 static struct type *
16710 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16711 {
16712   struct type *this_type = NULL;
16713
16714   switch (die->tag)
16715     {
16716     case DW_TAG_class_type:
16717     case DW_TAG_interface_type:
16718     case DW_TAG_structure_type:
16719     case DW_TAG_union_type:
16720       this_type = read_structure_type (die, cu);
16721       break;
16722     case DW_TAG_enumeration_type:
16723       this_type = read_enumeration_type (die, cu);
16724       break;
16725     case DW_TAG_subprogram:
16726     case DW_TAG_subroutine_type:
16727     case DW_TAG_inlined_subroutine:
16728       this_type = read_subroutine_type (die, cu);
16729       break;
16730     case DW_TAG_array_type:
16731       this_type = read_array_type (die, cu);
16732       break;
16733     case DW_TAG_set_type:
16734       this_type = read_set_type (die, cu);
16735       break;
16736     case DW_TAG_pointer_type:
16737       this_type = read_tag_pointer_type (die, cu);
16738       break;
16739     case DW_TAG_ptr_to_member_type:
16740       this_type = read_tag_ptr_to_member_type (die, cu);
16741       break;
16742     case DW_TAG_reference_type:
16743       this_type = read_tag_reference_type (die, cu);
16744       break;
16745     case DW_TAG_const_type:
16746       this_type = read_tag_const_type (die, cu);
16747       break;
16748     case DW_TAG_volatile_type:
16749       this_type = read_tag_volatile_type (die, cu);
16750       break;
16751     case DW_TAG_restrict_type:
16752       this_type = read_tag_restrict_type (die, cu);
16753       break;
16754     case DW_TAG_string_type:
16755       this_type = read_tag_string_type (die, cu);
16756       break;
16757     case DW_TAG_typedef:
16758       this_type = read_typedef (die, cu);
16759       break;
16760     case DW_TAG_subrange_type:
16761       this_type = read_subrange_type (die, cu);
16762       break;
16763     case DW_TAG_base_type:
16764       this_type = read_base_type (die, cu);
16765       break;
16766     case DW_TAG_unspecified_type:
16767       this_type = read_unspecified_type (die, cu);
16768       break;
16769     case DW_TAG_namespace:
16770       this_type = read_namespace_type (die, cu);
16771       break;
16772     case DW_TAG_module:
16773       this_type = read_module_type (die, cu);
16774       break;
16775     default:
16776       complaint (&symfile_complaints,
16777                  _("unexpected tag in read_type_die: '%s'"),
16778                  dwarf_tag_name (die->tag));
16779       break;
16780     }
16781
16782   return this_type;
16783 }
16784
16785 /* See if we can figure out if the class lives in a namespace.  We do
16786    this by looking for a member function; its demangled name will
16787    contain namespace info, if there is any.
16788    Return the computed name or NULL.
16789    Space for the result is allocated on the objfile's obstack.
16790    This is the full-die version of guess_partial_die_structure_name.
16791    In this case we know DIE has no useful parent.  */
16792
16793 static char *
16794 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16795 {
16796   struct die_info *spec_die;
16797   struct dwarf2_cu *spec_cu;
16798   struct die_info *child;
16799
16800   spec_cu = cu;
16801   spec_die = die_specification (die, &spec_cu);
16802   if (spec_die != NULL)
16803     {
16804       die = spec_die;
16805       cu = spec_cu;
16806     }
16807
16808   for (child = die->child;
16809        child != NULL;
16810        child = child->sibling)
16811     {
16812       if (child->tag == DW_TAG_subprogram)
16813         {
16814           struct attribute *attr;
16815
16816           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16817           if (attr == NULL)
16818             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16819           if (attr != NULL)
16820             {
16821               char *actual_name
16822                 = language_class_name_from_physname (cu->language_defn,
16823                                                      DW_STRING (attr));
16824               char *name = NULL;
16825
16826               if (actual_name != NULL)
16827                 {
16828                   const char *die_name = dwarf2_name (die, cu);
16829
16830                   if (die_name != NULL
16831                       && strcmp (die_name, actual_name) != 0)
16832                     {
16833                       /* Strip off the class name from the full name.
16834                          We want the prefix.  */
16835                       int die_name_len = strlen (die_name);
16836                       int actual_name_len = strlen (actual_name);
16837
16838                       /* Test for '::' as a sanity check.  */
16839                       if (actual_name_len > die_name_len + 2
16840                           && actual_name[actual_name_len
16841                                          - die_name_len - 1] == ':')
16842                         name =
16843                           obstack_copy0 (&cu->objfile->objfile_obstack,
16844                                          actual_name,
16845                                          actual_name_len - die_name_len - 2);
16846                     }
16847                 }
16848               xfree (actual_name);
16849               return name;
16850             }
16851         }
16852     }
16853
16854   return NULL;
16855 }
16856
16857 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16858    prefix part in such case.  See
16859    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16860
16861 static char *
16862 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16863 {
16864   struct attribute *attr;
16865   char *base;
16866
16867   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16868       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16869     return NULL;
16870
16871   attr = dwarf2_attr (die, DW_AT_name, cu);
16872   if (attr != NULL && DW_STRING (attr) != NULL)
16873     return NULL;
16874
16875   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16876   if (attr == NULL)
16877     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16878   if (attr == NULL || DW_STRING (attr) == NULL)
16879     return NULL;
16880
16881   /* dwarf2_name had to be already called.  */
16882   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16883
16884   /* Strip the base name, keep any leading namespaces/classes.  */
16885   base = strrchr (DW_STRING (attr), ':');
16886   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16887     return "";
16888
16889   return obstack_copy0 (&cu->objfile->objfile_obstack,
16890                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16891 }
16892
16893 /* Return the name of the namespace/class that DIE is defined within,
16894    or "" if we can't tell.  The caller should not xfree the result.
16895
16896    For example, if we're within the method foo() in the following
16897    code:
16898
16899    namespace N {
16900      class C {
16901        void foo () {
16902        }
16903      };
16904    }
16905
16906    then determine_prefix on foo's die will return "N::C".  */
16907
16908 static const char *
16909 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16910 {
16911   struct die_info *parent, *spec_die;
16912   struct dwarf2_cu *spec_cu;
16913   struct type *parent_type;
16914   char *retval;
16915
16916   if (cu->language != language_cplus && cu->language != language_java
16917       && cu->language != language_fortran)
16918     return "";
16919
16920   retval = anonymous_struct_prefix (die, cu);
16921   if (retval)
16922     return retval;
16923
16924   /* We have to be careful in the presence of DW_AT_specification.
16925      For example, with GCC 3.4, given the code
16926
16927      namespace N {
16928        void foo() {
16929          // Definition of N::foo.
16930        }
16931      }
16932
16933      then we'll have a tree of DIEs like this:
16934
16935      1: DW_TAG_compile_unit
16936        2: DW_TAG_namespace        // N
16937          3: DW_TAG_subprogram     // declaration of N::foo
16938        4: DW_TAG_subprogram       // definition of N::foo
16939             DW_AT_specification   // refers to die #3
16940
16941      Thus, when processing die #4, we have to pretend that we're in
16942      the context of its DW_AT_specification, namely the contex of die
16943      #3.  */
16944   spec_cu = cu;
16945   spec_die = die_specification (die, &spec_cu);
16946   if (spec_die == NULL)
16947     parent = die->parent;
16948   else
16949     {
16950       parent = spec_die->parent;
16951       cu = spec_cu;
16952     }
16953
16954   if (parent == NULL)
16955     return "";
16956   else if (parent->building_fullname)
16957     {
16958       const char *name;
16959       const char *parent_name;
16960
16961       /* It has been seen on RealView 2.2 built binaries,
16962          DW_TAG_template_type_param types actually _defined_ as
16963          children of the parent class:
16964
16965          enum E {};
16966          template class <class Enum> Class{};
16967          Class<enum E> class_e;
16968
16969          1: DW_TAG_class_type (Class)
16970            2: DW_TAG_enumeration_type (E)
16971              3: DW_TAG_enumerator (enum1:0)
16972              3: DW_TAG_enumerator (enum2:1)
16973              ...
16974            2: DW_TAG_template_type_param
16975               DW_AT_type  DW_FORM_ref_udata (E)
16976
16977          Besides being broken debug info, it can put GDB into an
16978          infinite loop.  Consider:
16979
16980          When we're building the full name for Class<E>, we'll start
16981          at Class, and go look over its template type parameters,
16982          finding E.  We'll then try to build the full name of E, and
16983          reach here.  We're now trying to build the full name of E,
16984          and look over the parent DIE for containing scope.  In the
16985          broken case, if we followed the parent DIE of E, we'd again
16986          find Class, and once again go look at its template type
16987          arguments, etc., etc.  Simply don't consider such parent die
16988          as source-level parent of this die (it can't be, the language
16989          doesn't allow it), and break the loop here.  */
16990       name = dwarf2_name (die, cu);
16991       parent_name = dwarf2_name (parent, cu);
16992       complaint (&symfile_complaints,
16993                  _("template param type '%s' defined within parent '%s'"),
16994                  name ? name : "<unknown>",
16995                  parent_name ? parent_name : "<unknown>");
16996       return "";
16997     }
16998   else
16999     switch (parent->tag)
17000       {
17001       case DW_TAG_namespace:
17002         parent_type = read_type_die (parent, cu);
17003         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
17004            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
17005            Work around this problem here.  */
17006         if (cu->language == language_cplus
17007             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
17008           return "";
17009         /* We give a name to even anonymous namespaces.  */
17010         return TYPE_TAG_NAME (parent_type);
17011       case DW_TAG_class_type:
17012       case DW_TAG_interface_type:
17013       case DW_TAG_structure_type:
17014       case DW_TAG_union_type:
17015       case DW_TAG_module:
17016         parent_type = read_type_die (parent, cu);
17017         if (TYPE_TAG_NAME (parent_type) != NULL)
17018           return TYPE_TAG_NAME (parent_type);
17019         else
17020           /* An anonymous structure is only allowed non-static data
17021              members; no typedefs, no member functions, et cetera.
17022              So it does not need a prefix.  */
17023           return "";
17024       case DW_TAG_compile_unit:
17025       case DW_TAG_partial_unit:
17026         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
17027         if (cu->language == language_cplus
17028             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17029             && die->child != NULL
17030             && (die->tag == DW_TAG_class_type
17031                 || die->tag == DW_TAG_structure_type
17032                 || die->tag == DW_TAG_union_type))
17033           {
17034             char *name = guess_full_die_structure_name (die, cu);
17035             if (name != NULL)
17036               return name;
17037           }
17038         return "";
17039       default:
17040         return determine_prefix (parent, cu);
17041       }
17042 }
17043
17044 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
17045    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
17046    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
17047    an obconcat, otherwise allocate storage for the result.  The CU argument is
17048    used to determine the language and hence, the appropriate separator.  */
17049
17050 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
17051
17052 static char *
17053 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
17054                  int physname, struct dwarf2_cu *cu)
17055 {
17056   const char *lead = "";
17057   const char *sep;
17058
17059   if (suffix == NULL || suffix[0] == '\0'
17060       || prefix == NULL || prefix[0] == '\0')
17061     sep = "";
17062   else if (cu->language == language_java)
17063     sep = ".";
17064   else if (cu->language == language_fortran && physname)
17065     {
17066       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
17067          DW_AT_MIPS_linkage_name is preferred and used instead.  */
17068
17069       lead = "__";
17070       sep = "_MOD_";
17071     }
17072   else
17073     sep = "::";
17074
17075   if (prefix == NULL)
17076     prefix = "";
17077   if (suffix == NULL)
17078     suffix = "";
17079
17080   if (obs == NULL)
17081     {
17082       char *retval
17083         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
17084
17085       strcpy (retval, lead);
17086       strcat (retval, prefix);
17087       strcat (retval, sep);
17088       strcat (retval, suffix);
17089       return retval;
17090     }
17091   else
17092     {
17093       /* We have an obstack.  */
17094       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
17095     }
17096 }
17097
17098 /* Return sibling of die, NULL if no sibling.  */
17099
17100 static struct die_info *
17101 sibling_die (struct die_info *die)
17102 {
17103   return die->sibling;
17104 }
17105
17106 /* Get name of a die, return NULL if not found.  */
17107
17108 static const char *
17109 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
17110                           struct obstack *obstack)
17111 {
17112   if (name && cu->language == language_cplus)
17113     {
17114       char *canon_name = cp_canonicalize_string (name);
17115
17116       if (canon_name != NULL)
17117         {
17118           if (strcmp (canon_name, name) != 0)
17119             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
17120           xfree (canon_name);
17121         }
17122     }
17123
17124   return name;
17125 }
17126
17127 /* Get name of a die, return NULL if not found.  */
17128
17129 static const char *
17130 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
17131 {
17132   struct attribute *attr;
17133
17134   attr = dwarf2_attr (die, DW_AT_name, cu);
17135   if ((!attr || !DW_STRING (attr))
17136       && die->tag != DW_TAG_class_type
17137       && die->tag != DW_TAG_interface_type
17138       && die->tag != DW_TAG_structure_type
17139       && die->tag != DW_TAG_union_type)
17140     return NULL;
17141
17142   switch (die->tag)
17143     {
17144     case DW_TAG_compile_unit:
17145     case DW_TAG_partial_unit:
17146       /* Compilation units have a DW_AT_name that is a filename, not
17147          a source language identifier.  */
17148     case DW_TAG_enumeration_type:
17149     case DW_TAG_enumerator:
17150       /* These tags always have simple identifiers already; no need
17151          to canonicalize them.  */
17152       return DW_STRING (attr);
17153
17154     case DW_TAG_subprogram:
17155       /* Java constructors will all be named "<init>", so return
17156          the class name when we see this special case.  */
17157       if (cu->language == language_java
17158           && DW_STRING (attr) != NULL
17159           && strcmp (DW_STRING (attr), "<init>") == 0)
17160         {
17161           struct dwarf2_cu *spec_cu = cu;
17162           struct die_info *spec_die;
17163
17164           /* GCJ will output '<init>' for Java constructor names.
17165              For this special case, return the name of the parent class.  */
17166
17167           /* GCJ may output suprogram DIEs with AT_specification set.
17168              If so, use the name of the specified DIE.  */
17169           spec_die = die_specification (die, &spec_cu);
17170           if (spec_die != NULL)
17171             return dwarf2_name (spec_die, spec_cu);
17172
17173           do
17174             {
17175               die = die->parent;
17176               if (die->tag == DW_TAG_class_type)
17177                 return dwarf2_name (die, cu);
17178             }
17179           while (die->tag != DW_TAG_compile_unit
17180                  && die->tag != DW_TAG_partial_unit);
17181         }
17182       break;
17183
17184     case DW_TAG_class_type:
17185     case DW_TAG_interface_type:
17186     case DW_TAG_structure_type:
17187     case DW_TAG_union_type:
17188       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17189          structures or unions.  These were of the form "._%d" in GCC 4.1,
17190          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17191          and GCC 4.4.  We work around this problem by ignoring these.  */
17192       if (attr && DW_STRING (attr)
17193           && (strncmp (DW_STRING (attr), "._", 2) == 0
17194               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17195         return NULL;
17196
17197       /* GCC might emit a nameless typedef that has a linkage name.  See
17198          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17199       if (!attr || DW_STRING (attr) == NULL)
17200         {
17201           char *demangled = NULL;
17202
17203           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17204           if (attr == NULL)
17205             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17206
17207           if (attr == NULL || DW_STRING (attr) == NULL)
17208             return NULL;
17209
17210           /* Avoid demangling DW_STRING (attr) the second time on a second
17211              call for the same DIE.  */
17212           if (!DW_STRING_IS_CANONICAL (attr))
17213             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
17214
17215           if (demangled)
17216             {
17217               char *base;
17218
17219               /* FIXME: we already did this for the partial symbol... */
17220               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17221                                                 demangled, strlen (demangled));
17222               DW_STRING_IS_CANONICAL (attr) = 1;
17223               xfree (demangled);
17224
17225               /* Strip any leading namespaces/classes, keep only the base name.
17226                  DW_AT_name for named DIEs does not contain the prefixes.  */
17227               base = strrchr (DW_STRING (attr), ':');
17228               if (base && base > DW_STRING (attr) && base[-1] == ':')
17229                 return &base[1];
17230               else
17231                 return DW_STRING (attr);
17232             }
17233         }
17234       break;
17235
17236     default:
17237       break;
17238     }
17239
17240   if (!DW_STRING_IS_CANONICAL (attr))
17241     {
17242       DW_STRING (attr)
17243         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17244                                     &cu->objfile->objfile_obstack);
17245       DW_STRING_IS_CANONICAL (attr) = 1;
17246     }
17247   return DW_STRING (attr);
17248 }
17249
17250 /* Return the die that this die in an extension of, or NULL if there
17251    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17252    containing the return value on output.  */
17253
17254 static struct die_info *
17255 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17256 {
17257   struct attribute *attr;
17258
17259   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17260   if (attr == NULL)
17261     return NULL;
17262
17263   return follow_die_ref (die, attr, ext_cu);
17264 }
17265
17266 /* Convert a DIE tag into its string name.  */
17267
17268 static const char *
17269 dwarf_tag_name (unsigned tag)
17270 {
17271   const char *name = get_DW_TAG_name (tag);
17272
17273   if (name == NULL)
17274     return "DW_TAG_<unknown>";
17275
17276   return name;
17277 }
17278
17279 /* Convert a DWARF attribute code into its string name.  */
17280
17281 static const char *
17282 dwarf_attr_name (unsigned attr)
17283 {
17284   const char *name;
17285
17286 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17287   if (attr == DW_AT_MIPS_fde)
17288     return "DW_AT_MIPS_fde";
17289 #else
17290   if (attr == DW_AT_HP_block_index)
17291     return "DW_AT_HP_block_index";
17292 #endif
17293
17294   name = get_DW_AT_name (attr);
17295
17296   if (name == NULL)
17297     return "DW_AT_<unknown>";
17298
17299   return name;
17300 }
17301
17302 /* Convert a DWARF value form code into its string name.  */
17303
17304 static const char *
17305 dwarf_form_name (unsigned form)
17306 {
17307   const char *name = get_DW_FORM_name (form);
17308
17309   if (name == NULL)
17310     return "DW_FORM_<unknown>";
17311
17312   return name;
17313 }
17314
17315 static char *
17316 dwarf_bool_name (unsigned mybool)
17317 {
17318   if (mybool)
17319     return "TRUE";
17320   else
17321     return "FALSE";
17322 }
17323
17324 /* Convert a DWARF type code into its string name.  */
17325
17326 static const char *
17327 dwarf_type_encoding_name (unsigned enc)
17328 {
17329   const char *name = get_DW_ATE_name (enc);
17330
17331   if (name == NULL)
17332     return "DW_ATE_<unknown>";
17333
17334   return name;
17335 }
17336
17337 static void
17338 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17339 {
17340   unsigned int i;
17341
17342   print_spaces (indent, f);
17343   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17344            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17345
17346   if (die->parent != NULL)
17347     {
17348       print_spaces (indent, f);
17349       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17350                           die->parent->offset.sect_off);
17351     }
17352
17353   print_spaces (indent, f);
17354   fprintf_unfiltered (f, "  has children: %s\n",
17355            dwarf_bool_name (die->child != NULL));
17356
17357   print_spaces (indent, f);
17358   fprintf_unfiltered (f, "  attributes:\n");
17359
17360   for (i = 0; i < die->num_attrs; ++i)
17361     {
17362       print_spaces (indent, f);
17363       fprintf_unfiltered (f, "    %s (%s) ",
17364                dwarf_attr_name (die->attrs[i].name),
17365                dwarf_form_name (die->attrs[i].form));
17366
17367       switch (die->attrs[i].form)
17368         {
17369         case DW_FORM_addr:
17370         case DW_FORM_GNU_addr_index:
17371           fprintf_unfiltered (f, "address: ");
17372           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17373           break;
17374         case DW_FORM_block2:
17375         case DW_FORM_block4:
17376         case DW_FORM_block:
17377         case DW_FORM_block1:
17378           fprintf_unfiltered (f, "block: size %s",
17379                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17380           break;
17381         case DW_FORM_exprloc:
17382           fprintf_unfiltered (f, "expression: size %s",
17383                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17384           break;
17385         case DW_FORM_ref_addr:
17386           fprintf_unfiltered (f, "ref address: ");
17387           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17388           break;
17389         case DW_FORM_GNU_ref_alt:
17390           fprintf_unfiltered (f, "alt ref address: ");
17391           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17392           break;
17393         case DW_FORM_ref1:
17394         case DW_FORM_ref2:
17395         case DW_FORM_ref4:
17396         case DW_FORM_ref8:
17397         case DW_FORM_ref_udata:
17398           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17399                               (long) (DW_UNSND (&die->attrs[i])));
17400           break;
17401         case DW_FORM_data1:
17402         case DW_FORM_data2:
17403         case DW_FORM_data4:
17404         case DW_FORM_data8:
17405         case DW_FORM_udata:
17406         case DW_FORM_sdata:
17407           fprintf_unfiltered (f, "constant: %s",
17408                               pulongest (DW_UNSND (&die->attrs[i])));
17409           break;
17410         case DW_FORM_sec_offset:
17411           fprintf_unfiltered (f, "section offset: %s",
17412                               pulongest (DW_UNSND (&die->attrs[i])));
17413           break;
17414         case DW_FORM_ref_sig8:
17415           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17416             {
17417               struct signatured_type *sig_type =
17418                 DW_SIGNATURED_TYPE (&die->attrs[i]);
17419
17420               fprintf_unfiltered (f, "signatured type: 0x%s, offset 0x%x",
17421                                   hex_string (sig_type->signature),
17422                                   sig_type->per_cu.offset.sect_off);
17423             }
17424           else
17425             fprintf_unfiltered (f, "signatured type, unknown");
17426           break;
17427         case DW_FORM_string:
17428         case DW_FORM_strp:
17429         case DW_FORM_GNU_str_index:
17430         case DW_FORM_GNU_strp_alt:
17431           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17432                    DW_STRING (&die->attrs[i])
17433                    ? DW_STRING (&die->attrs[i]) : "",
17434                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17435           break;
17436         case DW_FORM_flag:
17437           if (DW_UNSND (&die->attrs[i]))
17438             fprintf_unfiltered (f, "flag: TRUE");
17439           else
17440             fprintf_unfiltered (f, "flag: FALSE");
17441           break;
17442         case DW_FORM_flag_present:
17443           fprintf_unfiltered (f, "flag: TRUE");
17444           break;
17445         case DW_FORM_indirect:
17446           /* The reader will have reduced the indirect form to
17447              the "base form" so this form should not occur.  */
17448           fprintf_unfiltered (f, 
17449                               "unexpected attribute form: DW_FORM_indirect");
17450           break;
17451         default:
17452           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17453                    die->attrs[i].form);
17454           break;
17455         }
17456       fprintf_unfiltered (f, "\n");
17457     }
17458 }
17459
17460 static void
17461 dump_die_for_error (struct die_info *die)
17462 {
17463   dump_die_shallow (gdb_stderr, 0, die);
17464 }
17465
17466 static void
17467 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17468 {
17469   int indent = level * 4;
17470
17471   gdb_assert (die != NULL);
17472
17473   if (level >= max_level)
17474     return;
17475
17476   dump_die_shallow (f, indent, die);
17477
17478   if (die->child != NULL)
17479     {
17480       print_spaces (indent, f);
17481       fprintf_unfiltered (f, "  Children:");
17482       if (level + 1 < max_level)
17483         {
17484           fprintf_unfiltered (f, "\n");
17485           dump_die_1 (f, level + 1, max_level, die->child);
17486         }
17487       else
17488         {
17489           fprintf_unfiltered (f,
17490                               " [not printed, max nesting level reached]\n");
17491         }
17492     }
17493
17494   if (die->sibling != NULL && level > 0)
17495     {
17496       dump_die_1 (f, level, max_level, die->sibling);
17497     }
17498 }
17499
17500 /* This is called from the pdie macro in gdbinit.in.
17501    It's not static so gcc will keep a copy callable from gdb.  */
17502
17503 void
17504 dump_die (struct die_info *die, int max_level)
17505 {
17506   dump_die_1 (gdb_stdlog, 0, max_level, die);
17507 }
17508
17509 static void
17510 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17511 {
17512   void **slot;
17513
17514   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17515                                    INSERT);
17516
17517   *slot = die;
17518 }
17519
17520 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17521    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17522
17523 static int
17524 is_ref_attr (struct attribute *attr)
17525 {
17526   switch (attr->form)
17527     {
17528     case DW_FORM_ref_addr:
17529     case DW_FORM_ref1:
17530     case DW_FORM_ref2:
17531     case DW_FORM_ref4:
17532     case DW_FORM_ref8:
17533     case DW_FORM_ref_udata:
17534     case DW_FORM_GNU_ref_alt:
17535       return 1;
17536     default:
17537       return 0;
17538     }
17539 }
17540
17541 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17542    required kind.  */
17543
17544 static sect_offset
17545 dwarf2_get_ref_die_offset (struct attribute *attr)
17546 {
17547   sect_offset retval = { DW_UNSND (attr) };
17548
17549   if (is_ref_attr (attr))
17550     return retval;
17551
17552   retval.sect_off = 0;
17553   complaint (&symfile_complaints,
17554              _("unsupported die ref attribute form: '%s'"),
17555              dwarf_form_name (attr->form));
17556   return retval;
17557 }
17558
17559 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17560  * the value held by the attribute is not constant.  */
17561
17562 static LONGEST
17563 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17564 {
17565   if (attr->form == DW_FORM_sdata)
17566     return DW_SND (attr);
17567   else if (attr->form == DW_FORM_udata
17568            || attr->form == DW_FORM_data1
17569            || attr->form == DW_FORM_data2
17570            || attr->form == DW_FORM_data4
17571            || attr->form == DW_FORM_data8)
17572     return DW_UNSND (attr);
17573   else
17574     {
17575       complaint (&symfile_complaints,
17576                  _("Attribute value is not a constant (%s)"),
17577                  dwarf_form_name (attr->form));
17578       return default_value;
17579     }
17580 }
17581
17582 /* Follow reference or signature attribute ATTR of SRC_DIE.
17583    On entry *REF_CU is the CU of SRC_DIE.
17584    On exit *REF_CU is the CU of the result.  */
17585
17586 static struct die_info *
17587 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17588                        struct dwarf2_cu **ref_cu)
17589 {
17590   struct die_info *die;
17591
17592   if (is_ref_attr (attr))
17593     die = follow_die_ref (src_die, attr, ref_cu);
17594   else if (attr->form == DW_FORM_ref_sig8)
17595     die = follow_die_sig (src_die, attr, ref_cu);
17596   else
17597     {
17598       dump_die_for_error (src_die);
17599       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17600              (*ref_cu)->objfile->name);
17601     }
17602
17603   return die;
17604 }
17605
17606 /* Follow reference OFFSET.
17607    On entry *REF_CU is the CU of the source die referencing OFFSET.
17608    On exit *REF_CU is the CU of the result.
17609    Returns NULL if OFFSET is invalid.  */
17610
17611 static struct die_info *
17612 follow_die_offset (sect_offset offset, int offset_in_dwz,
17613                    struct dwarf2_cu **ref_cu)
17614 {
17615   struct die_info temp_die;
17616   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17617
17618   gdb_assert (cu->per_cu != NULL);
17619
17620   target_cu = cu;
17621
17622   if (cu->per_cu->is_debug_types)
17623     {
17624       /* .debug_types CUs cannot reference anything outside their CU.
17625          If they need to, they have to reference a signatured type via
17626          DW_FORM_ref_sig8.  */
17627       if (! offset_in_cu_p (&cu->header, offset))
17628         return NULL;
17629     }
17630   else if (offset_in_dwz != cu->per_cu->is_dwz
17631            || ! offset_in_cu_p (&cu->header, offset))
17632     {
17633       struct dwarf2_per_cu_data *per_cu;
17634
17635       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17636                                                  cu->objfile);
17637
17638       /* If necessary, add it to the queue and load its DIEs.  */
17639       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17640         load_full_comp_unit (per_cu, cu->language);
17641
17642       target_cu = per_cu->cu;
17643     }
17644   else if (cu->dies == NULL)
17645     {
17646       /* We're loading full DIEs during partial symbol reading.  */
17647       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17648       load_full_comp_unit (cu->per_cu, language_minimal);
17649     }
17650
17651   *ref_cu = target_cu;
17652   temp_die.offset = offset;
17653   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17654 }
17655
17656 /* Follow reference attribute ATTR of SRC_DIE.
17657    On entry *REF_CU is the CU of SRC_DIE.
17658    On exit *REF_CU is the CU of the result.  */
17659
17660 static struct die_info *
17661 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17662                 struct dwarf2_cu **ref_cu)
17663 {
17664   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17665   struct dwarf2_cu *cu = *ref_cu;
17666   struct die_info *die;
17667
17668   die = follow_die_offset (offset,
17669                            (attr->form == DW_FORM_GNU_ref_alt
17670                             || cu->per_cu->is_dwz),
17671                            ref_cu);
17672   if (!die)
17673     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17674            "at 0x%x [in module %s]"),
17675            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17676
17677   return die;
17678 }
17679
17680 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17681    Returned value is intended for DW_OP_call*.  Returned
17682    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17683
17684 struct dwarf2_locexpr_baton
17685 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17686                                struct dwarf2_per_cu_data *per_cu,
17687                                CORE_ADDR (*get_frame_pc) (void *baton),
17688                                void *baton)
17689 {
17690   struct dwarf2_cu *cu;
17691   struct die_info *die;
17692   struct attribute *attr;
17693   struct dwarf2_locexpr_baton retval;
17694
17695   dw2_setup (per_cu->objfile);
17696
17697   if (per_cu->cu == NULL)
17698     load_cu (per_cu);
17699   cu = per_cu->cu;
17700
17701   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17702   if (!die)
17703     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17704            offset.sect_off, per_cu->objfile->name);
17705
17706   attr = dwarf2_attr (die, DW_AT_location, cu);
17707   if (!attr)
17708     {
17709       /* DWARF: "If there is no such attribute, then there is no effect.".
17710          DATA is ignored if SIZE is 0.  */
17711
17712       retval.data = NULL;
17713       retval.size = 0;
17714     }
17715   else if (attr_form_is_section_offset (attr))
17716     {
17717       struct dwarf2_loclist_baton loclist_baton;
17718       CORE_ADDR pc = (*get_frame_pc) (baton);
17719       size_t size;
17720
17721       fill_in_loclist_baton (cu, &loclist_baton, attr);
17722
17723       retval.data = dwarf2_find_location_expression (&loclist_baton,
17724                                                      &size, pc);
17725       retval.size = size;
17726     }
17727   else
17728     {
17729       if (!attr_form_is_block (attr))
17730         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17731                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17732                offset.sect_off, per_cu->objfile->name);
17733
17734       retval.data = DW_BLOCK (attr)->data;
17735       retval.size = DW_BLOCK (attr)->size;
17736     }
17737   retval.per_cu = cu->per_cu;
17738
17739   age_cached_comp_units ();
17740
17741   return retval;
17742 }
17743
17744 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17745    offset.  */
17746
17747 struct dwarf2_locexpr_baton
17748 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17749                              struct dwarf2_per_cu_data *per_cu,
17750                              CORE_ADDR (*get_frame_pc) (void *baton),
17751                              void *baton)
17752 {
17753   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17754
17755   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17756 }
17757
17758 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17759    PER_CU.  */
17760
17761 struct type *
17762 dwarf2_get_die_type (cu_offset die_offset,
17763                      struct dwarf2_per_cu_data *per_cu)
17764 {
17765   sect_offset die_offset_sect;
17766
17767   dw2_setup (per_cu->objfile);
17768
17769   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17770   return get_die_type_at_offset (die_offset_sect, per_cu);
17771 }
17772
17773 /* Follow the signature attribute ATTR in SRC_DIE.
17774    On entry *REF_CU is the CU of SRC_DIE.
17775    On exit *REF_CU is the CU of the result.  */
17776
17777 static struct die_info *
17778 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17779                 struct dwarf2_cu **ref_cu)
17780 {
17781   struct objfile *objfile = (*ref_cu)->objfile;
17782   struct die_info temp_die;
17783   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17784   struct dwarf2_cu *sig_cu;
17785   struct die_info *die;
17786
17787   /* sig_type will be NULL if the signatured type is missing from
17788      the debug info.  */
17789   if (sig_type == NULL)
17790     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17791              "at 0x%x [in module %s]"),
17792            src_die->offset.sect_off, objfile->name);
17793
17794   /* If necessary, add it to the queue and load its DIEs.  */
17795
17796   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17797     read_signatured_type (sig_type);
17798
17799   gdb_assert (sig_type->per_cu.cu != NULL);
17800
17801   sig_cu = sig_type->per_cu.cu;
17802   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17803   temp_die.offset = sig_type->type_offset_in_section;
17804   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17805                              temp_die.offset.sect_off);
17806   if (die)
17807     {
17808       /* For .gdb_index version 7 keep track of included TUs.
17809          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17810       if (dwarf2_per_objfile->index_table != NULL
17811           && dwarf2_per_objfile->index_table->version <= 7)
17812         {
17813           VEC_safe_push (dwarf2_per_cu_ptr,
17814                          (*ref_cu)->per_cu->imported_symtabs,
17815                          sig_cu->per_cu);
17816         }
17817
17818       *ref_cu = sig_cu;
17819       return die;
17820     }
17821
17822   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17823          "from DIE at 0x%x [in module %s]"),
17824          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17825 }
17826
17827 /* Load the DIEs associated with type unit PER_CU into memory.  */
17828
17829 static void
17830 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17831 {
17832   struct signatured_type *sig_type;
17833
17834   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17835   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17836
17837   /* We have the per_cu, but we need the signatured_type.
17838      Fortunately this is an easy translation.  */
17839   gdb_assert (per_cu->is_debug_types);
17840   sig_type = (struct signatured_type *) per_cu;
17841
17842   gdb_assert (per_cu->cu == NULL);
17843
17844   read_signatured_type (sig_type);
17845
17846   gdb_assert (per_cu->cu != NULL);
17847 }
17848
17849 /* die_reader_func for read_signatured_type.
17850    This is identical to load_full_comp_unit_reader,
17851    but is kept separate for now.  */
17852
17853 static void
17854 read_signatured_type_reader (const struct die_reader_specs *reader,
17855                              const gdb_byte *info_ptr,
17856                              struct die_info *comp_unit_die,
17857                              int has_children,
17858                              void *data)
17859 {
17860   struct dwarf2_cu *cu = reader->cu;
17861
17862   gdb_assert (cu->die_hash == NULL);
17863   cu->die_hash =
17864     htab_create_alloc_ex (cu->header.length / 12,
17865                           die_hash,
17866                           die_eq,
17867                           NULL,
17868                           &cu->comp_unit_obstack,
17869                           hashtab_obstack_allocate,
17870                           dummy_obstack_deallocate);
17871
17872   if (has_children)
17873     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17874                                                   &info_ptr, comp_unit_die);
17875   cu->dies = comp_unit_die;
17876   /* comp_unit_die is not stored in die_hash, no need.  */
17877
17878   /* We try not to read any attributes in this function, because not
17879      all CUs needed for references have been loaded yet, and symbol
17880      table processing isn't initialized.  But we have to set the CU language,
17881      or we won't be able to build types correctly.
17882      Similarly, if we do not read the producer, we can not apply
17883      producer-specific interpretation.  */
17884   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17885 }
17886
17887 /* Read in a signatured type and build its CU and DIEs.
17888    If the type is a stub for the real type in a DWO file,
17889    read in the real type from the DWO file as well.  */
17890
17891 static void
17892 read_signatured_type (struct signatured_type *sig_type)
17893 {
17894   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17895
17896   gdb_assert (per_cu->is_debug_types);
17897   gdb_assert (per_cu->cu == NULL);
17898
17899   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17900                            read_signatured_type_reader, NULL);
17901 }
17902
17903 /* Decode simple location descriptions.
17904    Given a pointer to a dwarf block that defines a location, compute
17905    the location and return the value.
17906
17907    NOTE drow/2003-11-18: This function is called in two situations
17908    now: for the address of static or global variables (partial symbols
17909    only) and for offsets into structures which are expected to be
17910    (more or less) constant.  The partial symbol case should go away,
17911    and only the constant case should remain.  That will let this
17912    function complain more accurately.  A few special modes are allowed
17913    without complaint for global variables (for instance, global
17914    register values and thread-local values).
17915
17916    A location description containing no operations indicates that the
17917    object is optimized out.  The return value is 0 for that case.
17918    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17919    callers will only want a very basic result and this can become a
17920    complaint.
17921
17922    Note that stack[0] is unused except as a default error return.  */
17923
17924 static CORE_ADDR
17925 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17926 {
17927   struct objfile *objfile = cu->objfile;
17928   size_t i;
17929   size_t size = blk->size;
17930   const gdb_byte *data = blk->data;
17931   CORE_ADDR stack[64];
17932   int stacki;
17933   unsigned int bytes_read, unsnd;
17934   gdb_byte op;
17935
17936   i = 0;
17937   stacki = 0;
17938   stack[stacki] = 0;
17939   stack[++stacki] = 0;
17940
17941   while (i < size)
17942     {
17943       op = data[i++];
17944       switch (op)
17945         {
17946         case DW_OP_lit0:
17947         case DW_OP_lit1:
17948         case DW_OP_lit2:
17949         case DW_OP_lit3:
17950         case DW_OP_lit4:
17951         case DW_OP_lit5:
17952         case DW_OP_lit6:
17953         case DW_OP_lit7:
17954         case DW_OP_lit8:
17955         case DW_OP_lit9:
17956         case DW_OP_lit10:
17957         case DW_OP_lit11:
17958         case DW_OP_lit12:
17959         case DW_OP_lit13:
17960         case DW_OP_lit14:
17961         case DW_OP_lit15:
17962         case DW_OP_lit16:
17963         case DW_OP_lit17:
17964         case DW_OP_lit18:
17965         case DW_OP_lit19:
17966         case DW_OP_lit20:
17967         case DW_OP_lit21:
17968         case DW_OP_lit22:
17969         case DW_OP_lit23:
17970         case DW_OP_lit24:
17971         case DW_OP_lit25:
17972         case DW_OP_lit26:
17973         case DW_OP_lit27:
17974         case DW_OP_lit28:
17975         case DW_OP_lit29:
17976         case DW_OP_lit30:
17977         case DW_OP_lit31:
17978           stack[++stacki] = op - DW_OP_lit0;
17979           break;
17980
17981         case DW_OP_reg0:
17982         case DW_OP_reg1:
17983         case DW_OP_reg2:
17984         case DW_OP_reg3:
17985         case DW_OP_reg4:
17986         case DW_OP_reg5:
17987         case DW_OP_reg6:
17988         case DW_OP_reg7:
17989         case DW_OP_reg8:
17990         case DW_OP_reg9:
17991         case DW_OP_reg10:
17992         case DW_OP_reg11:
17993         case DW_OP_reg12:
17994         case DW_OP_reg13:
17995         case DW_OP_reg14:
17996         case DW_OP_reg15:
17997         case DW_OP_reg16:
17998         case DW_OP_reg17:
17999         case DW_OP_reg18:
18000         case DW_OP_reg19:
18001         case DW_OP_reg20:
18002         case DW_OP_reg21:
18003         case DW_OP_reg22:
18004         case DW_OP_reg23:
18005         case DW_OP_reg24:
18006         case DW_OP_reg25:
18007         case DW_OP_reg26:
18008         case DW_OP_reg27:
18009         case DW_OP_reg28:
18010         case DW_OP_reg29:
18011         case DW_OP_reg30:
18012         case DW_OP_reg31:
18013           stack[++stacki] = op - DW_OP_reg0;
18014           if (i < size)
18015             dwarf2_complex_location_expr_complaint ();
18016           break;
18017
18018         case DW_OP_regx:
18019           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
18020           i += bytes_read;
18021           stack[++stacki] = unsnd;
18022           if (i < size)
18023             dwarf2_complex_location_expr_complaint ();
18024           break;
18025
18026         case DW_OP_addr:
18027           stack[++stacki] = read_address (objfile->obfd, &data[i],
18028                                           cu, &bytes_read);
18029           i += bytes_read;
18030           break;
18031
18032         case DW_OP_const1u:
18033           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
18034           i += 1;
18035           break;
18036
18037         case DW_OP_const1s:
18038           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
18039           i += 1;
18040           break;
18041
18042         case DW_OP_const2u:
18043           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
18044           i += 2;
18045           break;
18046
18047         case DW_OP_const2s:
18048           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
18049           i += 2;
18050           break;
18051
18052         case DW_OP_const4u:
18053           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
18054           i += 4;
18055           break;
18056
18057         case DW_OP_const4s:
18058           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
18059           i += 4;
18060           break;
18061
18062         case DW_OP_const8u:
18063           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
18064           i += 8;
18065           break;
18066
18067         case DW_OP_constu:
18068           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
18069                                                   &bytes_read);
18070           i += bytes_read;
18071           break;
18072
18073         case DW_OP_consts:
18074           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
18075           i += bytes_read;
18076           break;
18077
18078         case DW_OP_dup:
18079           stack[stacki + 1] = stack[stacki];
18080           stacki++;
18081           break;
18082
18083         case DW_OP_plus:
18084           stack[stacki - 1] += stack[stacki];
18085           stacki--;
18086           break;
18087
18088         case DW_OP_plus_uconst:
18089           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
18090                                                  &bytes_read);
18091           i += bytes_read;
18092           break;
18093
18094         case DW_OP_minus:
18095           stack[stacki - 1] -= stack[stacki];
18096           stacki--;
18097           break;
18098
18099         case DW_OP_deref:
18100           /* If we're not the last op, then we definitely can't encode
18101              this using GDB's address_class enum.  This is valid for partial
18102              global symbols, although the variable's address will be bogus
18103              in the psymtab.  */
18104           if (i < size)
18105             dwarf2_complex_location_expr_complaint ();
18106           break;
18107
18108         case DW_OP_GNU_push_tls_address:
18109           /* The top of the stack has the offset from the beginning
18110              of the thread control block at which the variable is located.  */
18111           /* Nothing should follow this operator, so the top of stack would
18112              be returned.  */
18113           /* This is valid for partial global symbols, but the variable's
18114              address will be bogus in the psymtab.  Make it always at least
18115              non-zero to not look as a variable garbage collected by linker
18116              which have DW_OP_addr 0.  */
18117           if (i < size)
18118             dwarf2_complex_location_expr_complaint ();
18119           stack[stacki]++;
18120           break;
18121
18122         case DW_OP_GNU_uninit:
18123           break;
18124
18125         case DW_OP_GNU_addr_index:
18126         case DW_OP_GNU_const_index:
18127           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
18128                                                          &bytes_read);
18129           i += bytes_read;
18130           break;
18131
18132         default:
18133           {
18134             const char *name = get_DW_OP_name (op);
18135
18136             if (name)
18137               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
18138                          name);
18139             else
18140               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
18141                          op);
18142           }
18143
18144           return (stack[stacki]);
18145         }
18146
18147       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18148          outside of the allocated space.  Also enforce minimum>0.  */
18149       if (stacki >= ARRAY_SIZE (stack) - 1)
18150         {
18151           complaint (&symfile_complaints,
18152                      _("location description stack overflow"));
18153           return 0;
18154         }
18155
18156       if (stacki <= 0)
18157         {
18158           complaint (&symfile_complaints,
18159                      _("location description stack underflow"));
18160           return 0;
18161         }
18162     }
18163   return (stack[stacki]);
18164 }
18165
18166 /* memory allocation interface */
18167
18168 static struct dwarf_block *
18169 dwarf_alloc_block (struct dwarf2_cu *cu)
18170 {
18171   struct dwarf_block *blk;
18172
18173   blk = (struct dwarf_block *)
18174     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18175   return (blk);
18176 }
18177
18178 static struct die_info *
18179 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18180 {
18181   struct die_info *die;
18182   size_t size = sizeof (struct die_info);
18183
18184   if (num_attrs > 1)
18185     size += (num_attrs - 1) * sizeof (struct attribute);
18186
18187   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18188   memset (die, 0, sizeof (struct die_info));
18189   return (die);
18190 }
18191
18192 \f
18193 /* Macro support.  */
18194
18195 /* Return file name relative to the compilation directory of file number I in
18196    *LH's file name table.  The result is allocated using xmalloc; the caller is
18197    responsible for freeing it.  */
18198
18199 static char *
18200 file_file_name (int file, struct line_header *lh)
18201 {
18202   /* Is the file number a valid index into the line header's file name
18203      table?  Remember that file numbers start with one, not zero.  */
18204   if (1 <= file && file <= lh->num_file_names)
18205     {
18206       struct file_entry *fe = &lh->file_names[file - 1];
18207
18208       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18209         return xstrdup (fe->name);
18210       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18211                      fe->name, NULL);
18212     }
18213   else
18214     {
18215       /* The compiler produced a bogus file number.  We can at least
18216          record the macro definitions made in the file, even if we
18217          won't be able to find the file by name.  */
18218       char fake_name[80];
18219
18220       xsnprintf (fake_name, sizeof (fake_name),
18221                  "<bad macro file number %d>", file);
18222
18223       complaint (&symfile_complaints,
18224                  _("bad file number in macro information (%d)"),
18225                  file);
18226
18227       return xstrdup (fake_name);
18228     }
18229 }
18230
18231 /* Return the full name of file number I in *LH's file name table.
18232    Use COMP_DIR as the name of the current directory of the
18233    compilation.  The result is allocated using xmalloc; the caller is
18234    responsible for freeing it.  */
18235 static char *
18236 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18237 {
18238   /* Is the file number a valid index into the line header's file name
18239      table?  Remember that file numbers start with one, not zero.  */
18240   if (1 <= file && file <= lh->num_file_names)
18241     {
18242       char *relative = file_file_name (file, lh);
18243
18244       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18245         return relative;
18246       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18247     }
18248   else
18249     return file_file_name (file, lh);
18250 }
18251
18252
18253 static struct macro_source_file *
18254 macro_start_file (int file, int line,
18255                   struct macro_source_file *current_file,
18256                   const char *comp_dir,
18257                   struct line_header *lh, struct objfile *objfile)
18258 {
18259   /* File name relative to the compilation directory of this source file.  */
18260   char *file_name = file_file_name (file, lh);
18261
18262   /* We don't create a macro table for this compilation unit
18263      at all until we actually get a filename.  */
18264   if (! pending_macros)
18265     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18266                                       objfile->per_bfd->macro_cache,
18267                                       comp_dir);
18268
18269   if (! current_file)
18270     {
18271       /* If we have no current file, then this must be the start_file
18272          directive for the compilation unit's main source file.  */
18273       current_file = macro_set_main (pending_macros, file_name);
18274       macro_define_special (pending_macros);
18275     }
18276   else
18277     current_file = macro_include (current_file, line, file_name);
18278
18279   xfree (file_name);
18280
18281   return current_file;
18282 }
18283
18284
18285 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18286    followed by a null byte.  */
18287 static char *
18288 copy_string (const char *buf, int len)
18289 {
18290   char *s = xmalloc (len + 1);
18291
18292   memcpy (s, buf, len);
18293   s[len] = '\0';
18294   return s;
18295 }
18296
18297
18298 static const char *
18299 consume_improper_spaces (const char *p, const char *body)
18300 {
18301   if (*p == ' ')
18302     {
18303       complaint (&symfile_complaints,
18304                  _("macro definition contains spaces "
18305                    "in formal argument list:\n`%s'"),
18306                  body);
18307
18308       while (*p == ' ')
18309         p++;
18310     }
18311
18312   return p;
18313 }
18314
18315
18316 static void
18317 parse_macro_definition (struct macro_source_file *file, int line,
18318                         const char *body)
18319 {
18320   const char *p;
18321
18322   /* The body string takes one of two forms.  For object-like macro
18323      definitions, it should be:
18324
18325         <macro name> " " <definition>
18326
18327      For function-like macro definitions, it should be:
18328
18329         <macro name> "() " <definition>
18330      or
18331         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18332
18333      Spaces may appear only where explicitly indicated, and in the
18334      <definition>.
18335
18336      The Dwarf 2 spec says that an object-like macro's name is always
18337      followed by a space, but versions of GCC around March 2002 omit
18338      the space when the macro's definition is the empty string.
18339
18340      The Dwarf 2 spec says that there should be no spaces between the
18341      formal arguments in a function-like macro's formal argument list,
18342      but versions of GCC around March 2002 include spaces after the
18343      commas.  */
18344
18345
18346   /* Find the extent of the macro name.  The macro name is terminated
18347      by either a space or null character (for an object-like macro) or
18348      an opening paren (for a function-like macro).  */
18349   for (p = body; *p; p++)
18350     if (*p == ' ' || *p == '(')
18351       break;
18352
18353   if (*p == ' ' || *p == '\0')
18354     {
18355       /* It's an object-like macro.  */
18356       int name_len = p - body;
18357       char *name = copy_string (body, name_len);
18358       const char *replacement;
18359
18360       if (*p == ' ')
18361         replacement = body + name_len + 1;
18362       else
18363         {
18364           dwarf2_macro_malformed_definition_complaint (body);
18365           replacement = body + name_len;
18366         }
18367
18368       macro_define_object (file, line, name, replacement);
18369
18370       xfree (name);
18371     }
18372   else if (*p == '(')
18373     {
18374       /* It's a function-like macro.  */
18375       char *name = copy_string (body, p - body);
18376       int argc = 0;
18377       int argv_size = 1;
18378       char **argv = xmalloc (argv_size * sizeof (*argv));
18379
18380       p++;
18381
18382       p = consume_improper_spaces (p, body);
18383
18384       /* Parse the formal argument list.  */
18385       while (*p && *p != ')')
18386         {
18387           /* Find the extent of the current argument name.  */
18388           const char *arg_start = p;
18389
18390           while (*p && *p != ',' && *p != ')' && *p != ' ')
18391             p++;
18392
18393           if (! *p || p == arg_start)
18394             dwarf2_macro_malformed_definition_complaint (body);
18395           else
18396             {
18397               /* Make sure argv has room for the new argument.  */
18398               if (argc >= argv_size)
18399                 {
18400                   argv_size *= 2;
18401                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18402                 }
18403
18404               argv[argc++] = copy_string (arg_start, p - arg_start);
18405             }
18406
18407           p = consume_improper_spaces (p, body);
18408
18409           /* Consume the comma, if present.  */
18410           if (*p == ',')
18411             {
18412               p++;
18413
18414               p = consume_improper_spaces (p, body);
18415             }
18416         }
18417
18418       if (*p == ')')
18419         {
18420           p++;
18421
18422           if (*p == ' ')
18423             /* Perfectly formed definition, no complaints.  */
18424             macro_define_function (file, line, name,
18425                                    argc, (const char **) argv,
18426                                    p + 1);
18427           else if (*p == '\0')
18428             {
18429               /* Complain, but do define it.  */
18430               dwarf2_macro_malformed_definition_complaint (body);
18431               macro_define_function (file, line, name,
18432                                      argc, (const char **) argv,
18433                                      p);
18434             }
18435           else
18436             /* Just complain.  */
18437             dwarf2_macro_malformed_definition_complaint (body);
18438         }
18439       else
18440         /* Just complain.  */
18441         dwarf2_macro_malformed_definition_complaint (body);
18442
18443       xfree (name);
18444       {
18445         int i;
18446
18447         for (i = 0; i < argc; i++)
18448           xfree (argv[i]);
18449       }
18450       xfree (argv);
18451     }
18452   else
18453     dwarf2_macro_malformed_definition_complaint (body);
18454 }
18455
18456 /* Skip some bytes from BYTES according to the form given in FORM.
18457    Returns the new pointer.  */
18458
18459 static const gdb_byte *
18460 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
18461                  enum dwarf_form form,
18462                  unsigned int offset_size,
18463                  struct dwarf2_section_info *section)
18464 {
18465   unsigned int bytes_read;
18466
18467   switch (form)
18468     {
18469     case DW_FORM_data1:
18470     case DW_FORM_flag:
18471       ++bytes;
18472       break;
18473
18474     case DW_FORM_data2:
18475       bytes += 2;
18476       break;
18477
18478     case DW_FORM_data4:
18479       bytes += 4;
18480       break;
18481
18482     case DW_FORM_data8:
18483       bytes += 8;
18484       break;
18485
18486     case DW_FORM_string:
18487       read_direct_string (abfd, bytes, &bytes_read);
18488       bytes += bytes_read;
18489       break;
18490
18491     case DW_FORM_sec_offset:
18492     case DW_FORM_strp:
18493     case DW_FORM_GNU_strp_alt:
18494       bytes += offset_size;
18495       break;
18496
18497     case DW_FORM_block:
18498       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18499       bytes += bytes_read;
18500       break;
18501
18502     case DW_FORM_block1:
18503       bytes += 1 + read_1_byte (abfd, bytes);
18504       break;
18505     case DW_FORM_block2:
18506       bytes += 2 + read_2_bytes (abfd, bytes);
18507       break;
18508     case DW_FORM_block4:
18509       bytes += 4 + read_4_bytes (abfd, bytes);
18510       break;
18511
18512     case DW_FORM_sdata:
18513     case DW_FORM_udata:
18514     case DW_FORM_GNU_addr_index:
18515     case DW_FORM_GNU_str_index:
18516       bytes = gdb_skip_leb128 (bytes, buffer_end);
18517       if (bytes == NULL)
18518         {
18519           dwarf2_section_buffer_overflow_complaint (section);
18520           return NULL;
18521         }
18522       break;
18523
18524     default:
18525       {
18526       complain:
18527         complaint (&symfile_complaints,
18528                    _("invalid form 0x%x in `%s'"),
18529                    form,
18530                    section->asection->name);
18531         return NULL;
18532       }
18533     }
18534
18535   return bytes;
18536 }
18537
18538 /* A helper for dwarf_decode_macros that handles skipping an unknown
18539    opcode.  Returns an updated pointer to the macro data buffer; or,
18540    on error, issues a complaint and returns NULL.  */
18541
18542 static const gdb_byte *
18543 skip_unknown_opcode (unsigned int opcode,
18544                      const gdb_byte **opcode_definitions,
18545                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
18546                      bfd *abfd,
18547                      unsigned int offset_size,
18548                      struct dwarf2_section_info *section)
18549 {
18550   unsigned int bytes_read, i;
18551   unsigned long arg;
18552   const gdb_byte *defn;
18553
18554   if (opcode_definitions[opcode] == NULL)
18555     {
18556       complaint (&symfile_complaints,
18557                  _("unrecognized DW_MACFINO opcode 0x%x"),
18558                  opcode);
18559       return NULL;
18560     }
18561
18562   defn = opcode_definitions[opcode];
18563   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18564   defn += bytes_read;
18565
18566   for (i = 0; i < arg; ++i)
18567     {
18568       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18569                                  section);
18570       if (mac_ptr == NULL)
18571         {
18572           /* skip_form_bytes already issued the complaint.  */
18573           return NULL;
18574         }
18575     }
18576
18577   return mac_ptr;
18578 }
18579
18580 /* A helper function which parses the header of a macro section.
18581    If the macro section is the extended (for now called "GNU") type,
18582    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18583    the header, or issues a complaint and returns NULL on error.  */
18584
18585 static const gdb_byte *
18586 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
18587                           bfd *abfd,
18588                           const gdb_byte *mac_ptr,
18589                           unsigned int *offset_size,
18590                           int section_is_gnu)
18591 {
18592   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18593
18594   if (section_is_gnu)
18595     {
18596       unsigned int version, flags;
18597
18598       version = read_2_bytes (abfd, mac_ptr);
18599       if (version != 4)
18600         {
18601           complaint (&symfile_complaints,
18602                      _("unrecognized version `%d' in .debug_macro section"),
18603                      version);
18604           return NULL;
18605         }
18606       mac_ptr += 2;
18607
18608       flags = read_1_byte (abfd, mac_ptr);
18609       ++mac_ptr;
18610       *offset_size = (flags & 1) ? 8 : 4;
18611
18612       if ((flags & 2) != 0)
18613         /* We don't need the line table offset.  */
18614         mac_ptr += *offset_size;
18615
18616       /* Vendor opcode descriptions.  */
18617       if ((flags & 4) != 0)
18618         {
18619           unsigned int i, count;
18620
18621           count = read_1_byte (abfd, mac_ptr);
18622           ++mac_ptr;
18623           for (i = 0; i < count; ++i)
18624             {
18625               unsigned int opcode, bytes_read;
18626               unsigned long arg;
18627
18628               opcode = read_1_byte (abfd, mac_ptr);
18629               ++mac_ptr;
18630               opcode_definitions[opcode] = mac_ptr;
18631               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18632               mac_ptr += bytes_read;
18633               mac_ptr += arg;
18634             }
18635         }
18636     }
18637
18638   return mac_ptr;
18639 }
18640
18641 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18642    including DW_MACRO_GNU_transparent_include.  */
18643
18644 static void
18645 dwarf_decode_macro_bytes (bfd *abfd,
18646                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
18647                           struct macro_source_file *current_file,
18648                           struct line_header *lh, const char *comp_dir,
18649                           struct dwarf2_section_info *section,
18650                           int section_is_gnu, int section_is_dwz,
18651                           unsigned int offset_size,
18652                           struct objfile *objfile,
18653                           htab_t include_hash)
18654 {
18655   enum dwarf_macro_record_type macinfo_type;
18656   int at_commandline;
18657   const gdb_byte *opcode_definitions[256];
18658
18659   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18660                                       &offset_size, section_is_gnu);
18661   if (mac_ptr == NULL)
18662     {
18663       /* We already issued a complaint.  */
18664       return;
18665     }
18666
18667   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18668      GDB is still reading the definitions from command line.  First
18669      DW_MACINFO_start_file will need to be ignored as it was already executed
18670      to create CURRENT_FILE for the main source holding also the command line
18671      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18672      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18673
18674   at_commandline = 1;
18675
18676   do
18677     {
18678       /* Do we at least have room for a macinfo type byte?  */
18679       if (mac_ptr >= mac_end)
18680         {
18681           dwarf2_section_buffer_overflow_complaint (section);
18682           break;
18683         }
18684
18685       macinfo_type = read_1_byte (abfd, mac_ptr);
18686       mac_ptr++;
18687
18688       /* Note that we rely on the fact that the corresponding GNU and
18689          DWARF constants are the same.  */
18690       switch (macinfo_type)
18691         {
18692           /* A zero macinfo type indicates the end of the macro
18693              information.  */
18694         case 0:
18695           break;
18696
18697         case DW_MACRO_GNU_define:
18698         case DW_MACRO_GNU_undef:
18699         case DW_MACRO_GNU_define_indirect:
18700         case DW_MACRO_GNU_undef_indirect:
18701         case DW_MACRO_GNU_define_indirect_alt:
18702         case DW_MACRO_GNU_undef_indirect_alt:
18703           {
18704             unsigned int bytes_read;
18705             int line;
18706             const char *body;
18707             int is_define;
18708
18709             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18710             mac_ptr += bytes_read;
18711
18712             if (macinfo_type == DW_MACRO_GNU_define
18713                 || macinfo_type == DW_MACRO_GNU_undef)
18714               {
18715                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18716                 mac_ptr += bytes_read;
18717               }
18718             else
18719               {
18720                 LONGEST str_offset;
18721
18722                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18723                 mac_ptr += offset_size;
18724
18725                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18726                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18727                     || section_is_dwz)
18728                   {
18729                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18730
18731                     body = read_indirect_string_from_dwz (dwz, str_offset);
18732                   }
18733                 else
18734                   body = read_indirect_string_at_offset (abfd, str_offset);
18735               }
18736
18737             is_define = (macinfo_type == DW_MACRO_GNU_define
18738                          || macinfo_type == DW_MACRO_GNU_define_indirect
18739                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18740             if (! current_file)
18741               {
18742                 /* DWARF violation as no main source is present.  */
18743                 complaint (&symfile_complaints,
18744                            _("debug info with no main source gives macro %s "
18745                              "on line %d: %s"),
18746                            is_define ? _("definition") : _("undefinition"),
18747                            line, body);
18748                 break;
18749               }
18750             if ((line == 0 && !at_commandline)
18751                 || (line != 0 && at_commandline))
18752               complaint (&symfile_complaints,
18753                          _("debug info gives %s macro %s with %s line %d: %s"),
18754                          at_commandline ? _("command-line") : _("in-file"),
18755                          is_define ? _("definition") : _("undefinition"),
18756                          line == 0 ? _("zero") : _("non-zero"), line, body);
18757
18758             if (is_define)
18759               parse_macro_definition (current_file, line, body);
18760             else
18761               {
18762                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18763                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18764                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18765                 macro_undef (current_file, line, body);
18766               }
18767           }
18768           break;
18769
18770         case DW_MACRO_GNU_start_file:
18771           {
18772             unsigned int bytes_read;
18773             int line, file;
18774
18775             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18776             mac_ptr += bytes_read;
18777             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18778             mac_ptr += bytes_read;
18779
18780             if ((line == 0 && !at_commandline)
18781                 || (line != 0 && at_commandline))
18782               complaint (&symfile_complaints,
18783                          _("debug info gives source %d included "
18784                            "from %s at %s line %d"),
18785                          file, at_commandline ? _("command-line") : _("file"),
18786                          line == 0 ? _("zero") : _("non-zero"), line);
18787
18788             if (at_commandline)
18789               {
18790                 /* This DW_MACRO_GNU_start_file was executed in the
18791                    pass one.  */
18792                 at_commandline = 0;
18793               }
18794             else
18795               current_file = macro_start_file (file, line,
18796                                                current_file, comp_dir,
18797                                                lh, objfile);
18798           }
18799           break;
18800
18801         case DW_MACRO_GNU_end_file:
18802           if (! current_file)
18803             complaint (&symfile_complaints,
18804                        _("macro debug info has an unmatched "
18805                          "`close_file' directive"));
18806           else
18807             {
18808               current_file = current_file->included_by;
18809               if (! current_file)
18810                 {
18811                   enum dwarf_macro_record_type next_type;
18812
18813                   /* GCC circa March 2002 doesn't produce the zero
18814                      type byte marking the end of the compilation
18815                      unit.  Complain if it's not there, but exit no
18816                      matter what.  */
18817
18818                   /* Do we at least have room for a macinfo type byte?  */
18819                   if (mac_ptr >= mac_end)
18820                     {
18821                       dwarf2_section_buffer_overflow_complaint (section);
18822                       return;
18823                     }
18824
18825                   /* We don't increment mac_ptr here, so this is just
18826                      a look-ahead.  */
18827                   next_type = read_1_byte (abfd, mac_ptr);
18828                   if (next_type != 0)
18829                     complaint (&symfile_complaints,
18830                                _("no terminating 0-type entry for "
18831                                  "macros in `.debug_macinfo' section"));
18832
18833                   return;
18834                 }
18835             }
18836           break;
18837
18838         case DW_MACRO_GNU_transparent_include:
18839         case DW_MACRO_GNU_transparent_include_alt:
18840           {
18841             LONGEST offset;
18842             void **slot;
18843             bfd *include_bfd = abfd;
18844             struct dwarf2_section_info *include_section = section;
18845             struct dwarf2_section_info alt_section;
18846             const gdb_byte *include_mac_end = mac_end;
18847             int is_dwz = section_is_dwz;
18848             const gdb_byte *new_mac_ptr;
18849
18850             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18851             mac_ptr += offset_size;
18852
18853             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18854               {
18855                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18856
18857                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18858                                      &dwz->macro);
18859
18860                 include_bfd = dwz->macro.asection->owner;
18861                 include_section = &dwz->macro;
18862                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18863                 is_dwz = 1;
18864               }
18865
18866             new_mac_ptr = include_section->buffer + offset;
18867             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18868
18869             if (*slot != NULL)
18870               {
18871                 /* This has actually happened; see
18872                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18873                 complaint (&symfile_complaints,
18874                            _("recursive DW_MACRO_GNU_transparent_include in "
18875                              ".debug_macro section"));
18876               }
18877             else
18878               {
18879                 *slot = (void *) new_mac_ptr;
18880
18881                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18882                                           include_mac_end, current_file,
18883                                           lh, comp_dir,
18884                                           section, section_is_gnu, is_dwz,
18885                                           offset_size, objfile, include_hash);
18886
18887                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
18888               }
18889           }
18890           break;
18891
18892         case DW_MACINFO_vendor_ext:
18893           if (!section_is_gnu)
18894             {
18895               unsigned int bytes_read;
18896               int constant;
18897
18898               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18899               mac_ptr += bytes_read;
18900               read_direct_string (abfd, mac_ptr, &bytes_read);
18901               mac_ptr += bytes_read;
18902
18903               /* We don't recognize any vendor extensions.  */
18904               break;
18905             }
18906           /* FALLTHROUGH */
18907
18908         default:
18909           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18910                                          mac_ptr, mac_end, abfd, offset_size,
18911                                          section);
18912           if (mac_ptr == NULL)
18913             return;
18914           break;
18915         }
18916     } while (macinfo_type != 0);
18917 }
18918
18919 static void
18920 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18921                      const char *comp_dir, int section_is_gnu)
18922 {
18923   struct objfile *objfile = dwarf2_per_objfile->objfile;
18924   struct line_header *lh = cu->line_header;
18925   bfd *abfd;
18926   const gdb_byte *mac_ptr, *mac_end;
18927   struct macro_source_file *current_file = 0;
18928   enum dwarf_macro_record_type macinfo_type;
18929   unsigned int offset_size = cu->header.offset_size;
18930   const gdb_byte *opcode_definitions[256];
18931   struct cleanup *cleanup;
18932   htab_t include_hash;
18933   void **slot;
18934   struct dwarf2_section_info *section;
18935   const char *section_name;
18936
18937   if (cu->dwo_unit != NULL)
18938     {
18939       if (section_is_gnu)
18940         {
18941           section = &cu->dwo_unit->dwo_file->sections.macro;
18942           section_name = ".debug_macro.dwo";
18943         }
18944       else
18945         {
18946           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18947           section_name = ".debug_macinfo.dwo";
18948         }
18949     }
18950   else
18951     {
18952       if (section_is_gnu)
18953         {
18954           section = &dwarf2_per_objfile->macro;
18955           section_name = ".debug_macro";
18956         }
18957       else
18958         {
18959           section = &dwarf2_per_objfile->macinfo;
18960           section_name = ".debug_macinfo";
18961         }
18962     }
18963
18964   dwarf2_read_section (objfile, section);
18965   if (section->buffer == NULL)
18966     {
18967       complaint (&symfile_complaints, _("missing %s section"), section_name);
18968       return;
18969     }
18970   abfd = section->asection->owner;
18971
18972   /* First pass: Find the name of the base filename.
18973      This filename is needed in order to process all macros whose definition
18974      (or undefinition) comes from the command line.  These macros are defined
18975      before the first DW_MACINFO_start_file entry, and yet still need to be
18976      associated to the base file.
18977
18978      To determine the base file name, we scan the macro definitions until we
18979      reach the first DW_MACINFO_start_file entry.  We then initialize
18980      CURRENT_FILE accordingly so that any macro definition found before the
18981      first DW_MACINFO_start_file can still be associated to the base file.  */
18982
18983   mac_ptr = section->buffer + offset;
18984   mac_end = section->buffer + section->size;
18985
18986   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18987                                       &offset_size, section_is_gnu);
18988   if (mac_ptr == NULL)
18989     {
18990       /* We already issued a complaint.  */
18991       return;
18992     }
18993
18994   do
18995     {
18996       /* Do we at least have room for a macinfo type byte?  */
18997       if (mac_ptr >= mac_end)
18998         {
18999           /* Complaint is printed during the second pass as GDB will probably
19000              stop the first pass earlier upon finding
19001              DW_MACINFO_start_file.  */
19002           break;
19003         }
19004
19005       macinfo_type = read_1_byte (abfd, mac_ptr);
19006       mac_ptr++;
19007
19008       /* Note that we rely on the fact that the corresponding GNU and
19009          DWARF constants are the same.  */
19010       switch (macinfo_type)
19011         {
19012           /* A zero macinfo type indicates the end of the macro
19013              information.  */
19014         case 0:
19015           break;
19016
19017         case DW_MACRO_GNU_define:
19018         case DW_MACRO_GNU_undef:
19019           /* Only skip the data by MAC_PTR.  */
19020           {
19021             unsigned int bytes_read;
19022
19023             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19024             mac_ptr += bytes_read;
19025             read_direct_string (abfd, mac_ptr, &bytes_read);
19026             mac_ptr += bytes_read;
19027           }
19028           break;
19029
19030         case DW_MACRO_GNU_start_file:
19031           {
19032             unsigned int bytes_read;
19033             int line, file;
19034
19035             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19036             mac_ptr += bytes_read;
19037             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19038             mac_ptr += bytes_read;
19039
19040             current_file = macro_start_file (file, line, current_file,
19041                                              comp_dir, lh, objfile);
19042           }
19043           break;
19044
19045         case DW_MACRO_GNU_end_file:
19046           /* No data to skip by MAC_PTR.  */
19047           break;
19048
19049         case DW_MACRO_GNU_define_indirect:
19050         case DW_MACRO_GNU_undef_indirect:
19051         case DW_MACRO_GNU_define_indirect_alt:
19052         case DW_MACRO_GNU_undef_indirect_alt:
19053           {
19054             unsigned int bytes_read;
19055
19056             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19057             mac_ptr += bytes_read;
19058             mac_ptr += offset_size;
19059           }
19060           break;
19061
19062         case DW_MACRO_GNU_transparent_include:
19063         case DW_MACRO_GNU_transparent_include_alt:
19064           /* Note that, according to the spec, a transparent include
19065              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
19066              skip this opcode.  */
19067           mac_ptr += offset_size;
19068           break;
19069
19070         case DW_MACINFO_vendor_ext:
19071           /* Only skip the data by MAC_PTR.  */
19072           if (!section_is_gnu)
19073             {
19074               unsigned int bytes_read;
19075
19076               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
19077               mac_ptr += bytes_read;
19078               read_direct_string (abfd, mac_ptr, &bytes_read);
19079               mac_ptr += bytes_read;
19080             }
19081           /* FALLTHROUGH */
19082
19083         default:
19084           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
19085                                          mac_ptr, mac_end, abfd, offset_size,
19086                                          section);
19087           if (mac_ptr == NULL)
19088             return;
19089           break;
19090         }
19091     } while (macinfo_type != 0 && current_file == NULL);
19092
19093   /* Second pass: Process all entries.
19094
19095      Use the AT_COMMAND_LINE flag to determine whether we are still processing
19096      command-line macro definitions/undefinitions.  This flag is unset when we
19097      reach the first DW_MACINFO_start_file entry.  */
19098
19099   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
19100                                     NULL, xcalloc, xfree);
19101   cleanup = make_cleanup_htab_delete (include_hash);
19102   mac_ptr = section->buffer + offset;
19103   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
19104   *slot = (void *) mac_ptr;
19105   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
19106                             current_file, lh, comp_dir, section,
19107                             section_is_gnu, 0,
19108                             offset_size, objfile, include_hash);
19109   do_cleanups (cleanup);
19110 }
19111
19112 /* Check if the attribute's form is a DW_FORM_block*
19113    if so return true else false.  */
19114
19115 static int
19116 attr_form_is_block (struct attribute *attr)
19117 {
19118   return (attr == NULL ? 0 :
19119       attr->form == DW_FORM_block1
19120       || attr->form == DW_FORM_block2
19121       || attr->form == DW_FORM_block4
19122       || attr->form == DW_FORM_block
19123       || attr->form == DW_FORM_exprloc);
19124 }
19125
19126 /* Return non-zero if ATTR's value is a section offset --- classes
19127    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
19128    You may use DW_UNSND (attr) to retrieve such offsets.
19129
19130    Section 7.5.4, "Attribute Encodings", explains that no attribute
19131    may have a value that belongs to more than one of these classes; it
19132    would be ambiguous if we did, because we use the same forms for all
19133    of them.  */
19134
19135 static int
19136 attr_form_is_section_offset (struct attribute *attr)
19137 {
19138   return (attr->form == DW_FORM_data4
19139           || attr->form == DW_FORM_data8
19140           || attr->form == DW_FORM_sec_offset);
19141 }
19142
19143 /* Return non-zero if ATTR's value falls in the 'constant' class, or
19144    zero otherwise.  When this function returns true, you can apply
19145    dwarf2_get_attr_constant_value to it.
19146
19147    However, note that for some attributes you must check
19148    attr_form_is_section_offset before using this test.  DW_FORM_data4
19149    and DW_FORM_data8 are members of both the constant class, and of
19150    the classes that contain offsets into other debug sections
19151    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19152    that, if an attribute's can be either a constant or one of the
19153    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19154    taken as section offsets, not constants.  */
19155
19156 static int
19157 attr_form_is_constant (struct attribute *attr)
19158 {
19159   switch (attr->form)
19160     {
19161     case DW_FORM_sdata:
19162     case DW_FORM_udata:
19163     case DW_FORM_data1:
19164     case DW_FORM_data2:
19165     case DW_FORM_data4:
19166     case DW_FORM_data8:
19167       return 1;
19168     default:
19169       return 0;
19170     }
19171 }
19172
19173 /* Return the .debug_loc section to use for CU.
19174    For DWO files use .debug_loc.dwo.  */
19175
19176 static struct dwarf2_section_info *
19177 cu_debug_loc_section (struct dwarf2_cu *cu)
19178 {
19179   if (cu->dwo_unit)
19180     return &cu->dwo_unit->dwo_file->sections.loc;
19181   return &dwarf2_per_objfile->loc;
19182 }
19183
19184 /* A helper function that fills in a dwarf2_loclist_baton.  */
19185
19186 static void
19187 fill_in_loclist_baton (struct dwarf2_cu *cu,
19188                        struct dwarf2_loclist_baton *baton,
19189                        struct attribute *attr)
19190 {
19191   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19192
19193   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19194
19195   baton->per_cu = cu->per_cu;
19196   gdb_assert (baton->per_cu);
19197   /* We don't know how long the location list is, but make sure we
19198      don't run off the edge of the section.  */
19199   baton->size = section->size - DW_UNSND (attr);
19200   baton->data = section->buffer + DW_UNSND (attr);
19201   baton->base_address = cu->base_address;
19202   baton->from_dwo = cu->dwo_unit != NULL;
19203 }
19204
19205 static void
19206 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19207                              struct dwarf2_cu *cu, int is_block)
19208 {
19209   struct objfile *objfile = dwarf2_per_objfile->objfile;
19210   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19211
19212   if (attr_form_is_section_offset (attr)
19213       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19214          the section.  If so, fall through to the complaint in the
19215          other branch.  */
19216       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19217     {
19218       struct dwarf2_loclist_baton *baton;
19219
19220       baton = obstack_alloc (&objfile->objfile_obstack,
19221                              sizeof (struct dwarf2_loclist_baton));
19222
19223       fill_in_loclist_baton (cu, baton, attr);
19224
19225       if (cu->base_known == 0)
19226         complaint (&symfile_complaints,
19227                    _("Location list used without "
19228                      "specifying the CU base address."));
19229
19230       SYMBOL_ACLASS_INDEX (sym) = (is_block
19231                                    ? dwarf2_loclist_block_index
19232                                    : dwarf2_loclist_index);
19233       SYMBOL_LOCATION_BATON (sym) = baton;
19234     }
19235   else
19236     {
19237       struct dwarf2_locexpr_baton *baton;
19238
19239       baton = obstack_alloc (&objfile->objfile_obstack,
19240                              sizeof (struct dwarf2_locexpr_baton));
19241       baton->per_cu = cu->per_cu;
19242       gdb_assert (baton->per_cu);
19243
19244       if (attr_form_is_block (attr))
19245         {
19246           /* Note that we're just copying the block's data pointer
19247              here, not the actual data.  We're still pointing into the
19248              info_buffer for SYM's objfile; right now we never release
19249              that buffer, but when we do clean up properly this may
19250              need to change.  */
19251           baton->size = DW_BLOCK (attr)->size;
19252           baton->data = DW_BLOCK (attr)->data;
19253         }
19254       else
19255         {
19256           dwarf2_invalid_attrib_class_complaint ("location description",
19257                                                  SYMBOL_NATURAL_NAME (sym));
19258           baton->size = 0;
19259         }
19260
19261       SYMBOL_ACLASS_INDEX (sym) = (is_block
19262                                    ? dwarf2_locexpr_block_index
19263                                    : dwarf2_locexpr_index);
19264       SYMBOL_LOCATION_BATON (sym) = baton;
19265     }
19266 }
19267
19268 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19269    came from a separate debuginfo file, then the master objfile is
19270    returned.  */
19271
19272 struct objfile *
19273 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19274 {
19275   struct objfile *objfile = per_cu->objfile;
19276
19277   /* Return the master objfile, so that we can report and look up the
19278      correct file containing this variable.  */
19279   if (objfile->separate_debug_objfile_backlink)
19280     objfile = objfile->separate_debug_objfile_backlink;
19281
19282   return objfile;
19283 }
19284
19285 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19286    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19287    CU_HEADERP first.  */
19288
19289 static const struct comp_unit_head *
19290 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19291                        struct dwarf2_per_cu_data *per_cu)
19292 {
19293   const gdb_byte *info_ptr;
19294
19295   if (per_cu->cu)
19296     return &per_cu->cu->header;
19297
19298   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
19299
19300   memset (cu_headerp, 0, sizeof (*cu_headerp));
19301   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19302
19303   return cu_headerp;
19304 }
19305
19306 /* Return the address size given in the compilation unit header for CU.  */
19307
19308 int
19309 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19310 {
19311   struct comp_unit_head cu_header_local;
19312   const struct comp_unit_head *cu_headerp;
19313
19314   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19315
19316   return cu_headerp->addr_size;
19317 }
19318
19319 /* Return the offset size given in the compilation unit header for CU.  */
19320
19321 int
19322 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19323 {
19324   struct comp_unit_head cu_header_local;
19325   const struct comp_unit_head *cu_headerp;
19326
19327   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19328
19329   return cu_headerp->offset_size;
19330 }
19331
19332 /* See its dwarf2loc.h declaration.  */
19333
19334 int
19335 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19336 {
19337   struct comp_unit_head cu_header_local;
19338   const struct comp_unit_head *cu_headerp;
19339
19340   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19341
19342   if (cu_headerp->version == 2)
19343     return cu_headerp->addr_size;
19344   else
19345     return cu_headerp->offset_size;
19346 }
19347
19348 /* Return the text offset of the CU.  The returned offset comes from
19349    this CU's objfile.  If this objfile came from a separate debuginfo
19350    file, then the offset may be different from the corresponding
19351    offset in the parent objfile.  */
19352
19353 CORE_ADDR
19354 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19355 {
19356   struct objfile *objfile = per_cu->objfile;
19357
19358   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19359 }
19360
19361 /* Locate the .debug_info compilation unit from CU's objfile which contains
19362    the DIE at OFFSET.  Raises an error on failure.  */
19363
19364 static struct dwarf2_per_cu_data *
19365 dwarf2_find_containing_comp_unit (sect_offset offset,
19366                                   unsigned int offset_in_dwz,
19367                                   struct objfile *objfile)
19368 {
19369   struct dwarf2_per_cu_data *this_cu;
19370   int low, high;
19371   const sect_offset *cu_off;
19372
19373   low = 0;
19374   high = dwarf2_per_objfile->n_comp_units - 1;
19375   while (high > low)
19376     {
19377       struct dwarf2_per_cu_data *mid_cu;
19378       int mid = low + (high - low) / 2;
19379
19380       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19381       cu_off = &mid_cu->offset;
19382       if (mid_cu->is_dwz > offset_in_dwz
19383           || (mid_cu->is_dwz == offset_in_dwz
19384               && cu_off->sect_off >= offset.sect_off))
19385         high = mid;
19386       else
19387         low = mid + 1;
19388     }
19389   gdb_assert (low == high);
19390   this_cu = dwarf2_per_objfile->all_comp_units[low];
19391   cu_off = &this_cu->offset;
19392   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19393     {
19394       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19395         error (_("Dwarf Error: could not find partial DIE containing "
19396                "offset 0x%lx [in module %s]"),
19397                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19398
19399       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19400                   <= offset.sect_off);
19401       return dwarf2_per_objfile->all_comp_units[low-1];
19402     }
19403   else
19404     {
19405       this_cu = dwarf2_per_objfile->all_comp_units[low];
19406       if (low == dwarf2_per_objfile->n_comp_units - 1
19407           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19408         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19409       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19410       return this_cu;
19411     }
19412 }
19413
19414 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19415
19416 static void
19417 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19418 {
19419   memset (cu, 0, sizeof (*cu));
19420   per_cu->cu = cu;
19421   cu->per_cu = per_cu;
19422   cu->objfile = per_cu->objfile;
19423   obstack_init (&cu->comp_unit_obstack);
19424 }
19425
19426 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19427
19428 static void
19429 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19430                        enum language pretend_language)
19431 {
19432   struct attribute *attr;
19433
19434   /* Set the language we're debugging.  */
19435   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19436   if (attr)
19437     set_cu_language (DW_UNSND (attr), cu);
19438   else
19439     {
19440       cu->language = pretend_language;
19441       cu->language_defn = language_def (cu->language);
19442     }
19443
19444   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19445   if (attr)
19446     cu->producer = DW_STRING (attr);
19447 }
19448
19449 /* Release one cached compilation unit, CU.  We unlink it from the tree
19450    of compilation units, but we don't remove it from the read_in_chain;
19451    the caller is responsible for that.
19452    NOTE: DATA is a void * because this function is also used as a
19453    cleanup routine.  */
19454
19455 static void
19456 free_heap_comp_unit (void *data)
19457 {
19458   struct dwarf2_cu *cu = data;
19459
19460   gdb_assert (cu->per_cu != NULL);
19461   cu->per_cu->cu = NULL;
19462   cu->per_cu = NULL;
19463
19464   obstack_free (&cu->comp_unit_obstack, NULL);
19465
19466   xfree (cu);
19467 }
19468
19469 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19470    when we're finished with it.  We can't free the pointer itself, but be
19471    sure to unlink it from the cache.  Also release any associated storage.  */
19472
19473 static void
19474 free_stack_comp_unit (void *data)
19475 {
19476   struct dwarf2_cu *cu = data;
19477
19478   gdb_assert (cu->per_cu != NULL);
19479   cu->per_cu->cu = NULL;
19480   cu->per_cu = NULL;
19481
19482   obstack_free (&cu->comp_unit_obstack, NULL);
19483   cu->partial_dies = NULL;
19484 }
19485
19486 /* Free all cached compilation units.  */
19487
19488 static void
19489 free_cached_comp_units (void *data)
19490 {
19491   struct dwarf2_per_cu_data *per_cu, **last_chain;
19492
19493   per_cu = dwarf2_per_objfile->read_in_chain;
19494   last_chain = &dwarf2_per_objfile->read_in_chain;
19495   while (per_cu != NULL)
19496     {
19497       struct dwarf2_per_cu_data *next_cu;
19498
19499       next_cu = per_cu->cu->read_in_chain;
19500
19501       free_heap_comp_unit (per_cu->cu);
19502       *last_chain = next_cu;
19503
19504       per_cu = next_cu;
19505     }
19506 }
19507
19508 /* Increase the age counter on each cached compilation unit, and free
19509    any that are too old.  */
19510
19511 static void
19512 age_cached_comp_units (void)
19513 {
19514   struct dwarf2_per_cu_data *per_cu, **last_chain;
19515
19516   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19517   per_cu = dwarf2_per_objfile->read_in_chain;
19518   while (per_cu != NULL)
19519     {
19520       per_cu->cu->last_used ++;
19521       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19522         dwarf2_mark (per_cu->cu);
19523       per_cu = per_cu->cu->read_in_chain;
19524     }
19525
19526   per_cu = dwarf2_per_objfile->read_in_chain;
19527   last_chain = &dwarf2_per_objfile->read_in_chain;
19528   while (per_cu != NULL)
19529     {
19530       struct dwarf2_per_cu_data *next_cu;
19531
19532       next_cu = per_cu->cu->read_in_chain;
19533
19534       if (!per_cu->cu->mark)
19535         {
19536           free_heap_comp_unit (per_cu->cu);
19537           *last_chain = next_cu;
19538         }
19539       else
19540         last_chain = &per_cu->cu->read_in_chain;
19541
19542       per_cu = next_cu;
19543     }
19544 }
19545
19546 /* Remove a single compilation unit from the cache.  */
19547
19548 static void
19549 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19550 {
19551   struct dwarf2_per_cu_data *per_cu, **last_chain;
19552
19553   per_cu = dwarf2_per_objfile->read_in_chain;
19554   last_chain = &dwarf2_per_objfile->read_in_chain;
19555   while (per_cu != NULL)
19556     {
19557       struct dwarf2_per_cu_data *next_cu;
19558
19559       next_cu = per_cu->cu->read_in_chain;
19560
19561       if (per_cu == target_per_cu)
19562         {
19563           free_heap_comp_unit (per_cu->cu);
19564           per_cu->cu = NULL;
19565           *last_chain = next_cu;
19566           break;
19567         }
19568       else
19569         last_chain = &per_cu->cu->read_in_chain;
19570
19571       per_cu = next_cu;
19572     }
19573 }
19574
19575 /* Release all extra memory associated with OBJFILE.  */
19576
19577 void
19578 dwarf2_free_objfile (struct objfile *objfile)
19579 {
19580   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19581
19582   if (dwarf2_per_objfile == NULL)
19583     return;
19584
19585   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19586   free_cached_comp_units (NULL);
19587
19588   if (dwarf2_per_objfile->quick_file_names_table)
19589     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19590
19591   /* Everything else should be on the objfile obstack.  */
19592 }
19593
19594 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19595    We store these in a hash table separate from the DIEs, and preserve them
19596    when the DIEs are flushed out of cache.
19597
19598    The CU "per_cu" pointer is needed because offset alone is not enough to
19599    uniquely identify the type.  A file may have multiple .debug_types sections,
19600    or the type may come from a DWO file.  Furthermore, while it's more logical
19601    to use per_cu->section+offset, with Fission the section with the data is in
19602    the DWO file but we don't know that section at the point we need it.
19603    We have to use something in dwarf2_per_cu_data (or the pointer to it)
19604    because we can enter the lookup routine, get_die_type_at_offset, from
19605    outside this file, and thus won't necessarily have PER_CU->cu.
19606    Fortunately, PER_CU is stable for the life of the objfile.  */
19607
19608 struct dwarf2_per_cu_offset_and_type
19609 {
19610   const struct dwarf2_per_cu_data *per_cu;
19611   sect_offset offset;
19612   struct type *type;
19613 };
19614
19615 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19616
19617 static hashval_t
19618 per_cu_offset_and_type_hash (const void *item)
19619 {
19620   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19621
19622   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19623 }
19624
19625 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19626
19627 static int
19628 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19629 {
19630   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19631   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19632
19633   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19634           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19635 }
19636
19637 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19638    table if necessary.  For convenience, return TYPE.
19639
19640    The DIEs reading must have careful ordering to:
19641     * Not cause infite loops trying to read in DIEs as a prerequisite for
19642       reading current DIE.
19643     * Not trying to dereference contents of still incompletely read in types
19644       while reading in other DIEs.
19645     * Enable referencing still incompletely read in types just by a pointer to
19646       the type without accessing its fields.
19647
19648    Therefore caller should follow these rules:
19649      * Try to fetch any prerequisite types we may need to build this DIE type
19650        before building the type and calling set_die_type.
19651      * After building type call set_die_type for current DIE as soon as
19652        possible before fetching more types to complete the current type.
19653      * Make the type as complete as possible before fetching more types.  */
19654
19655 static struct type *
19656 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19657 {
19658   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19659   struct objfile *objfile = cu->objfile;
19660
19661   /* For Ada types, make sure that the gnat-specific data is always
19662      initialized (if not already set).  There are a few types where
19663      we should not be doing so, because the type-specific area is
19664      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19665      where the type-specific area is used to store the floatformat).
19666      But this is not a problem, because the gnat-specific information
19667      is actually not needed for these types.  */
19668   if (need_gnat_info (cu)
19669       && TYPE_CODE (type) != TYPE_CODE_FUNC
19670       && TYPE_CODE (type) != TYPE_CODE_FLT
19671       && !HAVE_GNAT_AUX_INFO (type))
19672     INIT_GNAT_SPECIFIC (type);
19673
19674   if (dwarf2_per_objfile->die_type_hash == NULL)
19675     {
19676       dwarf2_per_objfile->die_type_hash =
19677         htab_create_alloc_ex (127,
19678                               per_cu_offset_and_type_hash,
19679                               per_cu_offset_and_type_eq,
19680                               NULL,
19681                               &objfile->objfile_obstack,
19682                               hashtab_obstack_allocate,
19683                               dummy_obstack_deallocate);
19684     }
19685
19686   ofs.per_cu = cu->per_cu;
19687   ofs.offset = die->offset;
19688   ofs.type = type;
19689   slot = (struct dwarf2_per_cu_offset_and_type **)
19690     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19691   if (*slot)
19692     complaint (&symfile_complaints,
19693                _("A problem internal to GDB: DIE 0x%x has type already set"),
19694                die->offset.sect_off);
19695   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19696   **slot = ofs;
19697   return type;
19698 }
19699
19700 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
19701    or return NULL if the die does not have a saved type.  */
19702
19703 static struct type *
19704 get_die_type_at_offset (sect_offset offset,
19705                         struct dwarf2_per_cu_data *per_cu)
19706 {
19707   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19708
19709   if (dwarf2_per_objfile->die_type_hash == NULL)
19710     return NULL;
19711
19712   ofs.per_cu = per_cu;
19713   ofs.offset = offset;
19714   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19715   if (slot)
19716     return slot->type;
19717   else
19718     return NULL;
19719 }
19720
19721 /* Look up the type for DIE in CU in die_type_hash,
19722    or return NULL if DIE does not have a saved type.  */
19723
19724 static struct type *
19725 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19726 {
19727   return get_die_type_at_offset (die->offset, cu->per_cu);
19728 }
19729
19730 /* Add a dependence relationship from CU to REF_PER_CU.  */
19731
19732 static void
19733 dwarf2_add_dependence (struct dwarf2_cu *cu,
19734                        struct dwarf2_per_cu_data *ref_per_cu)
19735 {
19736   void **slot;
19737
19738   if (cu->dependencies == NULL)
19739     cu->dependencies
19740       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19741                               NULL, &cu->comp_unit_obstack,
19742                               hashtab_obstack_allocate,
19743                               dummy_obstack_deallocate);
19744
19745   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19746   if (*slot == NULL)
19747     *slot = ref_per_cu;
19748 }
19749
19750 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19751    Set the mark field in every compilation unit in the
19752    cache that we must keep because we are keeping CU.  */
19753
19754 static int
19755 dwarf2_mark_helper (void **slot, void *data)
19756 {
19757   struct dwarf2_per_cu_data *per_cu;
19758
19759   per_cu = (struct dwarf2_per_cu_data *) *slot;
19760
19761   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19762      reading of the chain.  As such dependencies remain valid it is not much
19763      useful to track and undo them during QUIT cleanups.  */
19764   if (per_cu->cu == NULL)
19765     return 1;
19766
19767   if (per_cu->cu->mark)
19768     return 1;
19769   per_cu->cu->mark = 1;
19770
19771   if (per_cu->cu->dependencies != NULL)
19772     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19773
19774   return 1;
19775 }
19776
19777 /* Set the mark field in CU and in every other compilation unit in the
19778    cache that we must keep because we are keeping CU.  */
19779
19780 static void
19781 dwarf2_mark (struct dwarf2_cu *cu)
19782 {
19783   if (cu->mark)
19784     return;
19785   cu->mark = 1;
19786   if (cu->dependencies != NULL)
19787     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19788 }
19789
19790 static void
19791 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19792 {
19793   while (per_cu)
19794     {
19795       per_cu->cu->mark = 0;
19796       per_cu = per_cu->cu->read_in_chain;
19797     }
19798 }
19799
19800 /* Trivial hash function for partial_die_info: the hash value of a DIE
19801    is its offset in .debug_info for this objfile.  */
19802
19803 static hashval_t
19804 partial_die_hash (const void *item)
19805 {
19806   const struct partial_die_info *part_die = item;
19807
19808   return part_die->offset.sect_off;
19809 }
19810
19811 /* Trivial comparison function for partial_die_info structures: two DIEs
19812    are equal if they have the same offset.  */
19813
19814 static int
19815 partial_die_eq (const void *item_lhs, const void *item_rhs)
19816 {
19817   const struct partial_die_info *part_die_lhs = item_lhs;
19818   const struct partial_die_info *part_die_rhs = item_rhs;
19819
19820   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19821 }
19822
19823 static struct cmd_list_element *set_dwarf2_cmdlist;
19824 static struct cmd_list_element *show_dwarf2_cmdlist;
19825
19826 static void
19827 set_dwarf2_cmd (char *args, int from_tty)
19828 {
19829   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19830 }
19831
19832 static void
19833 show_dwarf2_cmd (char *args, int from_tty)
19834 {
19835   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19836 }
19837
19838 /* Free data associated with OBJFILE, if necessary.  */
19839
19840 static void
19841 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19842 {
19843   struct dwarf2_per_objfile *data = d;
19844   int ix;
19845
19846   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19847     VEC_free (dwarf2_per_cu_ptr,
19848               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19849
19850   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19851     VEC_free (dwarf2_per_cu_ptr,
19852               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19853
19854   VEC_free (dwarf2_section_info_def, data->types);
19855
19856   if (data->dwo_files)
19857     free_dwo_files (data->dwo_files, objfile);
19858   if (data->dwp_file)
19859     gdb_bfd_unref (data->dwp_file->dbfd);
19860
19861   if (data->dwz_file && data->dwz_file->dwz_bfd)
19862     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19863 }
19864
19865 \f
19866 /* The "save gdb-index" command.  */
19867
19868 /* The contents of the hash table we create when building the string
19869    table.  */
19870 struct strtab_entry
19871 {
19872   offset_type offset;
19873   const char *str;
19874 };
19875
19876 /* Hash function for a strtab_entry.
19877
19878    Function is used only during write_hash_table so no index format backward
19879    compatibility is needed.  */
19880
19881 static hashval_t
19882 hash_strtab_entry (const void *e)
19883 {
19884   const struct strtab_entry *entry = e;
19885   return mapped_index_string_hash (INT_MAX, entry->str);
19886 }
19887
19888 /* Equality function for a strtab_entry.  */
19889
19890 static int
19891 eq_strtab_entry (const void *a, const void *b)
19892 {
19893   const struct strtab_entry *ea = a;
19894   const struct strtab_entry *eb = b;
19895   return !strcmp (ea->str, eb->str);
19896 }
19897
19898 /* Create a strtab_entry hash table.  */
19899
19900 static htab_t
19901 create_strtab (void)
19902 {
19903   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19904                             xfree, xcalloc, xfree);
19905 }
19906
19907 /* Add a string to the constant pool.  Return the string's offset in
19908    host order.  */
19909
19910 static offset_type
19911 add_string (htab_t table, struct obstack *cpool, const char *str)
19912 {
19913   void **slot;
19914   struct strtab_entry entry;
19915   struct strtab_entry *result;
19916
19917   entry.str = str;
19918   slot = htab_find_slot (table, &entry, INSERT);
19919   if (*slot)
19920     result = *slot;
19921   else
19922     {
19923       result = XNEW (struct strtab_entry);
19924       result->offset = obstack_object_size (cpool);
19925       result->str = str;
19926       obstack_grow_str0 (cpool, str);
19927       *slot = result;
19928     }
19929   return result->offset;
19930 }
19931
19932 /* An entry in the symbol table.  */
19933 struct symtab_index_entry
19934 {
19935   /* The name of the symbol.  */
19936   const char *name;
19937   /* The offset of the name in the constant pool.  */
19938   offset_type index_offset;
19939   /* A sorted vector of the indices of all the CUs that hold an object
19940      of this name.  */
19941   VEC (offset_type) *cu_indices;
19942 };
19943
19944 /* The symbol table.  This is a power-of-2-sized hash table.  */
19945 struct mapped_symtab
19946 {
19947   offset_type n_elements;
19948   offset_type size;
19949   struct symtab_index_entry **data;
19950 };
19951
19952 /* Hash function for a symtab_index_entry.  */
19953
19954 static hashval_t
19955 hash_symtab_entry (const void *e)
19956 {
19957   const struct symtab_index_entry *entry = e;
19958   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19959                          sizeof (offset_type) * VEC_length (offset_type,
19960                                                             entry->cu_indices),
19961                          0);
19962 }
19963
19964 /* Equality function for a symtab_index_entry.  */
19965
19966 static int
19967 eq_symtab_entry (const void *a, const void *b)
19968 {
19969   const struct symtab_index_entry *ea = a;
19970   const struct symtab_index_entry *eb = b;
19971   int len = VEC_length (offset_type, ea->cu_indices);
19972   if (len != VEC_length (offset_type, eb->cu_indices))
19973     return 0;
19974   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19975                   VEC_address (offset_type, eb->cu_indices),
19976                   sizeof (offset_type) * len);
19977 }
19978
19979 /* Destroy a symtab_index_entry.  */
19980
19981 static void
19982 delete_symtab_entry (void *p)
19983 {
19984   struct symtab_index_entry *entry = p;
19985   VEC_free (offset_type, entry->cu_indices);
19986   xfree (entry);
19987 }
19988
19989 /* Create a hash table holding symtab_index_entry objects.  */
19990
19991 static htab_t
19992 create_symbol_hash_table (void)
19993 {
19994   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19995                             delete_symtab_entry, xcalloc, xfree);
19996 }
19997
19998 /* Create a new mapped symtab object.  */
19999
20000 static struct mapped_symtab *
20001 create_mapped_symtab (void)
20002 {
20003   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
20004   symtab->n_elements = 0;
20005   symtab->size = 1024;
20006   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20007   return symtab;
20008 }
20009
20010 /* Destroy a mapped_symtab.  */
20011
20012 static void
20013 cleanup_mapped_symtab (void *p)
20014 {
20015   struct mapped_symtab *symtab = p;
20016   /* The contents of the array are freed when the other hash table is
20017      destroyed.  */
20018   xfree (symtab->data);
20019   xfree (symtab);
20020 }
20021
20022 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
20023    the slot.
20024    
20025    Function is used only during write_hash_table so no index format backward
20026    compatibility is needed.  */
20027
20028 static struct symtab_index_entry **
20029 find_slot (struct mapped_symtab *symtab, const char *name)
20030 {
20031   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
20032
20033   index = hash & (symtab->size - 1);
20034   step = ((hash * 17) & (symtab->size - 1)) | 1;
20035
20036   for (;;)
20037     {
20038       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
20039         return &symtab->data[index];
20040       index = (index + step) & (symtab->size - 1);
20041     }
20042 }
20043
20044 /* Expand SYMTAB's hash table.  */
20045
20046 static void
20047 hash_expand (struct mapped_symtab *symtab)
20048 {
20049   offset_type old_size = symtab->size;
20050   offset_type i;
20051   struct symtab_index_entry **old_entries = symtab->data;
20052
20053   symtab->size *= 2;
20054   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
20055
20056   for (i = 0; i < old_size; ++i)
20057     {
20058       if (old_entries[i])
20059         {
20060           struct symtab_index_entry **slot = find_slot (symtab,
20061                                                         old_entries[i]->name);
20062           *slot = old_entries[i];
20063         }
20064     }
20065
20066   xfree (old_entries);
20067 }
20068
20069 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
20070    CU_INDEX is the index of the CU in which the symbol appears.
20071    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
20072
20073 static void
20074 add_index_entry (struct mapped_symtab *symtab, const char *name,
20075                  int is_static, gdb_index_symbol_kind kind,
20076                  offset_type cu_index)
20077 {
20078   struct symtab_index_entry **slot;
20079   offset_type cu_index_and_attrs;
20080
20081   ++symtab->n_elements;
20082   if (4 * symtab->n_elements / 3 >= symtab->size)
20083     hash_expand (symtab);
20084
20085   slot = find_slot (symtab, name);
20086   if (!*slot)
20087     {
20088       *slot = XNEW (struct symtab_index_entry);
20089       (*slot)->name = name;
20090       /* index_offset is set later.  */
20091       (*slot)->cu_indices = NULL;
20092     }
20093
20094   cu_index_and_attrs = 0;
20095   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
20096   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
20097   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
20098
20099   /* We don't want to record an index value twice as we want to avoid the
20100      duplication.
20101      We process all global symbols and then all static symbols
20102      (which would allow us to avoid the duplication by only having to check
20103      the last entry pushed), but a symbol could have multiple kinds in one CU.
20104      To keep things simple we don't worry about the duplication here and
20105      sort and uniqufy the list after we've processed all symbols.  */
20106   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
20107 }
20108
20109 /* qsort helper routine for uniquify_cu_indices.  */
20110
20111 static int
20112 offset_type_compare (const void *ap, const void *bp)
20113 {
20114   offset_type a = *(offset_type *) ap;
20115   offset_type b = *(offset_type *) bp;
20116
20117   return (a > b) - (b > a);
20118 }
20119
20120 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
20121
20122 static void
20123 uniquify_cu_indices (struct mapped_symtab *symtab)
20124 {
20125   int i;
20126
20127   for (i = 0; i < symtab->size; ++i)
20128     {
20129       struct symtab_index_entry *entry = symtab->data[i];
20130
20131       if (entry
20132           && entry->cu_indices != NULL)
20133         {
20134           unsigned int next_to_insert, next_to_check;
20135           offset_type last_value;
20136
20137           qsort (VEC_address (offset_type, entry->cu_indices),
20138                  VEC_length (offset_type, entry->cu_indices),
20139                  sizeof (offset_type), offset_type_compare);
20140
20141           last_value = VEC_index (offset_type, entry->cu_indices, 0);
20142           next_to_insert = 1;
20143           for (next_to_check = 1;
20144                next_to_check < VEC_length (offset_type, entry->cu_indices);
20145                ++next_to_check)
20146             {
20147               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
20148                   != last_value)
20149                 {
20150                   last_value = VEC_index (offset_type, entry->cu_indices,
20151                                           next_to_check);
20152                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20153                                last_value);
20154                   ++next_to_insert;
20155                 }
20156             }
20157           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20158         }
20159     }
20160 }
20161
20162 /* Add a vector of indices to the constant pool.  */
20163
20164 static offset_type
20165 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20166                       struct symtab_index_entry *entry)
20167 {
20168   void **slot;
20169
20170   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20171   if (!*slot)
20172     {
20173       offset_type len = VEC_length (offset_type, entry->cu_indices);
20174       offset_type val = MAYBE_SWAP (len);
20175       offset_type iter;
20176       int i;
20177
20178       *slot = entry;
20179       entry->index_offset = obstack_object_size (cpool);
20180
20181       obstack_grow (cpool, &val, sizeof (val));
20182       for (i = 0;
20183            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20184            ++i)
20185         {
20186           val = MAYBE_SWAP (iter);
20187           obstack_grow (cpool, &val, sizeof (val));
20188         }
20189     }
20190   else
20191     {
20192       struct symtab_index_entry *old_entry = *slot;
20193       entry->index_offset = old_entry->index_offset;
20194       entry = old_entry;
20195     }
20196   return entry->index_offset;
20197 }
20198
20199 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20200    constant pool entries going into the obstack CPOOL.  */
20201
20202 static void
20203 write_hash_table (struct mapped_symtab *symtab,
20204                   struct obstack *output, struct obstack *cpool)
20205 {
20206   offset_type i;
20207   htab_t symbol_hash_table;
20208   htab_t str_table;
20209
20210   symbol_hash_table = create_symbol_hash_table ();
20211   str_table = create_strtab ();
20212
20213   /* We add all the index vectors to the constant pool first, to
20214      ensure alignment is ok.  */
20215   for (i = 0; i < symtab->size; ++i)
20216     {
20217       if (symtab->data[i])
20218         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20219     }
20220
20221   /* Now write out the hash table.  */
20222   for (i = 0; i < symtab->size; ++i)
20223     {
20224       offset_type str_off, vec_off;
20225
20226       if (symtab->data[i])
20227         {
20228           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20229           vec_off = symtab->data[i]->index_offset;
20230         }
20231       else
20232         {
20233           /* While 0 is a valid constant pool index, it is not valid
20234              to have 0 for both offsets.  */
20235           str_off = 0;
20236           vec_off = 0;
20237         }
20238
20239       str_off = MAYBE_SWAP (str_off);
20240       vec_off = MAYBE_SWAP (vec_off);
20241
20242       obstack_grow (output, &str_off, sizeof (str_off));
20243       obstack_grow (output, &vec_off, sizeof (vec_off));
20244     }
20245
20246   htab_delete (str_table);
20247   htab_delete (symbol_hash_table);
20248 }
20249
20250 /* Struct to map psymtab to CU index in the index file.  */
20251 struct psymtab_cu_index_map
20252 {
20253   struct partial_symtab *psymtab;
20254   unsigned int cu_index;
20255 };
20256
20257 static hashval_t
20258 hash_psymtab_cu_index (const void *item)
20259 {
20260   const struct psymtab_cu_index_map *map = item;
20261
20262   return htab_hash_pointer (map->psymtab);
20263 }
20264
20265 static int
20266 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20267 {
20268   const struct psymtab_cu_index_map *lhs = item_lhs;
20269   const struct psymtab_cu_index_map *rhs = item_rhs;
20270
20271   return lhs->psymtab == rhs->psymtab;
20272 }
20273
20274 /* Helper struct for building the address table.  */
20275 struct addrmap_index_data
20276 {
20277   struct objfile *objfile;
20278   struct obstack *addr_obstack;
20279   htab_t cu_index_htab;
20280
20281   /* Non-zero if the previous_* fields are valid.
20282      We can't write an entry until we see the next entry (since it is only then
20283      that we know the end of the entry).  */
20284   int previous_valid;
20285   /* Index of the CU in the table of all CUs in the index file.  */
20286   unsigned int previous_cu_index;
20287   /* Start address of the CU.  */
20288   CORE_ADDR previous_cu_start;
20289 };
20290
20291 /* Write an address entry to OBSTACK.  */
20292
20293 static void
20294 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20295                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20296 {
20297   offset_type cu_index_to_write;
20298   char addr[8];
20299   CORE_ADDR baseaddr;
20300
20301   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20302
20303   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20304   obstack_grow (obstack, addr, 8);
20305   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20306   obstack_grow (obstack, addr, 8);
20307   cu_index_to_write = MAYBE_SWAP (cu_index);
20308   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20309 }
20310
20311 /* Worker function for traversing an addrmap to build the address table.  */
20312
20313 static int
20314 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20315 {
20316   struct addrmap_index_data *data = datap;
20317   struct partial_symtab *pst = obj;
20318
20319   if (data->previous_valid)
20320     add_address_entry (data->objfile, data->addr_obstack,
20321                        data->previous_cu_start, start_addr,
20322                        data->previous_cu_index);
20323
20324   data->previous_cu_start = start_addr;
20325   if (pst != NULL)
20326     {
20327       struct psymtab_cu_index_map find_map, *map;
20328       find_map.psymtab = pst;
20329       map = htab_find (data->cu_index_htab, &find_map);
20330       gdb_assert (map != NULL);
20331       data->previous_cu_index = map->cu_index;
20332       data->previous_valid = 1;
20333     }
20334   else
20335       data->previous_valid = 0;
20336
20337   return 0;
20338 }
20339
20340 /* Write OBJFILE's address map to OBSTACK.
20341    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20342    in the index file.  */
20343
20344 static void
20345 write_address_map (struct objfile *objfile, struct obstack *obstack,
20346                    htab_t cu_index_htab)
20347 {
20348   struct addrmap_index_data addrmap_index_data;
20349
20350   /* When writing the address table, we have to cope with the fact that
20351      the addrmap iterator only provides the start of a region; we have to
20352      wait until the next invocation to get the start of the next region.  */
20353
20354   addrmap_index_data.objfile = objfile;
20355   addrmap_index_data.addr_obstack = obstack;
20356   addrmap_index_data.cu_index_htab = cu_index_htab;
20357   addrmap_index_data.previous_valid = 0;
20358
20359   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20360                    &addrmap_index_data);
20361
20362   /* It's highly unlikely the last entry (end address = 0xff...ff)
20363      is valid, but we should still handle it.
20364      The end address is recorded as the start of the next region, but that
20365      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20366      anyway.  */
20367   if (addrmap_index_data.previous_valid)
20368     add_address_entry (objfile, obstack,
20369                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20370                        addrmap_index_data.previous_cu_index);
20371 }
20372
20373 /* Return the symbol kind of PSYM.  */
20374
20375 static gdb_index_symbol_kind
20376 symbol_kind (struct partial_symbol *psym)
20377 {
20378   domain_enum domain = PSYMBOL_DOMAIN (psym);
20379   enum address_class aclass = PSYMBOL_CLASS (psym);
20380
20381   switch (domain)
20382     {
20383     case VAR_DOMAIN:
20384       switch (aclass)
20385         {
20386         case LOC_BLOCK:
20387           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20388         case LOC_TYPEDEF:
20389           return GDB_INDEX_SYMBOL_KIND_TYPE;
20390         case LOC_COMPUTED:
20391         case LOC_CONST_BYTES:
20392         case LOC_OPTIMIZED_OUT:
20393         case LOC_STATIC:
20394           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20395         case LOC_CONST:
20396           /* Note: It's currently impossible to recognize psyms as enum values
20397              short of reading the type info.  For now punt.  */
20398           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20399         default:
20400           /* There are other LOC_FOO values that one might want to classify
20401              as variables, but dwarf2read.c doesn't currently use them.  */
20402           return GDB_INDEX_SYMBOL_KIND_OTHER;
20403         }
20404     case STRUCT_DOMAIN:
20405       return GDB_INDEX_SYMBOL_KIND_TYPE;
20406     default:
20407       return GDB_INDEX_SYMBOL_KIND_OTHER;
20408     }
20409 }
20410
20411 /* Add a list of partial symbols to SYMTAB.  */
20412
20413 static void
20414 write_psymbols (struct mapped_symtab *symtab,
20415                 htab_t psyms_seen,
20416                 struct partial_symbol **psymp,
20417                 int count,
20418                 offset_type cu_index,
20419                 int is_static)
20420 {
20421   for (; count-- > 0; ++psymp)
20422     {
20423       struct partial_symbol *psym = *psymp;
20424       void **slot;
20425
20426       if (SYMBOL_LANGUAGE (psym) == language_ada)
20427         error (_("Ada is not currently supported by the index"));
20428
20429       /* Only add a given psymbol once.  */
20430       slot = htab_find_slot (psyms_seen, psym, INSERT);
20431       if (!*slot)
20432         {
20433           gdb_index_symbol_kind kind = symbol_kind (psym);
20434
20435           *slot = psym;
20436           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20437                            is_static, kind, cu_index);
20438         }
20439     }
20440 }
20441
20442 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20443    exception if there is an error.  */
20444
20445 static void
20446 write_obstack (FILE *file, struct obstack *obstack)
20447 {
20448   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20449               file)
20450       != obstack_object_size (obstack))
20451     error (_("couldn't data write to file"));
20452 }
20453
20454 /* Unlink a file if the argument is not NULL.  */
20455
20456 static void
20457 unlink_if_set (void *p)
20458 {
20459   char **filename = p;
20460   if (*filename)
20461     unlink (*filename);
20462 }
20463
20464 /* A helper struct used when iterating over debug_types.  */
20465 struct signatured_type_index_data
20466 {
20467   struct objfile *objfile;
20468   struct mapped_symtab *symtab;
20469   struct obstack *types_list;
20470   htab_t psyms_seen;
20471   int cu_index;
20472 };
20473
20474 /* A helper function that writes a single signatured_type to an
20475    obstack.  */
20476
20477 static int
20478 write_one_signatured_type (void **slot, void *d)
20479 {
20480   struct signatured_type_index_data *info = d;
20481   struct signatured_type *entry = (struct signatured_type *) *slot;
20482   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
20483   gdb_byte val[8];
20484
20485   write_psymbols (info->symtab,
20486                   info->psyms_seen,
20487                   info->objfile->global_psymbols.list
20488                   + psymtab->globals_offset,
20489                   psymtab->n_global_syms, info->cu_index,
20490                   0);
20491   write_psymbols (info->symtab,
20492                   info->psyms_seen,
20493                   info->objfile->static_psymbols.list
20494                   + psymtab->statics_offset,
20495                   psymtab->n_static_syms, info->cu_index,
20496                   1);
20497
20498   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20499                           entry->per_cu.offset.sect_off);
20500   obstack_grow (info->types_list, val, 8);
20501   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20502                           entry->type_offset_in_tu.cu_off);
20503   obstack_grow (info->types_list, val, 8);
20504   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20505   obstack_grow (info->types_list, val, 8);
20506
20507   ++info->cu_index;
20508
20509   return 1;
20510 }
20511
20512 /* Recurse into all "included" dependencies and write their symbols as
20513    if they appeared in this psymtab.  */
20514
20515 static void
20516 recursively_write_psymbols (struct objfile *objfile,
20517                             struct partial_symtab *psymtab,
20518                             struct mapped_symtab *symtab,
20519                             htab_t psyms_seen,
20520                             offset_type cu_index)
20521 {
20522   int i;
20523
20524   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20525     if (psymtab->dependencies[i]->user != NULL)
20526       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20527                                   symtab, psyms_seen, cu_index);
20528
20529   write_psymbols (symtab,
20530                   psyms_seen,
20531                   objfile->global_psymbols.list + psymtab->globals_offset,
20532                   psymtab->n_global_syms, cu_index,
20533                   0);
20534   write_psymbols (symtab,
20535                   psyms_seen,
20536                   objfile->static_psymbols.list + psymtab->statics_offset,
20537                   psymtab->n_static_syms, cu_index,
20538                   1);
20539 }
20540
20541 /* Create an index file for OBJFILE in the directory DIR.  */
20542
20543 static void
20544 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20545 {
20546   struct cleanup *cleanup;
20547   char *filename, *cleanup_filename;
20548   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20549   struct obstack cu_list, types_cu_list;
20550   int i;
20551   FILE *out_file;
20552   struct mapped_symtab *symtab;
20553   offset_type val, size_of_contents, total_len;
20554   struct stat st;
20555   htab_t psyms_seen;
20556   htab_t cu_index_htab;
20557   struct psymtab_cu_index_map *psymtab_cu_index_map;
20558
20559   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20560     return;
20561
20562   if (dwarf2_per_objfile->using_index)
20563     error (_("Cannot use an index to create the index"));
20564
20565   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20566     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20567
20568   if (stat (objfile->name, &st) < 0)
20569     perror_with_name (objfile->name);
20570
20571   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20572                      INDEX_SUFFIX, (char *) NULL);
20573   cleanup = make_cleanup (xfree, filename);
20574
20575   out_file = fopen (filename, "wb");
20576   if (!out_file)
20577     error (_("Can't open `%s' for writing"), filename);
20578
20579   cleanup_filename = filename;
20580   make_cleanup (unlink_if_set, &cleanup_filename);
20581
20582   symtab = create_mapped_symtab ();
20583   make_cleanup (cleanup_mapped_symtab, symtab);
20584
20585   obstack_init (&addr_obstack);
20586   make_cleanup_obstack_free (&addr_obstack);
20587
20588   obstack_init (&cu_list);
20589   make_cleanup_obstack_free (&cu_list);
20590
20591   obstack_init (&types_cu_list);
20592   make_cleanup_obstack_free (&types_cu_list);
20593
20594   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20595                                   NULL, xcalloc, xfree);
20596   make_cleanup_htab_delete (psyms_seen);
20597
20598   /* While we're scanning CU's create a table that maps a psymtab pointer
20599      (which is what addrmap records) to its index (which is what is recorded
20600      in the index file).  This will later be needed to write the address
20601      table.  */
20602   cu_index_htab = htab_create_alloc (100,
20603                                      hash_psymtab_cu_index,
20604                                      eq_psymtab_cu_index,
20605                                      NULL, xcalloc, xfree);
20606   make_cleanup_htab_delete (cu_index_htab);
20607   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20608     xmalloc (sizeof (struct psymtab_cu_index_map)
20609              * dwarf2_per_objfile->n_comp_units);
20610   make_cleanup (xfree, psymtab_cu_index_map);
20611
20612   /* The CU list is already sorted, so we don't need to do additional
20613      work here.  Also, the debug_types entries do not appear in
20614      all_comp_units, but only in their own hash table.  */
20615   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20616     {
20617       struct dwarf2_per_cu_data *per_cu
20618         = dwarf2_per_objfile->all_comp_units[i];
20619       struct partial_symtab *psymtab = per_cu->v.psymtab;
20620       gdb_byte val[8];
20621       struct psymtab_cu_index_map *map;
20622       void **slot;
20623
20624       if (psymtab->user == NULL)
20625         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20626
20627       map = &psymtab_cu_index_map[i];
20628       map->psymtab = psymtab;
20629       map->cu_index = i;
20630       slot = htab_find_slot (cu_index_htab, map, INSERT);
20631       gdb_assert (slot != NULL);
20632       gdb_assert (*slot == NULL);
20633       *slot = map;
20634
20635       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20636                               per_cu->offset.sect_off);
20637       obstack_grow (&cu_list, val, 8);
20638       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20639       obstack_grow (&cu_list, val, 8);
20640     }
20641
20642   /* Dump the address map.  */
20643   write_address_map (objfile, &addr_obstack, cu_index_htab);
20644
20645   /* Write out the .debug_type entries, if any.  */
20646   if (dwarf2_per_objfile->signatured_types)
20647     {
20648       struct signatured_type_index_data sig_data;
20649
20650       sig_data.objfile = objfile;
20651       sig_data.symtab = symtab;
20652       sig_data.types_list = &types_cu_list;
20653       sig_data.psyms_seen = psyms_seen;
20654       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20655       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20656                               write_one_signatured_type, &sig_data);
20657     }
20658
20659   /* Now that we've processed all symbols we can shrink their cu_indices
20660      lists.  */
20661   uniquify_cu_indices (symtab);
20662
20663   obstack_init (&constant_pool);
20664   make_cleanup_obstack_free (&constant_pool);
20665   obstack_init (&symtab_obstack);
20666   make_cleanup_obstack_free (&symtab_obstack);
20667   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20668
20669   obstack_init (&contents);
20670   make_cleanup_obstack_free (&contents);
20671   size_of_contents = 6 * sizeof (offset_type);
20672   total_len = size_of_contents;
20673
20674   /* The version number.  */
20675   val = MAYBE_SWAP (8);
20676   obstack_grow (&contents, &val, sizeof (val));
20677
20678   /* The offset of the CU list from the start of the file.  */
20679   val = MAYBE_SWAP (total_len);
20680   obstack_grow (&contents, &val, sizeof (val));
20681   total_len += obstack_object_size (&cu_list);
20682
20683   /* The offset of the types CU list from the start of the file.  */
20684   val = MAYBE_SWAP (total_len);
20685   obstack_grow (&contents, &val, sizeof (val));
20686   total_len += obstack_object_size (&types_cu_list);
20687
20688   /* The offset of the address table from the start of the file.  */
20689   val = MAYBE_SWAP (total_len);
20690   obstack_grow (&contents, &val, sizeof (val));
20691   total_len += obstack_object_size (&addr_obstack);
20692
20693   /* The offset of the symbol table from the start of the file.  */
20694   val = MAYBE_SWAP (total_len);
20695   obstack_grow (&contents, &val, sizeof (val));
20696   total_len += obstack_object_size (&symtab_obstack);
20697
20698   /* The offset of the constant pool from the start of the file.  */
20699   val = MAYBE_SWAP (total_len);
20700   obstack_grow (&contents, &val, sizeof (val));
20701   total_len += obstack_object_size (&constant_pool);
20702
20703   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20704
20705   write_obstack (out_file, &contents);
20706   write_obstack (out_file, &cu_list);
20707   write_obstack (out_file, &types_cu_list);
20708   write_obstack (out_file, &addr_obstack);
20709   write_obstack (out_file, &symtab_obstack);
20710   write_obstack (out_file, &constant_pool);
20711
20712   fclose (out_file);
20713
20714   /* We want to keep the file, so we set cleanup_filename to NULL
20715      here.  See unlink_if_set.  */
20716   cleanup_filename = NULL;
20717
20718   do_cleanups (cleanup);
20719 }
20720
20721 /* Implementation of the `save gdb-index' command.
20722    
20723    Note that the file format used by this command is documented in the
20724    GDB manual.  Any changes here must be documented there.  */
20725
20726 static void
20727 save_gdb_index_command (char *arg, int from_tty)
20728 {
20729   struct objfile *objfile;
20730
20731   if (!arg || !*arg)
20732     error (_("usage: save gdb-index DIRECTORY"));
20733
20734   ALL_OBJFILES (objfile)
20735   {
20736     struct stat st;
20737
20738     /* If the objfile does not correspond to an actual file, skip it.  */
20739     if (stat (objfile->name, &st) < 0)
20740       continue;
20741
20742     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20743     if (dwarf2_per_objfile)
20744       {
20745         volatile struct gdb_exception except;
20746
20747         TRY_CATCH (except, RETURN_MASK_ERROR)
20748           {
20749             write_psymtabs_to_index (objfile, arg);
20750           }
20751         if (except.reason < 0)
20752           exception_fprintf (gdb_stderr, except,
20753                              _("Error while writing index for `%s': "),
20754                              objfile->name);
20755       }
20756   }
20757 }
20758
20759 \f
20760
20761 int dwarf2_always_disassemble;
20762
20763 static void
20764 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20765                                 struct cmd_list_element *c, const char *value)
20766 {
20767   fprintf_filtered (file,
20768                     _("Whether to always disassemble "
20769                       "DWARF expressions is %s.\n"),
20770                     value);
20771 }
20772
20773 static void
20774 show_check_physname (struct ui_file *file, int from_tty,
20775                      struct cmd_list_element *c, const char *value)
20776 {
20777   fprintf_filtered (file,
20778                     _("Whether to check \"physname\" is %s.\n"),
20779                     value);
20780 }
20781
20782 void _initialize_dwarf2_read (void);
20783
20784 void
20785 _initialize_dwarf2_read (void)
20786 {
20787   struct cmd_list_element *c;
20788
20789   dwarf2_objfile_data_key
20790     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20791
20792   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20793 Set DWARF 2 specific variables.\n\
20794 Configure DWARF 2 variables such as the cache size"),
20795                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20796                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20797
20798   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20799 Show DWARF 2 specific variables\n\
20800 Show DWARF 2 variables such as the cache size"),
20801                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20802                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20803
20804   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20805                             &dwarf2_max_cache_age, _("\
20806 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20807 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20808 A higher limit means that cached compilation units will be stored\n\
20809 in memory longer, and more total memory will be used.  Zero disables\n\
20810 caching, which can slow down startup."),
20811                             NULL,
20812                             show_dwarf2_max_cache_age,
20813                             &set_dwarf2_cmdlist,
20814                             &show_dwarf2_cmdlist);
20815
20816   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20817                            &dwarf2_always_disassemble, _("\
20818 Set whether `info address' always disassembles DWARF expressions."), _("\
20819 Show whether `info address' always disassembles DWARF expressions."), _("\
20820 When enabled, DWARF expressions are always printed in an assembly-like\n\
20821 syntax.  When disabled, expressions will be printed in a more\n\
20822 conversational style, when possible."),
20823                            NULL,
20824                            show_dwarf2_always_disassemble,
20825                            &set_dwarf2_cmdlist,
20826                            &show_dwarf2_cmdlist);
20827
20828   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20829 Set debugging of the dwarf2 reader."), _("\
20830 Show debugging of the dwarf2 reader."), _("\
20831 When enabled, debugging messages are printed during dwarf2 reading\n\
20832 and symtab expansion."),
20833                             NULL,
20834                             NULL,
20835                             &setdebuglist, &showdebuglist);
20836
20837   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20838 Set debugging of the dwarf2 DIE reader."), _("\
20839 Show debugging of the dwarf2 DIE reader."), _("\
20840 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20841 The value is the maximum depth to print."),
20842                              NULL,
20843                              NULL,
20844                              &setdebuglist, &showdebuglist);
20845
20846   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20847 Set cross-checking of \"physname\" code against demangler."), _("\
20848 Show cross-checking of \"physname\" code against demangler."), _("\
20849 When enabled, GDB's internal \"physname\" code is checked against\n\
20850 the demangler."),
20851                            NULL, show_check_physname,
20852                            &setdebuglist, &showdebuglist);
20853
20854   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20855                            no_class, &use_deprecated_index_sections, _("\
20856 Set whether to use deprecated gdb_index sections."), _("\
20857 Show whether to use deprecated gdb_index sections."), _("\
20858 When enabled, deprecated .gdb_index sections are used anyway.\n\
20859 Normally they are ignored either because of a missing feature or\n\
20860 performance issue.\n\
20861 Warning: This option must be enabled before gdb reads the file."),
20862                            NULL,
20863                            NULL,
20864                            &setlist, &showlist);
20865
20866   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20867                _("\
20868 Save a gdb-index file.\n\
20869 Usage: save gdb-index DIRECTORY"),
20870                &save_cmdlist);
20871   set_cmd_completer (c, filename_completer);
20872
20873   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
20874                                                         &dwarf2_locexpr_funcs);
20875   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
20876                                                         &dwarf2_loclist_funcs);
20877
20878   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
20879                                         &dwarf2_block_frame_base_locexpr_funcs);
20880   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
20881                                         &dwarf2_block_frame_base_loclist_funcs);
20882 }