* dwarf2read.c (dwarf2_physname): Move declaration to better spot.
[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   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 signature + 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   unsigned int is_debug_types : 1;
547
548   /* Non-zero if this CU is from the .dwz file.  */
549   unsigned int is_dwz : 1;
550
551   /* The section this CU/TU lives in.
552      If the DIE refers to a DWO file, this is always the original die,
553      not the DWO file.  */
554   struct dwarf2_section_info *info_or_types_section;
555
556   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
557      of the CU cache it gets reset to NULL again.  */
558   struct dwarf2_cu *cu;
559
560   /* The corresponding objfile.
561      Normally we can get the objfile from dwarf2_per_objfile.
562      However we can enter this file with just a "per_cu" handle.  */
563   struct objfile *objfile;
564
565   /* When using partial symbol tables, the 'psymtab' field is active.
566      Otherwise the 'quick' field is active.  */
567   union
568   {
569     /* The partial symbol table associated with this compilation unit,
570        or NULL for unread partial units.  */
571     struct partial_symtab *psymtab;
572
573     /* Data needed by the "quick" functions.  */
574     struct dwarf2_per_cu_quick_data *quick;
575   } v;
576
577   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
578      while reading psymtabs, used to compute the psymtab dependencies,
579      and then cleared.  Then it is filled in again while reading full
580      symbols, and only deleted when the objfile is destroyed.
581
582      This is also used to work around a difference between the way gold
583      generates .gdb_index version <=7 and the way gdb does.  Arguably this
584      is a gold bug.  For symbols coming from TUs, gold records in the index
585      the CU that includes the TU instead of the TU itself.  This breaks
586      dw2_lookup_symbol: It assumes that if the index says symbol X lives
587      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
588      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
589      we need to look in TU Z to find X.  Fortunately, this is akin to
590      DW_TAG_imported_unit, so we just use the same mechanism: For
591      .gdb_index version <=7 this also records the TUs that the CU referred
592      to.  Concurrently with this change gdb was modified to emit version 8
593      indices so we only pay a price for gold generated indices.  */
594   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
595
596   /* Type units are grouped by their DW_AT_stmt_list entry so that they
597      can share them.  If this is a TU, this points to the containing
598      symtab.  */
599   struct type_unit_group *type_unit_group;
600 };
601
602 /* Entry in the signatured_types hash table.  */
603
604 struct signatured_type
605 {
606   /* The "per_cu" object of this type.
607      N.B.: This is the first member so that it's easy to convert pointers
608      between them.  */
609   struct dwarf2_per_cu_data per_cu;
610
611   /* The type's signature.  */
612   ULONGEST signature;
613
614   /* Offset in the TU of the type's DIE, as read from the TU header.
615      If the definition lives in a DWO file, this value is unusable.  */
616   cu_offset type_offset_in_tu;
617
618   /* Offset in the section of the type's DIE.
619      If the definition lives in a DWO file, this is the offset in the
620      .debug_types.dwo section.
621      The value is zero until the actual value is known.
622      Zero is otherwise not a valid section offset.  */
623   sect_offset type_offset_in_section;
624 };
625
626 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
627    This includes type_unit_group and quick_file_names.  */
628
629 struct stmt_list_hash
630 {
631   /* The DWO unit this table is from or NULL if there is none.  */
632   struct dwo_unit *dwo_unit;
633
634   /* Offset in .debug_line or .debug_line.dwo.  */
635   sect_offset line_offset;
636 };
637
638 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
639    an object of this type.  */
640
641 struct type_unit_group
642 {
643   /* dwarf2read.c's main "handle" on the symtab.
644      To simplify things we create an artificial CU that "includes" all the
645      type units using this stmt_list so that the rest of the code still has
646      a "per_cu" handle on the symtab.
647      This PER_CU is recognized by having no section.  */
648 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->info_or_types_section == NULL)
649   struct dwarf2_per_cu_data per_cu;
650
651   union
652   {
653     /* The TUs that share this DW_AT_stmt_list entry.
654        This is added to while parsing type units to build partial symtabs,
655        and is deleted afterwards and not used again.  */
656     VEC (dwarf2_per_cu_ptr) *tus;
657
658     /* When reading the line table in "quick" functions, we need a real TU.
659        Any will do, we know they all share the same DW_AT_stmt_list entry.
660        For simplicity's sake, we pick the first one.  */
661     struct dwarf2_per_cu_data *first_tu;
662   } t;
663
664   /* The primary symtab.
665      Type units in a group needn't all be defined in the same source file,
666      so we create an essentially anonymous symtab as the primary symtab.  */
667   struct symtab *primary_symtab;
668
669   /* The data used to construct the hash key.  */
670   struct stmt_list_hash hash;
671
672   /* The number of symtabs from the line header.
673      The value here must match line_header.num_file_names.  */
674   unsigned int num_symtabs;
675
676   /* The symbol tables for this TU (obtained from the files listed in
677      DW_AT_stmt_list).
678      WARNING: The order of entries here must match the order of entries
679      in the line header.  After the first TU using this type_unit_group, the
680      line header for the subsequent TUs is recreated from this.  This is done
681      because we need to use the same symtabs for each TU using the same
682      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
683      there's no guarantee the line header doesn't have duplicate entries.  */
684   struct symtab **symtabs;
685 };
686
687 /* These sections are what may appear in a DWO file.  */
688
689 struct dwo_sections
690 {
691   struct dwarf2_section_info abbrev;
692   struct dwarf2_section_info line;
693   struct dwarf2_section_info loc;
694   struct dwarf2_section_info macinfo;
695   struct dwarf2_section_info macro;
696   struct dwarf2_section_info str;
697   struct dwarf2_section_info str_offsets;
698   /* In the case of a virtual DWO file, these two are unused.  */
699   struct dwarf2_section_info info;
700   VEC (dwarf2_section_info_def) *types;
701 };
702
703 /* Common bits of DWO CUs/TUs.  */
704
705 struct dwo_unit
706 {
707   /* Backlink to the containing struct dwo_file.  */
708   struct dwo_file *dwo_file;
709
710   /* The "id" that distinguishes this CU/TU.
711      .debug_info calls this "dwo_id", .debug_types calls this "signature".
712      Since signatures came first, we stick with it for consistency.  */
713   ULONGEST signature;
714
715   /* The section this CU/TU lives in, in the DWO file.  */
716   struct dwarf2_section_info *info_or_types_section;
717
718   /* Same as dwarf2_per_cu_data:{offset,length} but for the DWO section.  */
719   sect_offset offset;
720   unsigned int length;
721
722   /* For types, offset in the type's DIE of the type defined by this TU.  */
723   cu_offset type_offset_in_tu;
724 };
725
726 /* Data for one DWO file.
727    This includes virtual DWO files that have been packaged into a
728    DWP file.  */
729
730 struct dwo_file
731 {
732   /* The DW_AT_GNU_dwo_name attribute.  This is the hash key.
733      For virtual DWO files the name is constructed from the section offsets
734      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
735      from related CU+TUs.  */
736   const char *name;
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.info_or_types_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   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                                       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   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     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   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     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     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_create_include_psymtab (char *, struct partial_symtab *,
1276                                            struct objfile *);
1277
1278 static void dwarf2_find_base_address (struct die_info *die,
1279                                       struct dwarf2_cu *cu);
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 *, gdb_byte *);
1326
1327 static struct partial_die_info *load_partial_dies
1328   (const struct die_reader_specs *, gdb_byte *, int);
1329
1330 static gdb_byte *read_partial_die (const struct die_reader_specs *,
1331                                    struct partial_die_info *,
1332                                    struct abbrev_info *,
1333                                    unsigned int,
1334                                    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 gdb_byte *read_attribute (const struct die_reader_specs *,
1343                                  struct attribute *, struct attr_abbrev *,
1344                                  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 *, gdb_byte *ptr, struct dwarf2_cu *,
1357                                unsigned int *);
1358
1359 static LONGEST read_initial_length (bfd *, gdb_byte *, unsigned int *);
1360
1361 static LONGEST read_checked_initial_length_and_offset
1362   (bfd *, gdb_byte *, const struct comp_unit_head *,
1363    unsigned int *, unsigned int *);
1364
1365 static LONGEST read_offset (bfd *, gdb_byte *, const struct comp_unit_head *,
1366                             unsigned int *);
1367
1368 static LONGEST read_offset_1 (bfd *, gdb_byte *, unsigned int);
1369
1370 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1371                                        sect_offset);
1372
1373 static gdb_byte *read_n_bytes (bfd *, gdb_byte *, unsigned int);
1374
1375 static char *read_direct_string (bfd *, gdb_byte *, unsigned int *);
1376
1377 static char *read_indirect_string (bfd *, gdb_byte *,
1378                                    const struct comp_unit_head *,
1379                                    unsigned int *);
1380
1381 static char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1382
1383 static ULONGEST read_unsigned_leb128 (bfd *, gdb_byte *, unsigned int *);
1384
1385 static LONGEST read_signed_leb128 (bfd *, gdb_byte *, unsigned int *);
1386
1387 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *, gdb_byte *,
1388                                               unsigned int *);
1389
1390 static char *read_str_index (const struct die_reader_specs *reader,
1391                              struct dwarf2_cu *cu, ULONGEST str_index);
1392
1393 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1394
1395 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1396                                       struct dwarf2_cu *);
1397
1398 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1399                                                 unsigned int);
1400
1401 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1402                                struct dwarf2_cu *cu);
1403
1404 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1405
1406 static struct die_info *die_specification (struct die_info *die,
1407                                            struct dwarf2_cu **);
1408
1409 static void free_line_header (struct line_header *lh);
1410
1411 static void add_file_name (struct line_header *, char *, unsigned int,
1412                            unsigned int, unsigned int);
1413
1414 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1415                                                      struct dwarf2_cu *cu);
1416
1417 static void dwarf_decode_lines (struct line_header *, const char *,
1418                                 struct dwarf2_cu *, struct partial_symtab *,
1419                                 int);
1420
1421 static void dwarf2_start_subfile (char *, const char *, const char *);
1422
1423 static void dwarf2_start_symtab (struct dwarf2_cu *,
1424                                  const char *, const char *, CORE_ADDR);
1425
1426 static struct symbol *new_symbol (struct die_info *, struct type *,
1427                                   struct dwarf2_cu *);
1428
1429 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1430                                        struct dwarf2_cu *, struct symbol *);
1431
1432 static void dwarf2_const_value (struct attribute *, struct symbol *,
1433                                 struct dwarf2_cu *);
1434
1435 static void dwarf2_const_value_attr (struct attribute *attr,
1436                                      struct type *type,
1437                                      const char *name,
1438                                      struct obstack *obstack,
1439                                      struct dwarf2_cu *cu, LONGEST *value,
1440                                      gdb_byte **bytes,
1441                                      struct dwarf2_locexpr_baton **baton);
1442
1443 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1444
1445 static int need_gnat_info (struct dwarf2_cu *);
1446
1447 static struct type *die_descriptive_type (struct die_info *,
1448                                           struct dwarf2_cu *);
1449
1450 static void set_descriptive_type (struct type *, struct die_info *,
1451                                   struct dwarf2_cu *);
1452
1453 static struct type *die_containing_type (struct die_info *,
1454                                          struct dwarf2_cu *);
1455
1456 static struct type *lookup_die_type (struct die_info *, struct attribute *,
1457                                      struct dwarf2_cu *);
1458
1459 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1460
1461 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1462
1463 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1464
1465 static char *typename_concat (struct obstack *obs, const char *prefix,
1466                               const char *suffix, int physname,
1467                               struct dwarf2_cu *cu);
1468
1469 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1470
1471 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1472
1473 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1474
1475 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1476
1477 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1478
1479 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1480                                struct dwarf2_cu *, struct partial_symtab *);
1481
1482 static int dwarf2_get_pc_bounds (struct die_info *,
1483                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1484                                  struct partial_symtab *);
1485
1486 static void get_scope_pc_bounds (struct die_info *,
1487                                  CORE_ADDR *, CORE_ADDR *,
1488                                  struct dwarf2_cu *);
1489
1490 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1491                                         CORE_ADDR, struct dwarf2_cu *);
1492
1493 static void dwarf2_add_field (struct field_info *, struct die_info *,
1494                               struct dwarf2_cu *);
1495
1496 static void dwarf2_attach_fields_to_type (struct field_info *,
1497                                           struct type *, struct dwarf2_cu *);
1498
1499 static void dwarf2_add_member_fn (struct field_info *,
1500                                   struct die_info *, struct type *,
1501                                   struct dwarf2_cu *);
1502
1503 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1504                                              struct type *,
1505                                              struct dwarf2_cu *);
1506
1507 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1508
1509 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1510
1511 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1512
1513 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1514
1515 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1516
1517 static struct type *read_module_type (struct die_info *die,
1518                                       struct dwarf2_cu *cu);
1519
1520 static const char *namespace_name (struct die_info *die,
1521                                    int *is_anonymous, struct dwarf2_cu *);
1522
1523 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1524
1525 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1526
1527 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1528                                                        struct dwarf2_cu *);
1529
1530 static struct die_info *read_die_and_children (const struct die_reader_specs *,
1531                                                gdb_byte *info_ptr,
1532                                                gdb_byte **new_info_ptr,
1533                                                struct die_info *parent);
1534
1535 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1536                                                gdb_byte *info_ptr,
1537                                                gdb_byte **new_info_ptr,
1538                                                struct die_info *parent);
1539
1540 static gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1541                                   struct die_info **, gdb_byte *, int *, int);
1542
1543 static gdb_byte *read_full_die (const struct die_reader_specs *,
1544                                 struct die_info **, gdb_byte *, 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 struct signatured_type *lookup_signatured_type_at_offset
1606     (struct objfile *objfile,
1607      struct dwarf2_section_info *section, sect_offset offset);
1608
1609 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1610
1611 static void read_signatured_type (struct signatured_type *);
1612
1613 static struct type_unit_group *get_type_unit_group
1614     (struct dwarf2_cu *, struct attribute *);
1615
1616 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1617
1618 /* memory allocation interface */
1619
1620 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1621
1622 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1623
1624 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1625                                  const char *, int);
1626
1627 static int attr_form_is_block (struct attribute *);
1628
1629 static int attr_form_is_section_offset (struct attribute *);
1630
1631 static int attr_form_is_constant (struct attribute *);
1632
1633 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1634                                    struct dwarf2_loclist_baton *baton,
1635                                    struct attribute *attr);
1636
1637 static void dwarf2_symbol_mark_computed (struct attribute *attr,
1638                                          struct symbol *sym,
1639                                          struct dwarf2_cu *cu,
1640                                          int is_block);
1641
1642 static gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1643                                gdb_byte *info_ptr,
1644                                struct abbrev_info *abbrev);
1645
1646 static void free_stack_comp_unit (void *);
1647
1648 static hashval_t partial_die_hash (const void *item);
1649
1650 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1651
1652 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1653   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1654
1655 static void init_one_comp_unit (struct dwarf2_cu *cu,
1656                                 struct dwarf2_per_cu_data *per_cu);
1657
1658 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1659                                    struct die_info *comp_unit_die,
1660                                    enum language pretend_language);
1661
1662 static void free_heap_comp_unit (void *);
1663
1664 static void free_cached_comp_units (void *);
1665
1666 static void age_cached_comp_units (void);
1667
1668 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1669
1670 static struct type *set_die_type (struct die_info *, struct type *,
1671                                   struct dwarf2_cu *);
1672
1673 static void create_all_comp_units (struct objfile *);
1674
1675 static int create_all_type_units (struct objfile *);
1676
1677 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1678                                  enum language);
1679
1680 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1681                                     enum language);
1682
1683 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1684                                     enum language);
1685
1686 static void dwarf2_add_dependence (struct dwarf2_cu *,
1687                                    struct dwarf2_per_cu_data *);
1688
1689 static void dwarf2_mark (struct dwarf2_cu *);
1690
1691 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1692
1693 static struct type *get_die_type_at_offset (sect_offset,
1694                                             struct dwarf2_per_cu_data *per_cu);
1695
1696 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1697
1698 static void dwarf2_release_queue (void *dummy);
1699
1700 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1701                              enum language pretend_language);
1702
1703 static int maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
1704                                   struct dwarf2_per_cu_data *per_cu,
1705                                   enum language pretend_language);
1706
1707 static void process_queue (void);
1708
1709 static void find_file_and_directory (struct die_info *die,
1710                                      struct dwarf2_cu *cu,
1711                                      const char **name, const char **comp_dir);
1712
1713 static char *file_full_name (int file, struct line_header *lh,
1714                              const char *comp_dir);
1715
1716 static gdb_byte *read_and_check_comp_unit_head
1717   (struct comp_unit_head *header,
1718    struct dwarf2_section_info *section,
1719    struct dwarf2_section_info *abbrev_section, gdb_byte *info_ptr,
1720    int is_debug_types_section);
1721
1722 static void init_cutu_and_read_dies
1723   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1724    int use_existing_cu, int keep,
1725    die_reader_func_ftype *die_reader_func, void *data);
1726
1727 static void init_cutu_and_read_dies_simple
1728   (struct dwarf2_per_cu_data *this_cu,
1729    die_reader_func_ftype *die_reader_func, void *data);
1730
1731 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1732
1733 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1734
1735 static struct dwo_unit *lookup_dwo_comp_unit
1736   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1737
1738 static struct dwo_unit *lookup_dwo_type_unit
1739   (struct signatured_type *, const char *, const char *);
1740
1741 static void free_dwo_file_cleanup (void *);
1742
1743 static void process_cu_includes (void);
1744
1745 static void check_producer (struct dwarf2_cu *cu);
1746
1747 #if WORDS_BIGENDIAN
1748
1749 /* Convert VALUE between big- and little-endian.  */
1750 static offset_type
1751 byte_swap (offset_type value)
1752 {
1753   offset_type result;
1754
1755   result = (value & 0xff) << 24;
1756   result |= (value & 0xff00) << 8;
1757   result |= (value & 0xff0000) >> 8;
1758   result |= (value & 0xff000000) >> 24;
1759   return result;
1760 }
1761
1762 #define MAYBE_SWAP(V)  byte_swap (V)
1763
1764 #else
1765 #define MAYBE_SWAP(V) (V)
1766 #endif /* WORDS_BIGENDIAN */
1767
1768 /* The suffix for an index file.  */
1769 #define INDEX_SUFFIX ".gdb-index"
1770
1771 /* Try to locate the sections we need for DWARF 2 debugging
1772    information and return true if we have enough to do something.
1773    NAMES points to the dwarf2 section names, or is NULL if the standard
1774    ELF names are used.  */
1775
1776 int
1777 dwarf2_has_info (struct objfile *objfile,
1778                  const struct dwarf2_debug_sections *names)
1779 {
1780   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1781   if (!dwarf2_per_objfile)
1782     {
1783       /* Initialize per-objfile state.  */
1784       struct dwarf2_per_objfile *data
1785         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1786
1787       memset (data, 0, sizeof (*data));
1788       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1789       dwarf2_per_objfile = data;
1790
1791       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1792                              (void *) names);
1793       dwarf2_per_objfile->objfile = objfile;
1794     }
1795   return (dwarf2_per_objfile->info.asection != NULL
1796           && dwarf2_per_objfile->abbrev.asection != NULL);
1797 }
1798
1799 /* When loading sections, we look either for uncompressed section or for
1800    compressed section names.  */
1801
1802 static int
1803 section_is_p (const char *section_name,
1804               const struct dwarf2_section_names *names)
1805 {
1806   if (names->normal != NULL
1807       && strcmp (section_name, names->normal) == 0)
1808     return 1;
1809   if (names->compressed != NULL
1810       && strcmp (section_name, names->compressed) == 0)
1811     return 1;
1812   return 0;
1813 }
1814
1815 /* This function is mapped across the sections and remembers the
1816    offset and size of each of the debugging sections we are interested
1817    in.  */
1818
1819 static void
1820 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
1821 {
1822   const struct dwarf2_debug_sections *names;
1823   flagword aflag = bfd_get_section_flags (abfd, sectp);
1824
1825   if (vnames == NULL)
1826     names = &dwarf2_elf_names;
1827   else
1828     names = (const struct dwarf2_debug_sections *) vnames;
1829
1830   if ((aflag & SEC_HAS_CONTENTS) == 0)
1831     {
1832     }
1833   else if (section_is_p (sectp->name, &names->info))
1834     {
1835       dwarf2_per_objfile->info.asection = sectp;
1836       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
1837     }
1838   else if (section_is_p (sectp->name, &names->abbrev))
1839     {
1840       dwarf2_per_objfile->abbrev.asection = sectp;
1841       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
1842     }
1843   else if (section_is_p (sectp->name, &names->line))
1844     {
1845       dwarf2_per_objfile->line.asection = sectp;
1846       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
1847     }
1848   else if (section_is_p (sectp->name, &names->loc))
1849     {
1850       dwarf2_per_objfile->loc.asection = sectp;
1851       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
1852     }
1853   else if (section_is_p (sectp->name, &names->macinfo))
1854     {
1855       dwarf2_per_objfile->macinfo.asection = sectp;
1856       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
1857     }
1858   else if (section_is_p (sectp->name, &names->macro))
1859     {
1860       dwarf2_per_objfile->macro.asection = sectp;
1861       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
1862     }
1863   else if (section_is_p (sectp->name, &names->str))
1864     {
1865       dwarf2_per_objfile->str.asection = sectp;
1866       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
1867     }
1868   else if (section_is_p (sectp->name, &names->addr))
1869     {
1870       dwarf2_per_objfile->addr.asection = sectp;
1871       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
1872     }
1873   else if (section_is_p (sectp->name, &names->frame))
1874     {
1875       dwarf2_per_objfile->frame.asection = sectp;
1876       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
1877     }
1878   else if (section_is_p (sectp->name, &names->eh_frame))
1879     {
1880       dwarf2_per_objfile->eh_frame.asection = sectp;
1881       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
1882     }
1883   else if (section_is_p (sectp->name, &names->ranges))
1884     {
1885       dwarf2_per_objfile->ranges.asection = sectp;
1886       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
1887     }
1888   else if (section_is_p (sectp->name, &names->types))
1889     {
1890       struct dwarf2_section_info type_section;
1891
1892       memset (&type_section, 0, sizeof (type_section));
1893       type_section.asection = sectp;
1894       type_section.size = bfd_get_section_size (sectp);
1895
1896       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
1897                      &type_section);
1898     }
1899   else if (section_is_p (sectp->name, &names->gdb_index))
1900     {
1901       dwarf2_per_objfile->gdb_index.asection = sectp;
1902       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
1903     }
1904
1905   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
1906       && bfd_section_vma (abfd, sectp) == 0)
1907     dwarf2_per_objfile->has_section_at_zero = 1;
1908 }
1909
1910 /* A helper function that decides whether a section is empty,
1911    or not present.  */
1912
1913 static int
1914 dwarf2_section_empty_p (struct dwarf2_section_info *info)
1915 {
1916   return info->asection == NULL || info->size == 0;
1917 }
1918
1919 /* Read the contents of the section INFO.
1920    OBJFILE is the main object file, but not necessarily the file where
1921    the section comes from.  E.g., for DWO files INFO->asection->owner
1922    is the bfd of the DWO file.
1923    If the section is compressed, uncompress it before returning.  */
1924
1925 static void
1926 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
1927 {
1928   asection *sectp = info->asection;
1929   bfd *abfd;
1930   gdb_byte *buf, *retbuf;
1931   unsigned char header[4];
1932
1933   if (info->readin)
1934     return;
1935   info->buffer = NULL;
1936   info->readin = 1;
1937
1938   if (dwarf2_section_empty_p (info))
1939     return;
1940
1941   abfd = sectp->owner;
1942
1943   /* If the section has relocations, we must read it ourselves.
1944      Otherwise we attach it to the BFD.  */
1945   if ((sectp->flags & SEC_RELOC) == 0)
1946     {
1947       const gdb_byte *bytes = gdb_bfd_map_section (sectp, &info->size);
1948
1949       /* We have to cast away const here for historical reasons.
1950          Fixing dwarf2read to be const-correct would be quite nice.  */
1951       info->buffer = (gdb_byte *) bytes;
1952       return;
1953     }
1954
1955   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
1956   info->buffer = buf;
1957
1958   /* When debugging .o files, we may need to apply relocations; see
1959      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
1960      We never compress sections in .o files, so we only need to
1961      try this when the section is not compressed.  */
1962   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
1963   if (retbuf != NULL)
1964     {
1965       info->buffer = retbuf;
1966       return;
1967     }
1968
1969   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
1970       || bfd_bread (buf, info->size, abfd) != info->size)
1971     error (_("Dwarf Error: Can't read DWARF data from '%s'"),
1972            bfd_get_filename (abfd));
1973 }
1974
1975 /* A helper function that returns the size of a section in a safe way.
1976    If you are positive that the section has been read before using the
1977    size, then it is safe to refer to the dwarf2_section_info object's
1978    "size" field directly.  In other cases, you must call this
1979    function, because for compressed sections the size field is not set
1980    correctly until the section has been read.  */
1981
1982 static bfd_size_type
1983 dwarf2_section_size (struct objfile *objfile,
1984                      struct dwarf2_section_info *info)
1985 {
1986   if (!info->readin)
1987     dwarf2_read_section (objfile, info);
1988   return info->size;
1989 }
1990
1991 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
1992    SECTION_NAME.  */
1993
1994 void
1995 dwarf2_get_section_info (struct objfile *objfile,
1996                          enum dwarf2_section_enum sect,
1997                          asection **sectp, gdb_byte **bufp,
1998                          bfd_size_type *sizep)
1999 {
2000   struct dwarf2_per_objfile *data
2001     = objfile_data (objfile, dwarf2_objfile_data_key);
2002   struct dwarf2_section_info *info;
2003
2004   /* We may see an objfile without any DWARF, in which case we just
2005      return nothing.  */
2006   if (data == NULL)
2007     {
2008       *sectp = NULL;
2009       *bufp = NULL;
2010       *sizep = 0;
2011       return;
2012     }
2013   switch (sect)
2014     {
2015     case DWARF2_DEBUG_FRAME:
2016       info = &data->frame;
2017       break;
2018     case DWARF2_EH_FRAME:
2019       info = &data->eh_frame;
2020       break;
2021     default:
2022       gdb_assert_not_reached ("unexpected section");
2023     }
2024
2025   dwarf2_read_section (objfile, info);
2026
2027   *sectp = info->asection;
2028   *bufp = info->buffer;
2029   *sizep = info->size;
2030 }
2031
2032 /* A helper function to find the sections for a .dwz file.  */
2033
2034 static void
2035 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2036 {
2037   struct dwz_file *dwz_file = arg;
2038
2039   /* Note that we only support the standard ELF names, because .dwz
2040      is ELF-only (at the time of writing).  */
2041   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2042     {
2043       dwz_file->abbrev.asection = sectp;
2044       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2045     }
2046   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2047     {
2048       dwz_file->info.asection = sectp;
2049       dwz_file->info.size = bfd_get_section_size (sectp);
2050     }
2051   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2052     {
2053       dwz_file->str.asection = sectp;
2054       dwz_file->str.size = bfd_get_section_size (sectp);
2055     }
2056   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2057     {
2058       dwz_file->line.asection = sectp;
2059       dwz_file->line.size = bfd_get_section_size (sectp);
2060     }
2061   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2062     {
2063       dwz_file->macro.asection = sectp;
2064       dwz_file->macro.size = bfd_get_section_size (sectp);
2065     }
2066   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2067     {
2068       dwz_file->gdb_index.asection = sectp;
2069       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2070     }
2071 }
2072
2073 /* Open the separate '.dwz' debug file, if needed.  Error if the file
2074    cannot be found.  */
2075
2076 static struct dwz_file *
2077 dwarf2_get_dwz_file (void)
2078 {
2079   bfd *abfd, *dwz_bfd;
2080   asection *section;
2081   gdb_byte *data;
2082   struct cleanup *cleanup;
2083   const char *filename;
2084   struct dwz_file *result;
2085
2086   if (dwarf2_per_objfile->dwz_file != NULL)
2087     return dwarf2_per_objfile->dwz_file;
2088
2089   abfd = dwarf2_per_objfile->objfile->obfd;
2090   section = bfd_get_section_by_name (abfd, ".gnu_debugaltlink");
2091   if (section == NULL)
2092     error (_("could not find '.gnu_debugaltlink' section"));
2093   if (!bfd_malloc_and_get_section (abfd, section, &data))
2094     error (_("could not read '.gnu_debugaltlink' section: %s"),
2095            bfd_errmsg (bfd_get_error ()));
2096   cleanup = make_cleanup (xfree, data);
2097
2098   filename = data;
2099   if (!IS_ABSOLUTE_PATH (filename))
2100     {
2101       char *abs = gdb_realpath (dwarf2_per_objfile->objfile->name);
2102       char *rel;
2103
2104       make_cleanup (xfree, abs);
2105       abs = ldirname (abs);
2106       make_cleanup (xfree, abs);
2107
2108       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2109       make_cleanup (xfree, rel);
2110       filename = rel;
2111     }
2112
2113   /* The format is just a NUL-terminated file name, followed by the
2114      build-id.  For now, though, we ignore the build-id.  */
2115   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2116   if (dwz_bfd == NULL)
2117     error (_("could not read '%s': %s"), filename,
2118            bfd_errmsg (bfd_get_error ()));
2119
2120   if (!bfd_check_format (dwz_bfd, bfd_object))
2121     {
2122       gdb_bfd_unref (dwz_bfd);
2123       error (_("file '%s' was not usable: %s"), filename,
2124              bfd_errmsg (bfd_get_error ()));
2125     }
2126
2127   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2128                            struct dwz_file);
2129   result->dwz_bfd = dwz_bfd;
2130
2131   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2132
2133   do_cleanups (cleanup);
2134
2135   dwarf2_per_objfile->dwz_file = result;
2136   return result;
2137 }
2138 \f
2139 /* DWARF quick_symbols_functions support.  */
2140
2141 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2142    unique line tables, so we maintain a separate table of all .debug_line
2143    derived entries to support the sharing.
2144    All the quick functions need is the list of file names.  We discard the
2145    line_header when we're done and don't need to record it here.  */
2146 struct quick_file_names
2147 {
2148   /* The data used to construct the hash key.  */
2149   struct stmt_list_hash hash;
2150
2151   /* The number of entries in file_names, real_names.  */
2152   unsigned int num_file_names;
2153
2154   /* The file names from the line table, after being run through
2155      file_full_name.  */
2156   const char **file_names;
2157
2158   /* The file names from the line table after being run through
2159      gdb_realpath.  These are computed lazily.  */
2160   const char **real_names;
2161 };
2162
2163 /* When using the index (and thus not using psymtabs), each CU has an
2164    object of this type.  This is used to hold information needed by
2165    the various "quick" methods.  */
2166 struct dwarf2_per_cu_quick_data
2167 {
2168   /* The file table.  This can be NULL if there was no file table
2169      or it's currently not read in.
2170      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2171   struct quick_file_names *file_names;
2172
2173   /* The corresponding symbol table.  This is NULL if symbols for this
2174      CU have not yet been read.  */
2175   struct symtab *symtab;
2176
2177   /* A temporary mark bit used when iterating over all CUs in
2178      expand_symtabs_matching.  */
2179   unsigned int mark : 1;
2180
2181   /* True if we've tried to read the file table and found there isn't one.
2182      There will be no point in trying to read it again next time.  */
2183   unsigned int no_file_data : 1;
2184 };
2185
2186 /* Utility hash function for a stmt_list_hash.  */
2187
2188 static hashval_t
2189 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2190 {
2191   hashval_t v = 0;
2192
2193   if (stmt_list_hash->dwo_unit != NULL)
2194     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2195   v += stmt_list_hash->line_offset.sect_off;
2196   return v;
2197 }
2198
2199 /* Utility equality function for a stmt_list_hash.  */
2200
2201 static int
2202 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2203                     const struct stmt_list_hash *rhs)
2204 {
2205   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2206     return 0;
2207   if (lhs->dwo_unit != NULL
2208       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2209     return 0;
2210
2211   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2212 }
2213
2214 /* Hash function for a quick_file_names.  */
2215
2216 static hashval_t
2217 hash_file_name_entry (const void *e)
2218 {
2219   const struct quick_file_names *file_data = e;
2220
2221   return hash_stmt_list_entry (&file_data->hash);
2222 }
2223
2224 /* Equality function for a quick_file_names.  */
2225
2226 static int
2227 eq_file_name_entry (const void *a, const void *b)
2228 {
2229   const struct quick_file_names *ea = a;
2230   const struct quick_file_names *eb = b;
2231
2232   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2233 }
2234
2235 /* Delete function for a quick_file_names.  */
2236
2237 static void
2238 delete_file_name_entry (void *e)
2239 {
2240   struct quick_file_names *file_data = e;
2241   int i;
2242
2243   for (i = 0; i < file_data->num_file_names; ++i)
2244     {
2245       xfree ((void*) file_data->file_names[i]);
2246       if (file_data->real_names)
2247         xfree ((void*) file_data->real_names[i]);
2248     }
2249
2250   /* The space for the struct itself lives on objfile_obstack,
2251      so we don't free it here.  */
2252 }
2253
2254 /* Create a quick_file_names hash table.  */
2255
2256 static htab_t
2257 create_quick_file_names_table (unsigned int nr_initial_entries)
2258 {
2259   return htab_create_alloc (nr_initial_entries,
2260                             hash_file_name_entry, eq_file_name_entry,
2261                             delete_file_name_entry, xcalloc, xfree);
2262 }
2263
2264 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2265    have to be created afterwards.  You should call age_cached_comp_units after
2266    processing PER_CU->CU.  dw2_setup must have been already called.  */
2267
2268 static void
2269 load_cu (struct dwarf2_per_cu_data *per_cu)
2270 {
2271   if (per_cu->is_debug_types)
2272     load_full_type_unit (per_cu);
2273   else
2274     load_full_comp_unit (per_cu, language_minimal);
2275
2276   gdb_assert (per_cu->cu != NULL);
2277
2278   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2279 }
2280
2281 /* Read in the symbols for PER_CU.  */
2282
2283 static void
2284 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2285 {
2286   struct cleanup *back_to;
2287
2288   /* Skip type_unit_groups, reading the type units they contain
2289      is handled elsewhere.  */
2290   if (IS_TYPE_UNIT_GROUP (per_cu))
2291     return;
2292
2293   back_to = make_cleanup (dwarf2_release_queue, NULL);
2294
2295   if (dwarf2_per_objfile->using_index
2296       ? per_cu->v.quick->symtab == NULL
2297       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2298     {
2299       queue_comp_unit (per_cu, language_minimal);
2300       load_cu (per_cu);
2301     }
2302
2303   process_queue ();
2304
2305   /* Age the cache, releasing compilation units that have not
2306      been used recently.  */
2307   age_cached_comp_units ();
2308
2309   do_cleanups (back_to);
2310 }
2311
2312 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2313    the objfile from which this CU came.  Returns the resulting symbol
2314    table.  */
2315
2316 static struct symtab *
2317 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2318 {
2319   gdb_assert (dwarf2_per_objfile->using_index);
2320   if (!per_cu->v.quick->symtab)
2321     {
2322       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2323       increment_reading_symtab ();
2324       dw2_do_instantiate_symtab (per_cu);
2325       process_cu_includes ();
2326       do_cleanups (back_to);
2327     }
2328   return per_cu->v.quick->symtab;
2329 }
2330
2331 /* Return the CU given its index.
2332
2333    This is intended for loops like:
2334
2335    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2336                     + dwarf2_per_objfile->n_type_units); ++i)
2337      {
2338        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2339
2340        ...;
2341      }
2342 */
2343
2344 static struct dwarf2_per_cu_data *
2345 dw2_get_cu (int index)
2346 {
2347   if (index >= dwarf2_per_objfile->n_comp_units)
2348     {
2349       index -= dwarf2_per_objfile->n_comp_units;
2350       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2351       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2352     }
2353
2354   return dwarf2_per_objfile->all_comp_units[index];
2355 }
2356
2357 /* Return the primary CU given its index.
2358    The difference between this function and dw2_get_cu is in the handling
2359    of type units (TUs).  Here we return the type_unit_group object.
2360
2361    This is intended for loops like:
2362
2363    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2364                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2365      {
2366        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2367
2368        ...;
2369      }
2370 */
2371
2372 static struct dwarf2_per_cu_data *
2373 dw2_get_primary_cu (int index)
2374 {
2375   if (index >= dwarf2_per_objfile->n_comp_units)
2376     {
2377       index -= dwarf2_per_objfile->n_comp_units;
2378       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2379       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2380     }
2381
2382   return dwarf2_per_objfile->all_comp_units[index];
2383 }
2384
2385 /* A helper for create_cus_from_index that handles a given list of
2386    CUs.  */
2387
2388 static void
2389 create_cus_from_index_list (struct objfile *objfile,
2390                             const gdb_byte *cu_list, offset_type n_elements,
2391                             struct dwarf2_section_info *section,
2392                             int is_dwz,
2393                             int base_offset)
2394 {
2395   offset_type i;
2396
2397   for (i = 0; i < n_elements; i += 2)
2398     {
2399       struct dwarf2_per_cu_data *the_cu;
2400       ULONGEST offset, length;
2401
2402       gdb_static_assert (sizeof (ULONGEST) >= 8);
2403       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2404       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2405       cu_list += 2 * 8;
2406
2407       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2408                                struct dwarf2_per_cu_data);
2409       the_cu->offset.sect_off = offset;
2410       the_cu->length = length;
2411       the_cu->objfile = objfile;
2412       the_cu->info_or_types_section = section;
2413       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2414                                         struct dwarf2_per_cu_quick_data);
2415       the_cu->is_dwz = is_dwz;
2416       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2417     }
2418 }
2419
2420 /* Read the CU list from the mapped index, and use it to create all
2421    the CU objects for this objfile.  */
2422
2423 static void
2424 create_cus_from_index (struct objfile *objfile,
2425                        const gdb_byte *cu_list, offset_type cu_list_elements,
2426                        const gdb_byte *dwz_list, offset_type dwz_elements)
2427 {
2428   struct dwz_file *dwz;
2429
2430   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2431   dwarf2_per_objfile->all_comp_units
2432     = obstack_alloc (&objfile->objfile_obstack,
2433                      dwarf2_per_objfile->n_comp_units
2434                      * sizeof (struct dwarf2_per_cu_data *));
2435
2436   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2437                               &dwarf2_per_objfile->info, 0, 0);
2438
2439   if (dwz_elements == 0)
2440     return;
2441
2442   dwz = dwarf2_get_dwz_file ();
2443   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2444                               cu_list_elements / 2);
2445 }
2446
2447 /* Create the signatured type hash table from the index.  */
2448
2449 static void
2450 create_signatured_type_table_from_index (struct objfile *objfile,
2451                                          struct dwarf2_section_info *section,
2452                                          const gdb_byte *bytes,
2453                                          offset_type elements)
2454 {
2455   offset_type i;
2456   htab_t sig_types_hash;
2457
2458   dwarf2_per_objfile->n_type_units = elements / 3;
2459   dwarf2_per_objfile->all_type_units
2460     = obstack_alloc (&objfile->objfile_obstack,
2461                      dwarf2_per_objfile->n_type_units
2462                      * sizeof (struct signatured_type *));
2463
2464   sig_types_hash = allocate_signatured_type_table (objfile);
2465
2466   for (i = 0; i < elements; i += 3)
2467     {
2468       struct signatured_type *sig_type;
2469       ULONGEST offset, type_offset_in_tu, signature;
2470       void **slot;
2471
2472       gdb_static_assert (sizeof (ULONGEST) >= 8);
2473       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2474       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2475                                                     BFD_ENDIAN_LITTLE);
2476       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2477       bytes += 3 * 8;
2478
2479       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2480                                  struct signatured_type);
2481       sig_type->signature = signature;
2482       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2483       sig_type->per_cu.is_debug_types = 1;
2484       sig_type->per_cu.info_or_types_section = section;
2485       sig_type->per_cu.offset.sect_off = offset;
2486       sig_type->per_cu.objfile = objfile;
2487       sig_type->per_cu.v.quick
2488         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2489                           struct dwarf2_per_cu_quick_data);
2490
2491       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2492       *slot = sig_type;
2493
2494       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2495     }
2496
2497   dwarf2_per_objfile->signatured_types = sig_types_hash;
2498 }
2499
2500 /* Read the address map data from the mapped index, and use it to
2501    populate the objfile's psymtabs_addrmap.  */
2502
2503 static void
2504 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2505 {
2506   const gdb_byte *iter, *end;
2507   struct obstack temp_obstack;
2508   struct addrmap *mutable_map;
2509   struct cleanup *cleanup;
2510   CORE_ADDR baseaddr;
2511
2512   obstack_init (&temp_obstack);
2513   cleanup = make_cleanup_obstack_free (&temp_obstack);
2514   mutable_map = addrmap_create_mutable (&temp_obstack);
2515
2516   iter = index->address_table;
2517   end = iter + index->address_table_size;
2518
2519   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2520
2521   while (iter < end)
2522     {
2523       ULONGEST hi, lo, cu_index;
2524       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2525       iter += 8;
2526       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2527       iter += 8;
2528       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2529       iter += 4;
2530       
2531       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2532                          dw2_get_cu (cu_index));
2533     }
2534
2535   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2536                                                     &objfile->objfile_obstack);
2537   do_cleanups (cleanup);
2538 }
2539
2540 /* The hash function for strings in the mapped index.  This is the same as
2541    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2542    implementation.  This is necessary because the hash function is tied to the
2543    format of the mapped index file.  The hash values do not have to match with
2544    SYMBOL_HASH_NEXT.
2545    
2546    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2547
2548 static hashval_t
2549 mapped_index_string_hash (int index_version, const void *p)
2550 {
2551   const unsigned char *str = (const unsigned char *) p;
2552   hashval_t r = 0;
2553   unsigned char c;
2554
2555   while ((c = *str++) != 0)
2556     {
2557       if (index_version >= 5)
2558         c = tolower (c);
2559       r = r * 67 + c - 113;
2560     }
2561
2562   return r;
2563 }
2564
2565 /* Find a slot in the mapped index INDEX for the object named NAME.
2566    If NAME is found, set *VEC_OUT to point to the CU vector in the
2567    constant pool and return 1.  If NAME cannot be found, return 0.  */
2568
2569 static int
2570 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2571                           offset_type **vec_out)
2572 {
2573   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2574   offset_type hash;
2575   offset_type slot, step;
2576   int (*cmp) (const char *, const char *);
2577
2578   if (current_language->la_language == language_cplus
2579       || current_language->la_language == language_java
2580       || current_language->la_language == language_fortran)
2581     {
2582       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2583          not contain any.  */
2584       const char *paren = strchr (name, '(');
2585
2586       if (paren)
2587         {
2588           char *dup;
2589
2590           dup = xmalloc (paren - name + 1);
2591           memcpy (dup, name, paren - name);
2592           dup[paren - name] = 0;
2593
2594           make_cleanup (xfree, dup);
2595           name = dup;
2596         }
2597     }
2598
2599   /* Index version 4 did not support case insensitive searches.  But the
2600      indices for case insensitive languages are built in lowercase, therefore
2601      simulate our NAME being searched is also lowercased.  */
2602   hash = mapped_index_string_hash ((index->version == 4
2603                                     && case_sensitivity == case_sensitive_off
2604                                     ? 5 : index->version),
2605                                    name);
2606
2607   slot = hash & (index->symbol_table_slots - 1);
2608   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2609   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2610
2611   for (;;)
2612     {
2613       /* Convert a slot number to an offset into the table.  */
2614       offset_type i = 2 * slot;
2615       const char *str;
2616       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2617         {
2618           do_cleanups (back_to);
2619           return 0;
2620         }
2621
2622       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2623       if (!cmp (name, str))
2624         {
2625           *vec_out = (offset_type *) (index->constant_pool
2626                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2627           do_cleanups (back_to);
2628           return 1;
2629         }
2630
2631       slot = (slot + step) & (index->symbol_table_slots - 1);
2632     }
2633 }
2634
2635 /* A helper function that reads the .gdb_index from SECTION and fills
2636    in MAP.  FILENAME is the name of the file containing the section;
2637    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2638    ok to use deprecated sections.
2639
2640    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2641    out parameters that are filled in with information about the CU and
2642    TU lists in the section.
2643
2644    Returns 1 if all went well, 0 otherwise.  */
2645
2646 static int
2647 read_index_from_section (struct objfile *objfile,
2648                          const char *filename,
2649                          int deprecated_ok,
2650                          struct dwarf2_section_info *section,
2651                          struct mapped_index *map,
2652                          const gdb_byte **cu_list,
2653                          offset_type *cu_list_elements,
2654                          const gdb_byte **types_list,
2655                          offset_type *types_list_elements)
2656 {
2657   char *addr;
2658   offset_type version;
2659   offset_type *metadata;
2660   int i;
2661
2662   if (dwarf2_section_empty_p (section))
2663     return 0;
2664
2665   /* Older elfutils strip versions could keep the section in the main
2666      executable while splitting it for the separate debug info file.  */
2667   if ((bfd_get_file_flags (section->asection) & SEC_HAS_CONTENTS) == 0)
2668     return 0;
2669
2670   dwarf2_read_section (objfile, section);
2671
2672   addr = section->buffer;
2673   /* Version check.  */
2674   version = MAYBE_SWAP (*(offset_type *) addr);
2675   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2676      causes the index to behave very poorly for certain requests.  Version 3
2677      contained incomplete addrmap.  So, it seems better to just ignore such
2678      indices.  */
2679   if (version < 4)
2680     {
2681       static int warning_printed = 0;
2682       if (!warning_printed)
2683         {
2684           warning (_("Skipping obsolete .gdb_index section in %s."),
2685                    filename);
2686           warning_printed = 1;
2687         }
2688       return 0;
2689     }
2690   /* Index version 4 uses a different hash function than index version
2691      5 and later.
2692
2693      Versions earlier than 6 did not emit psymbols for inlined
2694      functions.  Using these files will cause GDB not to be able to
2695      set breakpoints on inlined functions by name, so we ignore these
2696      indices unless the user has done
2697      "set use-deprecated-index-sections on".  */
2698   if (version < 6 && !deprecated_ok)
2699     {
2700       static int warning_printed = 0;
2701       if (!warning_printed)
2702         {
2703           warning (_("\
2704 Skipping deprecated .gdb_index section in %s.\n\
2705 Do \"set use-deprecated-index-sections on\" before the file is read\n\
2706 to use the section anyway."),
2707                    filename);
2708           warning_printed = 1;
2709         }
2710       return 0;
2711     }
2712   /* Version 7 indices generated by gold refer to the CU for a symbol instead
2713      of the TU (for symbols coming from TUs).  It's just a performance bug, and
2714      we can't distinguish gdb-generated indices from gold-generated ones, so
2715      nothing to do here.  */
2716
2717   /* Indexes with higher version than the one supported by GDB may be no
2718      longer backward compatible.  */
2719   if (version > 8)
2720     return 0;
2721
2722   map->version = version;
2723   map->total_size = section->size;
2724
2725   metadata = (offset_type *) (addr + sizeof (offset_type));
2726
2727   i = 0;
2728   *cu_list = addr + MAYBE_SWAP (metadata[i]);
2729   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
2730                        / 8);
2731   ++i;
2732
2733   *types_list = addr + MAYBE_SWAP (metadata[i]);
2734   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
2735                            - MAYBE_SWAP (metadata[i]))
2736                           / 8);
2737   ++i;
2738
2739   map->address_table = addr + MAYBE_SWAP (metadata[i]);
2740   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
2741                              - MAYBE_SWAP (metadata[i]));
2742   ++i;
2743
2744   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
2745   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
2746                               - MAYBE_SWAP (metadata[i]))
2747                              / (2 * sizeof (offset_type)));
2748   ++i;
2749
2750   map->constant_pool = addr + MAYBE_SWAP (metadata[i]);
2751
2752   return 1;
2753 }
2754
2755
2756 /* Read the index file.  If everything went ok, initialize the "quick"
2757    elements of all the CUs and return 1.  Otherwise, return 0.  */
2758
2759 static int
2760 dwarf2_read_index (struct objfile *objfile)
2761 {
2762   struct mapped_index local_map, *map;
2763   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
2764   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
2765
2766   if (!read_index_from_section (objfile, objfile->name,
2767                                 use_deprecated_index_sections,
2768                                 &dwarf2_per_objfile->gdb_index, &local_map,
2769                                 &cu_list, &cu_list_elements,
2770                                 &types_list, &types_list_elements))
2771     return 0;
2772
2773   /* Don't use the index if it's empty.  */
2774   if (local_map.symbol_table_slots == 0)
2775     return 0;
2776
2777   /* If there is a .dwz file, read it so we can get its CU list as
2778      well.  */
2779   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
2780     {
2781       struct dwz_file *dwz = dwarf2_get_dwz_file ();
2782       struct mapped_index dwz_map;
2783       const gdb_byte *dwz_types_ignore;
2784       offset_type dwz_types_elements_ignore;
2785
2786       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
2787                                     1,
2788                                     &dwz->gdb_index, &dwz_map,
2789                                     &dwz_list, &dwz_list_elements,
2790                                     &dwz_types_ignore,
2791                                     &dwz_types_elements_ignore))
2792         {
2793           warning (_("could not read '.gdb_index' section from %s; skipping"),
2794                    bfd_get_filename (dwz->dwz_bfd));
2795           return 0;
2796         }
2797     }
2798
2799   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
2800                          dwz_list_elements);
2801
2802   if (types_list_elements)
2803     {
2804       struct dwarf2_section_info *section;
2805
2806       /* We can only handle a single .debug_types when we have an
2807          index.  */
2808       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
2809         return 0;
2810
2811       section = VEC_index (dwarf2_section_info_def,
2812                            dwarf2_per_objfile->types, 0);
2813
2814       create_signatured_type_table_from_index (objfile, section, types_list,
2815                                                types_list_elements);
2816     }
2817
2818   create_addrmap_from_index (objfile, &local_map);
2819
2820   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
2821   *map = local_map;
2822
2823   dwarf2_per_objfile->index_table = map;
2824   dwarf2_per_objfile->using_index = 1;
2825   dwarf2_per_objfile->quick_file_names_table =
2826     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
2827
2828   return 1;
2829 }
2830
2831 /* A helper for the "quick" functions which sets the global
2832    dwarf2_per_objfile according to OBJFILE.  */
2833
2834 static void
2835 dw2_setup (struct objfile *objfile)
2836 {
2837   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
2838   gdb_assert (dwarf2_per_objfile);
2839 }
2840
2841 /* die_reader_func for dw2_get_file_names.  */
2842
2843 static void
2844 dw2_get_file_names_reader (const struct die_reader_specs *reader,
2845                            gdb_byte *info_ptr,
2846                            struct die_info *comp_unit_die,
2847                            int has_children,
2848                            void *data)
2849 {
2850   struct dwarf2_cu *cu = reader->cu;
2851   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
2852   struct objfile *objfile = dwarf2_per_objfile->objfile;
2853   struct dwarf2_per_cu_data *lh_cu;
2854   struct line_header *lh;
2855   struct attribute *attr;
2856   int i;
2857   const char *name, *comp_dir;
2858   void **slot;
2859   struct quick_file_names *qfn;
2860   unsigned int line_offset;
2861
2862   /* Our callers never want to match partial units -- instead they
2863      will match the enclosing full CU.  */
2864   if (comp_unit_die->tag == DW_TAG_partial_unit)
2865     {
2866       this_cu->v.quick->no_file_data = 1;
2867       return;
2868     }
2869
2870   /* If we're reading the line header for TUs, store it in the "per_cu"
2871      for tu_group.  */
2872   if (this_cu->is_debug_types)
2873     {
2874       struct type_unit_group *tu_group = data;
2875
2876       gdb_assert (tu_group != NULL);
2877       lh_cu = &tu_group->per_cu;
2878     }
2879   else
2880     lh_cu = this_cu;
2881
2882   lh = NULL;
2883   slot = NULL;
2884   line_offset = 0;
2885
2886   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
2887   if (attr)
2888     {
2889       struct quick_file_names find_entry;
2890
2891       line_offset = DW_UNSND (attr);
2892
2893       /* We may have already read in this line header (TU line header sharing).
2894          If we have we're done.  */
2895       find_entry.hash.dwo_unit = cu->dwo_unit;
2896       find_entry.hash.line_offset.sect_off = line_offset;
2897       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
2898                              &find_entry, INSERT);
2899       if (*slot != NULL)
2900         {
2901           lh_cu->v.quick->file_names = *slot;
2902           return;
2903         }
2904
2905       lh = dwarf_decode_line_header (line_offset, cu);
2906     }
2907   if (lh == NULL)
2908     {
2909       lh_cu->v.quick->no_file_data = 1;
2910       return;
2911     }
2912
2913   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
2914   qfn->hash.dwo_unit = cu->dwo_unit;
2915   qfn->hash.line_offset.sect_off = line_offset;
2916   gdb_assert (slot != NULL);
2917   *slot = qfn;
2918
2919   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
2920
2921   qfn->num_file_names = lh->num_file_names;
2922   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
2923                                    lh->num_file_names * sizeof (char *));
2924   for (i = 0; i < lh->num_file_names; ++i)
2925     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
2926   qfn->real_names = NULL;
2927
2928   free_line_header (lh);
2929
2930   lh_cu->v.quick->file_names = qfn;
2931 }
2932
2933 /* A helper for the "quick" functions which attempts to read the line
2934    table for THIS_CU.  */
2935
2936 static struct quick_file_names *
2937 dw2_get_file_names (struct objfile *objfile,
2938                     struct dwarf2_per_cu_data *this_cu)
2939 {
2940   /* For TUs this should only be called on the parent group.  */
2941   if (this_cu->is_debug_types)
2942     gdb_assert (IS_TYPE_UNIT_GROUP (this_cu));
2943
2944   if (this_cu->v.quick->file_names != NULL)
2945     return this_cu->v.quick->file_names;
2946   /* If we know there is no line data, no point in looking again.  */
2947   if (this_cu->v.quick->no_file_data)
2948     return NULL;
2949
2950   /* If DWO files are in use, we can still find the DW_AT_stmt_list attribute
2951      in the stub for CUs, there's is no need to lookup the DWO file.
2952      However, that's not the case for TUs where DW_AT_stmt_list lives in the
2953      DWO file.  */
2954   if (this_cu->is_debug_types)
2955     {
2956       struct type_unit_group *tu_group = this_cu->type_unit_group;
2957
2958       init_cutu_and_read_dies (tu_group->t.first_tu, NULL, 0, 0,
2959                                dw2_get_file_names_reader, tu_group);
2960     }
2961   else
2962     init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
2963
2964   if (this_cu->v.quick->no_file_data)
2965     return NULL;
2966   return this_cu->v.quick->file_names;
2967 }
2968
2969 /* A helper for the "quick" functions which computes and caches the
2970    real path for a given file name from the line table.  */
2971
2972 static const char *
2973 dw2_get_real_path (struct objfile *objfile,
2974                    struct quick_file_names *qfn, int index)
2975 {
2976   if (qfn->real_names == NULL)
2977     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
2978                                       qfn->num_file_names, sizeof (char *));
2979
2980   if (qfn->real_names[index] == NULL)
2981     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
2982
2983   return qfn->real_names[index];
2984 }
2985
2986 static struct symtab *
2987 dw2_find_last_source_symtab (struct objfile *objfile)
2988 {
2989   int index;
2990
2991   dw2_setup (objfile);
2992   index = dwarf2_per_objfile->n_comp_units - 1;
2993   return dw2_instantiate_symtab (dw2_get_cu (index));
2994 }
2995
2996 /* Traversal function for dw2_forget_cached_source_info.  */
2997
2998 static int
2999 dw2_free_cached_file_names (void **slot, void *info)
3000 {
3001   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3002
3003   if (file_data->real_names)
3004     {
3005       int i;
3006
3007       for (i = 0; i < file_data->num_file_names; ++i)
3008         {
3009           xfree ((void*) file_data->real_names[i]);
3010           file_data->real_names[i] = NULL;
3011         }
3012     }
3013
3014   return 1;
3015 }
3016
3017 static void
3018 dw2_forget_cached_source_info (struct objfile *objfile)
3019 {
3020   dw2_setup (objfile);
3021
3022   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3023                           dw2_free_cached_file_names, NULL);
3024 }
3025
3026 /* Helper function for dw2_map_symtabs_matching_filename that expands
3027    the symtabs and calls the iterator.  */
3028
3029 static int
3030 dw2_map_expand_apply (struct objfile *objfile,
3031                       struct dwarf2_per_cu_data *per_cu,
3032                       const char *name, const char *real_path,
3033                       int (*callback) (struct symtab *, void *),
3034                       void *data)
3035 {
3036   struct symtab *last_made = objfile->symtabs;
3037
3038   /* Don't visit already-expanded CUs.  */
3039   if (per_cu->v.quick->symtab)
3040     return 0;
3041
3042   /* This may expand more than one symtab, and we want to iterate over
3043      all of them.  */
3044   dw2_instantiate_symtab (per_cu);
3045
3046   return iterate_over_some_symtabs (name, real_path, callback, data,
3047                                     objfile->symtabs, last_made);
3048 }
3049
3050 /* Implementation of the map_symtabs_matching_filename method.  */
3051
3052 static int
3053 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3054                                    const char *real_path,
3055                                    int (*callback) (struct symtab *, void *),
3056                                    void *data)
3057 {
3058   int i;
3059   const char *name_basename = lbasename (name);
3060
3061   dw2_setup (objfile);
3062
3063   /* The rule is CUs specify all the files, including those used by
3064      any TU, so there's no need to scan TUs here.  */
3065
3066   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3067     {
3068       int j;
3069       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3070       struct quick_file_names *file_data;
3071
3072       /* We only need to look at symtabs not already expanded.  */
3073       if (per_cu->v.quick->symtab)
3074         continue;
3075
3076       file_data = dw2_get_file_names (objfile, per_cu);
3077       if (file_data == NULL)
3078         continue;
3079
3080       for (j = 0; j < file_data->num_file_names; ++j)
3081         {
3082           const char *this_name = file_data->file_names[j];
3083           const char *this_real_name;
3084
3085           if (compare_filenames_for_search (this_name, name))
3086             {
3087               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3088                                         callback, data))
3089                 return 1;
3090               continue;
3091             }
3092
3093           /* Before we invoke realpath, which can get expensive when many
3094              files are involved, do a quick comparison of the basenames.  */
3095           if (! basenames_may_differ
3096               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3097             continue;
3098
3099           this_real_name = dw2_get_real_path (objfile, file_data, j);
3100           if (compare_filenames_for_search (this_real_name, name))
3101             {
3102               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3103                                         callback, data))
3104                 return 1;
3105               continue;
3106             }
3107
3108           if (real_path != NULL)
3109             {
3110               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3111               gdb_assert (IS_ABSOLUTE_PATH (name));
3112               if (this_real_name != NULL
3113                   && FILENAME_CMP (real_path, this_real_name) == 0)
3114                 {
3115                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3116                                             callback, data))
3117                     return 1;
3118                   continue;
3119                 }
3120             }
3121         }
3122     }
3123
3124   return 0;
3125 }
3126
3127 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3128
3129 struct dw2_symtab_iterator
3130 {
3131   /* The internalized form of .gdb_index.  */
3132   struct mapped_index *index;
3133   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3134   int want_specific_block;
3135   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3136      Unused if !WANT_SPECIFIC_BLOCK.  */
3137   int block_index;
3138   /* The kind of symbol we're looking for.  */
3139   domain_enum domain;
3140   /* The list of CUs from the index entry of the symbol,
3141      or NULL if not found.  */
3142   offset_type *vec;
3143   /* The next element in VEC to look at.  */
3144   int next;
3145   /* The number of elements in VEC, or zero if there is no match.  */
3146   int length;
3147 };
3148
3149 /* Initialize the index symtab iterator ITER.
3150    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3151    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3152
3153 static void
3154 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3155                       struct mapped_index *index,
3156                       int want_specific_block,
3157                       int block_index,
3158                       domain_enum domain,
3159                       const char *name)
3160 {
3161   iter->index = index;
3162   iter->want_specific_block = want_specific_block;
3163   iter->block_index = block_index;
3164   iter->domain = domain;
3165   iter->next = 0;
3166
3167   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3168     iter->length = MAYBE_SWAP (*iter->vec);
3169   else
3170     {
3171       iter->vec = NULL;
3172       iter->length = 0;
3173     }
3174 }
3175
3176 /* Return the next matching CU or NULL if there are no more.  */
3177
3178 static struct dwarf2_per_cu_data *
3179 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3180 {
3181   for ( ; iter->next < iter->length; ++iter->next)
3182     {
3183       offset_type cu_index_and_attrs =
3184         MAYBE_SWAP (iter->vec[iter->next + 1]);
3185       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3186       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (cu_index);
3187       int want_static = iter->block_index != GLOBAL_BLOCK;
3188       /* This value is only valid for index versions >= 7.  */
3189       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3190       gdb_index_symbol_kind symbol_kind =
3191         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3192       /* Only check the symbol attributes if they're present.
3193          Indices prior to version 7 don't record them,
3194          and indices >= 7 may elide them for certain symbols
3195          (gold does this).  */
3196       int attrs_valid =
3197         (iter->index->version >= 7
3198          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3199
3200       /* Skip if already read in.  */
3201       if (per_cu->v.quick->symtab)
3202         continue;
3203
3204       if (attrs_valid
3205           && iter->want_specific_block
3206           && want_static != is_static)
3207         continue;
3208
3209       /* Only check the symbol's kind if it has one.  */
3210       if (attrs_valid)
3211         {
3212           switch (iter->domain)
3213             {
3214             case VAR_DOMAIN:
3215               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3216                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3217                   /* Some types are also in VAR_DOMAIN.  */
3218                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3219                 continue;
3220               break;
3221             case STRUCT_DOMAIN:
3222               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3223                 continue;
3224               break;
3225             case LABEL_DOMAIN:
3226               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3227                 continue;
3228               break;
3229             default:
3230               break;
3231             }
3232         }
3233
3234       ++iter->next;
3235       return per_cu;
3236     }
3237
3238   return NULL;
3239 }
3240
3241 static struct symtab *
3242 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3243                    const char *name, domain_enum domain)
3244 {
3245   struct symtab *stab_best = NULL;
3246   struct mapped_index *index;
3247
3248   dw2_setup (objfile);
3249
3250   index = dwarf2_per_objfile->index_table;
3251
3252   /* index is NULL if OBJF_READNOW.  */
3253   if (index)
3254     {
3255       struct dw2_symtab_iterator iter;
3256       struct dwarf2_per_cu_data *per_cu;
3257
3258       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3259
3260       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3261         {
3262           struct symbol *sym = NULL;
3263           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3264
3265           /* Some caution must be observed with overloaded functions
3266              and methods, since the index will not contain any overload
3267              information (but NAME might contain it).  */
3268           if (stab->primary)
3269             {
3270               struct blockvector *bv = BLOCKVECTOR (stab);
3271               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3272
3273               sym = lookup_block_symbol (block, name, domain);
3274             }
3275
3276           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3277             {
3278               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3279                 return stab;
3280
3281               stab_best = stab;
3282             }
3283
3284           /* Keep looking through other CUs.  */
3285         }
3286     }
3287
3288   return stab_best;
3289 }
3290
3291 static void
3292 dw2_print_stats (struct objfile *objfile)
3293 {
3294   int i, count;
3295
3296   dw2_setup (objfile);
3297   count = 0;
3298   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3299                    + dwarf2_per_objfile->n_type_units); ++i)
3300     {
3301       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3302
3303       if (!per_cu->v.quick->symtab)
3304         ++count;
3305     }
3306   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3307 }
3308
3309 static void
3310 dw2_dump (struct objfile *objfile)
3311 {
3312   /* Nothing worth printing.  */
3313 }
3314
3315 static void
3316 dw2_relocate (struct objfile *objfile, struct section_offsets *new_offsets,
3317               struct section_offsets *delta)
3318 {
3319   /* There's nothing to relocate here.  */
3320 }
3321
3322 static void
3323 dw2_expand_symtabs_for_function (struct objfile *objfile,
3324                                  const char *func_name)
3325 {
3326   struct mapped_index *index;
3327
3328   dw2_setup (objfile);
3329
3330   index = dwarf2_per_objfile->index_table;
3331
3332   /* index is NULL if OBJF_READNOW.  */
3333   if (index)
3334     {
3335       struct dw2_symtab_iterator iter;
3336       struct dwarf2_per_cu_data *per_cu;
3337
3338       /* Note: It doesn't matter what we pass for block_index here.  */
3339       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3340                             func_name);
3341
3342       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3343         dw2_instantiate_symtab (per_cu);
3344     }
3345 }
3346
3347 static void
3348 dw2_expand_all_symtabs (struct objfile *objfile)
3349 {
3350   int i;
3351
3352   dw2_setup (objfile);
3353
3354   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3355                    + dwarf2_per_objfile->n_type_units); ++i)
3356     {
3357       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3358
3359       dw2_instantiate_symtab (per_cu);
3360     }
3361 }
3362
3363 static void
3364 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3365                                   const char *fullname)
3366 {
3367   int i;
3368
3369   dw2_setup (objfile);
3370
3371   /* We don't need to consider type units here.
3372      This is only called for examining code, e.g. expand_line_sal.
3373      There can be an order of magnitude (or more) more type units
3374      than comp units, and we avoid them if we can.  */
3375
3376   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3377     {
3378       int j;
3379       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3380       struct quick_file_names *file_data;
3381
3382       /* We only need to look at symtabs not already expanded.  */
3383       if (per_cu->v.quick->symtab)
3384         continue;
3385
3386       file_data = dw2_get_file_names (objfile, per_cu);
3387       if (file_data == NULL)
3388         continue;
3389
3390       for (j = 0; j < file_data->num_file_names; ++j)
3391         {
3392           const char *this_fullname = file_data->file_names[j];
3393
3394           if (filename_cmp (this_fullname, fullname) == 0)
3395             {
3396               dw2_instantiate_symtab (per_cu);
3397               break;
3398             }
3399         }
3400     }
3401 }
3402
3403 /* A helper function for dw2_find_symbol_file that finds the primary
3404    file name for a given CU.  This is a die_reader_func.  */
3405
3406 static void
3407 dw2_get_primary_filename_reader (const struct die_reader_specs *reader,
3408                                  gdb_byte *info_ptr,
3409                                  struct die_info *comp_unit_die,
3410                                  int has_children,
3411                                  void *data)
3412 {
3413   const char **result_ptr = data;
3414   struct dwarf2_cu *cu = reader->cu;
3415   struct attribute *attr;
3416
3417   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
3418   if (attr == NULL)
3419     *result_ptr = NULL;
3420   else
3421     *result_ptr = DW_STRING (attr);
3422 }
3423
3424 static const char *
3425 dw2_find_symbol_file (struct objfile *objfile, const char *name)
3426 {
3427   struct dwarf2_per_cu_data *per_cu;
3428   offset_type *vec;
3429   const char *filename;
3430
3431   dw2_setup (objfile);
3432
3433   /* index_table is NULL if OBJF_READNOW.  */
3434   if (!dwarf2_per_objfile->index_table)
3435     {
3436       struct symtab *s;
3437
3438       ALL_OBJFILE_PRIMARY_SYMTABS (objfile, s)
3439         {
3440           struct blockvector *bv = BLOCKVECTOR (s);
3441           const struct block *block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
3442           struct symbol *sym = lookup_block_symbol (block, name, VAR_DOMAIN);
3443
3444           if (sym)
3445             {
3446               /* Only file extension of returned filename is recognized.  */
3447               return SYMBOL_SYMTAB (sym)->filename;
3448             }
3449         }
3450       return NULL;
3451     }
3452
3453   if (!find_slot_in_mapped_hash (dwarf2_per_objfile->index_table,
3454                                  name, &vec))
3455     return NULL;
3456
3457   /* Note that this just looks at the very first one named NAME -- but
3458      actually we are looking for a function.  find_main_filename
3459      should be rewritten so that it doesn't require a custom hook.  It
3460      could just use the ordinary symbol tables.  */
3461   /* vec[0] is the length, which must always be >0.  */
3462   per_cu = dw2_get_cu (GDB_INDEX_CU_VALUE (MAYBE_SWAP (vec[1])));
3463
3464   if (per_cu->v.quick->symtab != NULL)
3465     {
3466       /* Only file extension of returned filename is recognized.  */
3467       return per_cu->v.quick->symtab->filename;
3468     }
3469
3470   init_cutu_and_read_dies (per_cu, NULL, 0, 0,
3471                            dw2_get_primary_filename_reader, &filename);
3472
3473   /* Only file extension of returned filename is recognized.  */
3474   return filename;
3475 }
3476
3477 static void
3478 dw2_map_matching_symbols (const char * name, domain_enum namespace,
3479                           struct objfile *objfile, int global,
3480                           int (*callback) (struct block *,
3481                                            struct symbol *, void *),
3482                           void *data, symbol_compare_ftype *match,
3483                           symbol_compare_ftype *ordered_compare)
3484 {
3485   /* Currently unimplemented; used for Ada.  The function can be called if the
3486      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3487      does not look for non-Ada symbols this function should just return.  */
3488 }
3489
3490 static void
3491 dw2_expand_symtabs_matching
3492   (struct objfile *objfile,
3493    int (*file_matcher) (const char *, void *, int basenames),
3494    int (*name_matcher) (const char *, void *),
3495    enum search_domain kind,
3496    void *data)
3497 {
3498   int i;
3499   offset_type iter;
3500   struct mapped_index *index;
3501
3502   dw2_setup (objfile);
3503
3504   /* index_table is NULL if OBJF_READNOW.  */
3505   if (!dwarf2_per_objfile->index_table)
3506     return;
3507   index = dwarf2_per_objfile->index_table;
3508
3509   if (file_matcher != NULL)
3510     {
3511       struct cleanup *cleanup;
3512       htab_t visited_found, visited_not_found;
3513
3514       visited_found = htab_create_alloc (10,
3515                                          htab_hash_pointer, htab_eq_pointer,
3516                                          NULL, xcalloc, xfree);
3517       cleanup = make_cleanup_htab_delete (visited_found);
3518       visited_not_found = htab_create_alloc (10,
3519                                              htab_hash_pointer, htab_eq_pointer,
3520                                              NULL, xcalloc, xfree);
3521       make_cleanup_htab_delete (visited_not_found);
3522
3523       /* The rule is CUs specify all the files, including those used by
3524          any TU, so there's no need to scan TUs here.  */
3525
3526       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3527         {
3528           int j;
3529           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3530           struct quick_file_names *file_data;
3531           void **slot;
3532
3533           per_cu->v.quick->mark = 0;
3534
3535           /* We only need to look at symtabs not already expanded.  */
3536           if (per_cu->v.quick->symtab)
3537             continue;
3538
3539           file_data = dw2_get_file_names (objfile, per_cu);
3540           if (file_data == NULL)
3541             continue;
3542
3543           if (htab_find (visited_not_found, file_data) != NULL)
3544             continue;
3545           else if (htab_find (visited_found, file_data) != NULL)
3546             {
3547               per_cu->v.quick->mark = 1;
3548               continue;
3549             }
3550
3551           for (j = 0; j < file_data->num_file_names; ++j)
3552             {
3553               const char *this_real_name;
3554
3555               if (file_matcher (file_data->file_names[j], data, 0))
3556                 {
3557                   per_cu->v.quick->mark = 1;
3558                   break;
3559                 }
3560
3561               /* Before we invoke realpath, which can get expensive when many
3562                  files are involved, do a quick comparison of the basenames.  */
3563               if (!basenames_may_differ
3564                   && !file_matcher (lbasename (file_data->file_names[j]),
3565                                     data, 1))
3566                 continue;
3567
3568               this_real_name = dw2_get_real_path (objfile, file_data, j);
3569               if (file_matcher (this_real_name, data, 0))
3570                 {
3571                   per_cu->v.quick->mark = 1;
3572                   break;
3573                 }
3574             }
3575
3576           slot = htab_find_slot (per_cu->v.quick->mark
3577                                  ? visited_found
3578                                  : visited_not_found,
3579                                  file_data, INSERT);
3580           *slot = file_data;
3581         }
3582
3583       do_cleanups (cleanup);
3584     }
3585
3586   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3587     {
3588       offset_type idx = 2 * iter;
3589       const char *name;
3590       offset_type *vec, vec_len, vec_idx;
3591
3592       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3593         continue;
3594
3595       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3596
3597       if (! (*name_matcher) (name, data))
3598         continue;
3599
3600       /* The name was matched, now expand corresponding CUs that were
3601          marked.  */
3602       vec = (offset_type *) (index->constant_pool
3603                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3604       vec_len = MAYBE_SWAP (vec[0]);
3605       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3606         {
3607           struct dwarf2_per_cu_data *per_cu;
3608           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3609           gdb_index_symbol_kind symbol_kind =
3610             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3611           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3612
3613           /* Don't crash on bad data.  */
3614           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3615                            + dwarf2_per_objfile->n_type_units))
3616             continue;
3617
3618           /* Only check the symbol's kind if it has one.
3619              Indices prior to version 7 don't record it.  */
3620           if (index->version >= 7)
3621             {
3622               switch (kind)
3623                 {
3624                 case VARIABLES_DOMAIN:
3625                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3626                     continue;
3627                   break;
3628                 case FUNCTIONS_DOMAIN:
3629                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3630                     continue;
3631                   break;
3632                 case TYPES_DOMAIN:
3633                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3634                     continue;
3635                   break;
3636                 default:
3637                   break;
3638                 }
3639             }
3640
3641           per_cu = dw2_get_cu (cu_index);
3642           if (file_matcher == NULL || per_cu->v.quick->mark)
3643             dw2_instantiate_symtab (per_cu);
3644         }
3645     }
3646 }
3647
3648 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3649    symtab.  */
3650
3651 static struct symtab *
3652 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3653 {
3654   int i;
3655
3656   if (BLOCKVECTOR (symtab) != NULL
3657       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3658     return symtab;
3659
3660   if (symtab->includes == NULL)
3661     return NULL;
3662
3663   for (i = 0; symtab->includes[i]; ++i)
3664     {
3665       struct symtab *s = symtab->includes[i];
3666
3667       s = recursively_find_pc_sect_symtab (s, pc);
3668       if (s != NULL)
3669         return s;
3670     }
3671
3672   return NULL;
3673 }
3674
3675 static struct symtab *
3676 dw2_find_pc_sect_symtab (struct objfile *objfile,
3677                          struct minimal_symbol *msymbol,
3678                          CORE_ADDR pc,
3679                          struct obj_section *section,
3680                          int warn_if_readin)
3681 {
3682   struct dwarf2_per_cu_data *data;
3683   struct symtab *result;
3684
3685   dw2_setup (objfile);
3686
3687   if (!objfile->psymtabs_addrmap)
3688     return NULL;
3689
3690   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3691   if (!data)
3692     return NULL;
3693
3694   if (warn_if_readin && data->v.quick->symtab)
3695     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3696              paddress (get_objfile_arch (objfile), pc));
3697
3698   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3699   gdb_assert (result != NULL);
3700   return result;
3701 }
3702
3703 static void
3704 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3705                           void *data, int need_fullname)
3706 {
3707   int i;
3708   struct cleanup *cleanup;
3709   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3710                                       NULL, xcalloc, xfree);
3711
3712   cleanup = make_cleanup_htab_delete (visited);
3713   dw2_setup (objfile);
3714
3715   /* The rule is CUs specify all the files, including those used by
3716      any TU, so there's no need to scan TUs here.
3717      We can ignore file names coming from already-expanded CUs.  */
3718
3719   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3720     {
3721       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3722
3723       if (per_cu->v.quick->symtab)
3724         {
3725           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3726                                         INSERT);
3727
3728           *slot = per_cu->v.quick->file_names;
3729         }
3730     }
3731
3732   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3733     {
3734       int j;
3735       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3736       struct quick_file_names *file_data;
3737       void **slot;
3738
3739       /* We only need to look at symtabs not already expanded.  */
3740       if (per_cu->v.quick->symtab)
3741         continue;
3742
3743       file_data = dw2_get_file_names (objfile, per_cu);
3744       if (file_data == NULL)
3745         continue;
3746
3747       slot = htab_find_slot (visited, file_data, INSERT);
3748       if (*slot)
3749         {
3750           /* Already visited.  */
3751           continue;
3752         }
3753       *slot = file_data;
3754
3755       for (j = 0; j < file_data->num_file_names; ++j)
3756         {
3757           const char *this_real_name;
3758
3759           if (need_fullname)
3760             this_real_name = dw2_get_real_path (objfile, file_data, j);
3761           else
3762             this_real_name = NULL;
3763           (*fun) (file_data->file_names[j], this_real_name, data);
3764         }
3765     }
3766
3767   do_cleanups (cleanup);
3768 }
3769
3770 static int
3771 dw2_has_symbols (struct objfile *objfile)
3772 {
3773   return 1;
3774 }
3775
3776 const struct quick_symbol_functions dwarf2_gdb_index_functions =
3777 {
3778   dw2_has_symbols,
3779   dw2_find_last_source_symtab,
3780   dw2_forget_cached_source_info,
3781   dw2_map_symtabs_matching_filename,
3782   dw2_lookup_symbol,
3783   dw2_print_stats,
3784   dw2_dump,
3785   dw2_relocate,
3786   dw2_expand_symtabs_for_function,
3787   dw2_expand_all_symtabs,
3788   dw2_expand_symtabs_with_fullname,
3789   dw2_find_symbol_file,
3790   dw2_map_matching_symbols,
3791   dw2_expand_symtabs_matching,
3792   dw2_find_pc_sect_symtab,
3793   dw2_map_symbol_filenames
3794 };
3795
3796 /* Initialize for reading DWARF for this objfile.  Return 0 if this
3797    file will use psymtabs, or 1 if using the GNU index.  */
3798
3799 int
3800 dwarf2_initialize_objfile (struct objfile *objfile)
3801 {
3802   /* If we're about to read full symbols, don't bother with the
3803      indices.  In this case we also don't care if some other debug
3804      format is making psymtabs, because they are all about to be
3805      expanded anyway.  */
3806   if ((objfile->flags & OBJF_READNOW))
3807     {
3808       int i;
3809
3810       dwarf2_per_objfile->using_index = 1;
3811       create_all_comp_units (objfile);
3812       create_all_type_units (objfile);
3813       dwarf2_per_objfile->quick_file_names_table =
3814         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3815
3816       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3817                        + dwarf2_per_objfile->n_type_units); ++i)
3818         {
3819           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3820
3821           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3822                                             struct dwarf2_per_cu_quick_data);
3823         }
3824
3825       /* Return 1 so that gdb sees the "quick" functions.  However,
3826          these functions will be no-ops because we will have expanded
3827          all symtabs.  */
3828       return 1;
3829     }
3830
3831   if (dwarf2_read_index (objfile))
3832     return 1;
3833
3834   return 0;
3835 }
3836
3837 \f
3838
3839 /* Build a partial symbol table.  */
3840
3841 void
3842 dwarf2_build_psymtabs (struct objfile *objfile)
3843 {
3844   volatile struct gdb_exception except;
3845
3846   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
3847     {
3848       init_psymbol_list (objfile, 1024);
3849     }
3850
3851   TRY_CATCH (except, RETURN_MASK_ERROR)
3852     {
3853       /* This isn't really ideal: all the data we allocate on the
3854          objfile's obstack is still uselessly kept around.  However,
3855          freeing it seems unsafe.  */
3856       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
3857
3858       dwarf2_build_psymtabs_hard (objfile);
3859       discard_cleanups (cleanups);
3860     }
3861   if (except.reason < 0)
3862     exception_print (gdb_stderr, except);
3863 }
3864
3865 /* Return the total length of the CU described by HEADER.  */
3866
3867 static unsigned int
3868 get_cu_length (const struct comp_unit_head *header)
3869 {
3870   return header->initial_length_size + header->length;
3871 }
3872
3873 /* Return TRUE if OFFSET is within CU_HEADER.  */
3874
3875 static inline int
3876 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
3877 {
3878   sect_offset bottom = { cu_header->offset.sect_off };
3879   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
3880
3881   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
3882 }
3883
3884 /* Find the base address of the compilation unit for range lists and
3885    location lists.  It will normally be specified by DW_AT_low_pc.
3886    In DWARF-3 draft 4, the base address could be overridden by
3887    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
3888    compilation units with discontinuous ranges.  */
3889
3890 static void
3891 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
3892 {
3893   struct attribute *attr;
3894
3895   cu->base_known = 0;
3896   cu->base_address = 0;
3897
3898   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
3899   if (attr)
3900     {
3901       cu->base_address = DW_ADDR (attr);
3902       cu->base_known = 1;
3903     }
3904   else
3905     {
3906       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
3907       if (attr)
3908         {
3909           cu->base_address = DW_ADDR (attr);
3910           cu->base_known = 1;
3911         }
3912     }
3913 }
3914
3915 /* Read in the comp unit header information from the debug_info at info_ptr.
3916    NOTE: This leaves members offset, first_die_offset to be filled in
3917    by the caller.  */
3918
3919 static gdb_byte *
3920 read_comp_unit_head (struct comp_unit_head *cu_header,
3921                      gdb_byte *info_ptr, bfd *abfd)
3922 {
3923   int signed_addr;
3924   unsigned int bytes_read;
3925
3926   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
3927   cu_header->initial_length_size = bytes_read;
3928   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
3929   info_ptr += bytes_read;
3930   cu_header->version = read_2_bytes (abfd, info_ptr);
3931   info_ptr += 2;
3932   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
3933                                              &bytes_read);
3934   info_ptr += bytes_read;
3935   cu_header->addr_size = read_1_byte (abfd, info_ptr);
3936   info_ptr += 1;
3937   signed_addr = bfd_get_sign_extend_vma (abfd);
3938   if (signed_addr < 0)
3939     internal_error (__FILE__, __LINE__,
3940                     _("read_comp_unit_head: dwarf from non elf file"));
3941   cu_header->signed_addr_p = signed_addr;
3942
3943   return info_ptr;
3944 }
3945
3946 /* Helper function that returns the proper abbrev section for
3947    THIS_CU.  */
3948
3949 static struct dwarf2_section_info *
3950 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
3951 {
3952   struct dwarf2_section_info *abbrev;
3953
3954   if (this_cu->is_dwz)
3955     abbrev = &dwarf2_get_dwz_file ()->abbrev;
3956   else
3957     abbrev = &dwarf2_per_objfile->abbrev;
3958
3959   return abbrev;
3960 }
3961
3962 /* Subroutine of read_and_check_comp_unit_head and
3963    read_and_check_type_unit_head to simplify them.
3964    Perform various error checking on the header.  */
3965
3966 static void
3967 error_check_comp_unit_head (struct comp_unit_head *header,
3968                             struct dwarf2_section_info *section,
3969                             struct dwarf2_section_info *abbrev_section)
3970 {
3971   bfd *abfd = section->asection->owner;
3972   const char *filename = bfd_get_filename (abfd);
3973
3974   if (header->version != 2 && header->version != 3 && header->version != 4)
3975     error (_("Dwarf Error: wrong version in compilation unit header "
3976            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
3977            filename);
3978
3979   if (header->abbrev_offset.sect_off
3980       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
3981     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
3982            "(offset 0x%lx + 6) [in module %s]"),
3983            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
3984            filename);
3985
3986   /* Cast to unsigned long to use 64-bit arithmetic when possible to
3987      avoid potential 32-bit overflow.  */
3988   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
3989       > section->size)
3990     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
3991            "(offset 0x%lx + 0) [in module %s]"),
3992            (long) header->length, (long) header->offset.sect_off,
3993            filename);
3994 }
3995
3996 /* Read in a CU/TU header and perform some basic error checking.
3997    The contents of the header are stored in HEADER.
3998    The result is a pointer to the start of the first DIE.  */
3999
4000 static gdb_byte *
4001 read_and_check_comp_unit_head (struct comp_unit_head *header,
4002                                struct dwarf2_section_info *section,
4003                                struct dwarf2_section_info *abbrev_section,
4004                                gdb_byte *info_ptr,
4005                                int is_debug_types_section)
4006 {
4007   gdb_byte *beg_of_comp_unit = info_ptr;
4008   bfd *abfd = section->asection->owner;
4009
4010   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4011
4012   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4013
4014   /* If we're reading a type unit, skip over the signature and
4015      type_offset fields.  */
4016   if (is_debug_types_section)
4017     info_ptr += 8 /*signature*/ + header->offset_size;
4018
4019   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4020
4021   error_check_comp_unit_head (header, section, abbrev_section);
4022
4023   return info_ptr;
4024 }
4025
4026 /* Read in the types comp unit header information from .debug_types entry at
4027    types_ptr.  The result is a pointer to one past the end of the header.  */
4028
4029 static gdb_byte *
4030 read_and_check_type_unit_head (struct comp_unit_head *header,
4031                                struct dwarf2_section_info *section,
4032                                struct dwarf2_section_info *abbrev_section,
4033                                gdb_byte *info_ptr,
4034                                ULONGEST *signature,
4035                                cu_offset *type_offset_in_tu)
4036 {
4037   gdb_byte *beg_of_comp_unit = info_ptr;
4038   bfd *abfd = section->asection->owner;
4039
4040   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4041
4042   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4043
4044   /* If we're reading a type unit, skip over the signature and
4045      type_offset fields.  */
4046   if (signature != NULL)
4047     *signature = read_8_bytes (abfd, info_ptr);
4048   info_ptr += 8;
4049   if (type_offset_in_tu != NULL)
4050     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4051                                                header->offset_size);
4052   info_ptr += header->offset_size;
4053
4054   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4055
4056   error_check_comp_unit_head (header, section, abbrev_section);
4057
4058   return info_ptr;
4059 }
4060
4061 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4062
4063 static sect_offset
4064 read_abbrev_offset (struct dwarf2_section_info *section,
4065                     sect_offset offset)
4066 {
4067   bfd *abfd = section->asection->owner;
4068   gdb_byte *info_ptr;
4069   unsigned int length, initial_length_size, offset_size;
4070   sect_offset abbrev_offset;
4071
4072   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4073   info_ptr = section->buffer + offset.sect_off;
4074   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4075   offset_size = initial_length_size == 4 ? 4 : 8;
4076   info_ptr += initial_length_size + 2 /*version*/;
4077   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4078   return abbrev_offset;
4079 }
4080
4081 /* Allocate a new partial symtab for file named NAME and mark this new
4082    partial symtab as being an include of PST.  */
4083
4084 static void
4085 dwarf2_create_include_psymtab (char *name, struct partial_symtab *pst,
4086                                struct objfile *objfile)
4087 {
4088   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4089
4090   if (!IS_ABSOLUTE_PATH (subpst->filename))
4091     {
4092       /* It shares objfile->objfile_obstack.  */
4093       subpst->dirname = pst->dirname;
4094     }
4095
4096   subpst->section_offsets = pst->section_offsets;
4097   subpst->textlow = 0;
4098   subpst->texthigh = 0;
4099
4100   subpst->dependencies = (struct partial_symtab **)
4101     obstack_alloc (&objfile->objfile_obstack,
4102                    sizeof (struct partial_symtab *));
4103   subpst->dependencies[0] = pst;
4104   subpst->number_of_dependencies = 1;
4105
4106   subpst->globals_offset = 0;
4107   subpst->n_global_syms = 0;
4108   subpst->statics_offset = 0;
4109   subpst->n_static_syms = 0;
4110   subpst->symtab = NULL;
4111   subpst->read_symtab = pst->read_symtab;
4112   subpst->readin = 0;
4113
4114   /* No private part is necessary for include psymtabs.  This property
4115      can be used to differentiate between such include psymtabs and
4116      the regular ones.  */
4117   subpst->read_symtab_private = NULL;
4118 }
4119
4120 /* Read the Line Number Program data and extract the list of files
4121    included by the source file represented by PST.  Build an include
4122    partial symtab for each of these included files.  */
4123
4124 static void
4125 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4126                                struct die_info *die,
4127                                struct partial_symtab *pst)
4128 {
4129   struct line_header *lh = NULL;
4130   struct attribute *attr;
4131
4132   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4133   if (attr)
4134     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4135   if (lh == NULL)
4136     return;  /* No linetable, so no includes.  */
4137
4138   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4139   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4140
4141   free_line_header (lh);
4142 }
4143
4144 static hashval_t
4145 hash_signatured_type (const void *item)
4146 {
4147   const struct signatured_type *sig_type = item;
4148
4149   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4150   return sig_type->signature;
4151 }
4152
4153 static int
4154 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4155 {
4156   const struct signatured_type *lhs = item_lhs;
4157   const struct signatured_type *rhs = item_rhs;
4158
4159   return lhs->signature == rhs->signature;
4160 }
4161
4162 /* Allocate a hash table for signatured types.  */
4163
4164 static htab_t
4165 allocate_signatured_type_table (struct objfile *objfile)
4166 {
4167   return htab_create_alloc_ex (41,
4168                                hash_signatured_type,
4169                                eq_signatured_type,
4170                                NULL,
4171                                &objfile->objfile_obstack,
4172                                hashtab_obstack_allocate,
4173                                dummy_obstack_deallocate);
4174 }
4175
4176 /* A helper function to add a signatured type CU to a table.  */
4177
4178 static int
4179 add_signatured_type_cu_to_table (void **slot, void *datum)
4180 {
4181   struct signatured_type *sigt = *slot;
4182   struct signatured_type ***datap = datum;
4183
4184   **datap = sigt;
4185   ++*datap;
4186
4187   return 1;
4188 }
4189
4190 /* Create the hash table of all entries in the .debug_types section.
4191    DWO_FILE is a pointer to the DWO file for .debug_types.dwo,
4192    NULL otherwise.
4193    Note: This function processes DWO files only, not DWP files.
4194    The result is a pointer to the hash table or NULL if there are
4195    no types.  */
4196
4197 static htab_t
4198 create_debug_types_hash_table (struct dwo_file *dwo_file,
4199                                VEC (dwarf2_section_info_def) *types)
4200 {
4201   struct objfile *objfile = dwarf2_per_objfile->objfile;
4202   htab_t types_htab = NULL;
4203   int ix;
4204   struct dwarf2_section_info *section;
4205   struct dwarf2_section_info *abbrev_section;
4206
4207   if (VEC_empty (dwarf2_section_info_def, types))
4208     return NULL;
4209
4210   abbrev_section = (dwo_file != NULL
4211                     ? &dwo_file->sections.abbrev
4212                     : &dwarf2_per_objfile->abbrev);
4213
4214   if (dwarf2_read_debug)
4215     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4216                         dwo_file ? ".dwo" : "",
4217                         bfd_get_filename (abbrev_section->asection->owner));
4218
4219   for (ix = 0;
4220        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4221        ++ix)
4222     {
4223       bfd *abfd;
4224       gdb_byte *info_ptr, *end_ptr;
4225       struct dwarf2_section_info *abbrev_section;
4226
4227       dwarf2_read_section (objfile, section);
4228       info_ptr = section->buffer;
4229
4230       if (info_ptr == NULL)
4231         continue;
4232
4233       /* We can't set abfd until now because the section may be empty or
4234          not present, in which case section->asection will be NULL.  */
4235       abfd = section->asection->owner;
4236
4237       if (dwo_file)
4238         abbrev_section = &dwo_file->sections.abbrev;
4239       else
4240         abbrev_section = &dwarf2_per_objfile->abbrev;
4241
4242       if (types_htab == NULL)
4243         {
4244           if (dwo_file)
4245             types_htab = allocate_dwo_unit_table (objfile);
4246           else
4247             types_htab = allocate_signatured_type_table (objfile);
4248         }
4249
4250       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4251          because we don't need to read any dies: the signature is in the
4252          header.  */
4253
4254       end_ptr = info_ptr + section->size;
4255       while (info_ptr < end_ptr)
4256         {
4257           sect_offset offset;
4258           cu_offset type_offset_in_tu;
4259           ULONGEST signature;
4260           struct signatured_type *sig_type;
4261           struct dwo_unit *dwo_tu;
4262           void **slot;
4263           gdb_byte *ptr = info_ptr;
4264           struct comp_unit_head header;
4265           unsigned int length;
4266
4267           offset.sect_off = ptr - section->buffer;
4268
4269           /* We need to read the type's signature in order to build the hash
4270              table, but we don't need anything else just yet.  */
4271
4272           ptr = read_and_check_type_unit_head (&header, section,
4273                                                abbrev_section, ptr,
4274                                                &signature, &type_offset_in_tu);
4275
4276           length = get_cu_length (&header);
4277
4278           /* Skip dummy type units.  */
4279           if (ptr >= info_ptr + length
4280               || peek_abbrev_code (abfd, ptr) == 0)
4281             {
4282               info_ptr += length;
4283               continue;
4284             }
4285
4286           if (dwo_file)
4287             {
4288               sig_type = NULL;
4289               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4290                                        struct dwo_unit);
4291               dwo_tu->dwo_file = dwo_file;
4292               dwo_tu->signature = signature;
4293               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4294               dwo_tu->info_or_types_section = section;
4295               dwo_tu->offset = offset;
4296               dwo_tu->length = length;
4297             }
4298           else
4299             {
4300               /* N.B.: type_offset is not usable if this type uses a DWO file.
4301                  The real type_offset is in the DWO file.  */
4302               dwo_tu = NULL;
4303               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4304                                          struct signatured_type);
4305               sig_type->signature = signature;
4306               sig_type->type_offset_in_tu = type_offset_in_tu;
4307               sig_type->per_cu.objfile = objfile;
4308               sig_type->per_cu.is_debug_types = 1;
4309               sig_type->per_cu.info_or_types_section = section;
4310               sig_type->per_cu.offset = offset;
4311               sig_type->per_cu.length = length;
4312             }
4313
4314           slot = htab_find_slot (types_htab,
4315                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4316                                  INSERT);
4317           gdb_assert (slot != NULL);
4318           if (*slot != NULL)
4319             {
4320               sect_offset dup_offset;
4321
4322               if (dwo_file)
4323                 {
4324                   const struct dwo_unit *dup_tu = *slot;
4325
4326                   dup_offset = dup_tu->offset;
4327                 }
4328               else
4329                 {
4330                   const struct signatured_type *dup_tu = *slot;
4331
4332                   dup_offset = dup_tu->per_cu.offset;
4333                 }
4334
4335               complaint (&symfile_complaints,
4336                          _("debug type entry at offset 0x%x is duplicate to the "
4337                            "entry at offset 0x%x, signature 0x%s"),
4338                          offset.sect_off, dup_offset.sect_off,
4339                          phex (signature, sizeof (signature)));
4340             }
4341           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4342
4343           if (dwarf2_read_debug)
4344             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature 0x%s\n",
4345                                 offset.sect_off,
4346                                 phex (signature, sizeof (signature)));
4347
4348           info_ptr += length;
4349         }
4350     }
4351
4352   return types_htab;
4353 }
4354
4355 /* Create the hash table of all entries in the .debug_types section,
4356    and initialize all_type_units.
4357    The result is zero if there is an error (e.g. missing .debug_types section),
4358    otherwise non-zero.  */
4359
4360 static int
4361 create_all_type_units (struct objfile *objfile)
4362 {
4363   htab_t types_htab;
4364   struct signatured_type **iter;
4365
4366   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4367   if (types_htab == NULL)
4368     {
4369       dwarf2_per_objfile->signatured_types = NULL;
4370       return 0;
4371     }
4372
4373   dwarf2_per_objfile->signatured_types = types_htab;
4374
4375   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4376   dwarf2_per_objfile->all_type_units
4377     = obstack_alloc (&objfile->objfile_obstack,
4378                      dwarf2_per_objfile->n_type_units
4379                      * sizeof (struct signatured_type *));
4380   iter = &dwarf2_per_objfile->all_type_units[0];
4381   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4382   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4383               == dwarf2_per_objfile->n_type_units);
4384
4385   return 1;
4386 }
4387
4388 /* Lookup a signature based type for DW_FORM_ref_sig8.
4389    Returns NULL if signature SIG is not present in the table.  */
4390
4391 static struct signatured_type *
4392 lookup_signatured_type (ULONGEST sig)
4393 {
4394   struct signatured_type find_entry, *entry;
4395
4396   if (dwarf2_per_objfile->signatured_types == NULL)
4397     {
4398       complaint (&symfile_complaints,
4399                  _("missing `.debug_types' section for DW_FORM_ref_sig8 die"));
4400       return NULL;
4401     }
4402
4403   find_entry.signature = sig;
4404   entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4405   return entry;
4406 }
4407 \f
4408 /* Low level DIE reading support.  */
4409
4410 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4411
4412 static void
4413 init_cu_die_reader (struct die_reader_specs *reader,
4414                     struct dwarf2_cu *cu,
4415                     struct dwarf2_section_info *section,
4416                     struct dwo_file *dwo_file)
4417 {
4418   gdb_assert (section->readin && section->buffer != NULL);
4419   reader->abfd = section->asection->owner;
4420   reader->cu = cu;
4421   reader->dwo_file = dwo_file;
4422   reader->die_section = section;
4423   reader->buffer = section->buffer;
4424   reader->buffer_end = section->buffer + section->size;
4425 }
4426
4427 /* Initialize a CU (or TU) and read its DIEs.
4428    If the CU defers to a DWO file, read the DWO file as well.
4429
4430    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
4431    Otherwise the table specified in the comp unit header is read in and used.
4432    This is an optimization for when we already have the abbrev table.
4433
4434    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
4435    Otherwise, a new CU is allocated with xmalloc.
4436
4437    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
4438    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
4439
4440    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4441    linker) then DIE_READER_FUNC will not get called.  */
4442
4443 static void
4444 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
4445                          struct abbrev_table *abbrev_table,
4446                          int use_existing_cu, int keep,
4447                          die_reader_func_ftype *die_reader_func,
4448                          void *data)
4449 {
4450   struct objfile *objfile = dwarf2_per_objfile->objfile;
4451   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4452   bfd *abfd = section->asection->owner;
4453   struct dwarf2_cu *cu;
4454   gdb_byte *begin_info_ptr, *info_ptr;
4455   struct die_reader_specs reader;
4456   struct die_info *comp_unit_die;
4457   int has_children;
4458   struct attribute *attr;
4459   struct cleanup *cleanups, *free_cu_cleanup = NULL;
4460   struct signatured_type *sig_type = NULL;
4461   struct dwarf2_section_info *abbrev_section;
4462   /* Non-zero if CU currently points to a DWO file and we need to
4463      reread it.  When this happens we need to reread the skeleton die
4464      before we can reread the DWO file.  */
4465   int rereading_dwo_cu = 0;
4466
4467   if (dwarf2_die_debug)
4468     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4469                         this_cu->is_debug_types ? "type" : "comp",
4470                         this_cu->offset.sect_off);
4471
4472   if (use_existing_cu)
4473     gdb_assert (keep);
4474
4475   cleanups = make_cleanup (null_cleanup, NULL);
4476
4477   /* This is cheap if the section is already read in.  */
4478   dwarf2_read_section (objfile, section);
4479
4480   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4481
4482   abbrev_section = get_abbrev_section_for_cu (this_cu);
4483
4484   if (use_existing_cu && this_cu->cu != NULL)
4485     {
4486       cu = this_cu->cu;
4487
4488       /* If this CU is from a DWO file we need to start over, we need to
4489          refetch the attributes from the skeleton CU.
4490          This could be optimized by retrieving those attributes from when we
4491          were here the first time: the previous comp_unit_die was stored in
4492          comp_unit_obstack.  But there's no data yet that we need this
4493          optimization.  */
4494       if (cu->dwo_unit != NULL)
4495         rereading_dwo_cu = 1;
4496     }
4497   else
4498     {
4499       /* If !use_existing_cu, this_cu->cu must be NULL.  */
4500       gdb_assert (this_cu->cu == NULL);
4501
4502       cu = xmalloc (sizeof (*cu));
4503       init_one_comp_unit (cu, this_cu);
4504
4505       /* If an error occurs while loading, release our storage.  */
4506       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
4507     }
4508
4509   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
4510     {
4511       /* We already have the header, there's no need to read it in again.  */
4512       info_ptr += cu->header.first_die_offset.cu_off;
4513     }
4514   else
4515     {
4516       if (this_cu->is_debug_types)
4517         {
4518           ULONGEST signature;
4519           cu_offset type_offset_in_tu;
4520
4521           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4522                                                     abbrev_section, info_ptr,
4523                                                     &signature,
4524                                                     &type_offset_in_tu);
4525
4526           /* Since per_cu is the first member of struct signatured_type,
4527              we can go from a pointer to one to a pointer to the other.  */
4528           sig_type = (struct signatured_type *) this_cu;
4529           gdb_assert (sig_type->signature == signature);
4530           gdb_assert (sig_type->type_offset_in_tu.cu_off
4531                       == type_offset_in_tu.cu_off);
4532           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4533
4534           /* LENGTH has not been set yet for type units if we're
4535              using .gdb_index.  */
4536           this_cu->length = get_cu_length (&cu->header);
4537
4538           /* Establish the type offset that can be used to lookup the type.  */
4539           sig_type->type_offset_in_section.sect_off =
4540             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
4541         }
4542       else
4543         {
4544           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4545                                                     abbrev_section,
4546                                                     info_ptr, 0);
4547
4548           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
4549           gdb_assert (this_cu->length == get_cu_length (&cu->header));
4550         }
4551     }
4552
4553   /* Skip dummy compilation units.  */
4554   if (info_ptr >= begin_info_ptr + this_cu->length
4555       || peek_abbrev_code (abfd, info_ptr) == 0)
4556     {
4557       do_cleanups (cleanups);
4558       return;
4559     }
4560
4561   /* If we don't have them yet, read the abbrevs for this compilation unit.
4562      And if we need to read them now, make sure they're freed when we're
4563      done.  Note that it's important that if the CU had an abbrev table
4564      on entry we don't free it when we're done: Somewhere up the call stack
4565      it may be in use.  */
4566   if (abbrev_table != NULL)
4567     {
4568       gdb_assert (cu->abbrev_table == NULL);
4569       gdb_assert (cu->header.abbrev_offset.sect_off
4570                   == abbrev_table->offset.sect_off);
4571       cu->abbrev_table = abbrev_table;
4572     }
4573   else if (cu->abbrev_table == NULL)
4574     {
4575       dwarf2_read_abbrevs (cu, abbrev_section);
4576       make_cleanup (dwarf2_free_abbrev_table, cu);
4577     }
4578   else if (rereading_dwo_cu)
4579     {
4580       dwarf2_free_abbrev_table (cu);
4581       dwarf2_read_abbrevs (cu, abbrev_section);
4582     }
4583
4584   /* Read the top level CU/TU die.  */
4585   init_cu_die_reader (&reader, cu, section, NULL);
4586   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4587
4588   /* If we have a DWO stub, process it and then read in the DWO file.
4589      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains
4590      a DWO CU, that this test will fail.  */
4591   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
4592   if (attr)
4593     {
4594       const char *dwo_name = DW_STRING (attr);
4595       const char *comp_dir_string;
4596       struct dwo_unit *dwo_unit;
4597       ULONGEST signature; /* Or dwo_id.  */
4598       struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4599       int i,num_extra_attrs;
4600       struct dwarf2_section_info *dwo_abbrev_section;
4601
4602       if (has_children)
4603         error (_("Dwarf Error: compilation unit with DW_AT_GNU_dwo_name"
4604                  " has children (offset 0x%x) [in module %s]"),
4605                this_cu->offset.sect_off, bfd_get_filename (abfd));
4606
4607       /* These attributes aren't processed until later:
4608          DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4609          However, the attribute is found in the stub which we won't have later.
4610          In order to not impose this complication on the rest of the code,
4611          we read them here and copy them to the DWO CU/TU die.  */
4612
4613       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4614          DWO file.  */
4615       stmt_list = NULL;
4616       if (! this_cu->is_debug_types)
4617         stmt_list = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
4618       low_pc = dwarf2_attr (comp_unit_die, DW_AT_low_pc, cu);
4619       high_pc = dwarf2_attr (comp_unit_die, DW_AT_high_pc, cu);
4620       ranges = dwarf2_attr (comp_unit_die, DW_AT_ranges, cu);
4621       comp_dir = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4622
4623       /* There should be a DW_AT_addr_base attribute here (if needed).
4624          We need the value before we can process DW_FORM_GNU_addr_index.  */
4625       cu->addr_base = 0;
4626       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_addr_base, cu);
4627       if (attr)
4628         cu->addr_base = DW_UNSND (attr);
4629
4630       /* There should be a DW_AT_ranges_base attribute here (if needed).
4631          We need the value before we can process DW_AT_ranges.  */
4632       cu->ranges_base = 0;
4633       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_ranges_base, cu);
4634       if (attr)
4635         cu->ranges_base = DW_UNSND (attr);
4636
4637       if (this_cu->is_debug_types)
4638         {
4639           gdb_assert (sig_type != NULL);
4640           signature = sig_type->signature;
4641         }
4642       else
4643         {
4644           attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
4645           if (! attr)
4646             error (_("Dwarf Error: missing dwo_id [in module %s]"),
4647                    dwo_name);
4648           signature = DW_UNSND (attr);
4649         }
4650
4651       /* We may need the comp_dir in order to find the DWO file.  */
4652       comp_dir_string = NULL;
4653       if (comp_dir)
4654         comp_dir_string = DW_STRING (comp_dir);
4655
4656       if (this_cu->is_debug_types)
4657         dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir_string);
4658       else
4659         dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir_string,
4660                                          signature);
4661
4662       if (dwo_unit == NULL)
4663         {
4664           error (_("Dwarf Error: CU at offset 0x%x references unknown DWO"
4665                    " with ID %s [in module %s]"),
4666                  this_cu->offset.sect_off,
4667                  phex (signature, sizeof (signature)),
4668                  objfile->name);
4669         }
4670
4671       /* Set up for reading the DWO CU/TU.  */
4672       cu->dwo_unit = dwo_unit;
4673       section = dwo_unit->info_or_types_section;
4674       dwarf2_read_section (objfile, section);
4675       begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4676       dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4677       init_cu_die_reader (&reader, cu, section, dwo_unit->dwo_file);
4678
4679       if (this_cu->is_debug_types)
4680         {
4681           ULONGEST signature;
4682           cu_offset type_offset_in_tu;
4683
4684           info_ptr = read_and_check_type_unit_head (&cu->header, section,
4685                                                     dwo_abbrev_section,
4686                                                     info_ptr,
4687                                                     &signature,
4688                                                     &type_offset_in_tu);
4689           gdb_assert (sig_type->signature == signature);
4690           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4691           /* For DWOs coming from DWP files, we don't know the CU length
4692              nor the type's offset in the TU until now.  */
4693           dwo_unit->length = get_cu_length (&cu->header);
4694           dwo_unit->type_offset_in_tu = type_offset_in_tu;
4695
4696           /* Establish the type offset that can be used to lookup the type.
4697              For DWO files, we don't know it until now.  */
4698           sig_type->type_offset_in_section.sect_off =
4699             dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
4700         }
4701       else
4702         {
4703           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
4704                                                     dwo_abbrev_section,
4705                                                     info_ptr, 0);
4706           gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4707           /* For DWOs coming from DWP files, we don't know the CU length
4708              until now.  */
4709           dwo_unit->length = get_cu_length (&cu->header);
4710         }
4711
4712       /* Discard the original CU's abbrev table, and read the DWO's.  */
4713       if (abbrev_table == NULL)
4714         {
4715           dwarf2_free_abbrev_table (cu);
4716           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4717         }
4718       else
4719         {
4720           dwarf2_read_abbrevs (cu, dwo_abbrev_section);
4721           make_cleanup (dwarf2_free_abbrev_table, cu);
4722         }
4723
4724       /* Read in the die, but leave space to copy over the attributes
4725          from the stub.  This has the benefit of simplifying the rest of
4726          the code - all the real work is done here.  */
4727       num_extra_attrs = ((stmt_list != NULL)
4728                          + (low_pc != NULL)
4729                          + (high_pc != NULL)
4730                          + (ranges != NULL)
4731                          + (comp_dir != NULL));
4732       info_ptr = read_full_die_1 (&reader, &comp_unit_die, info_ptr,
4733                                   &has_children, num_extra_attrs);
4734
4735       /* Copy over the attributes from the stub to the DWO die.  */
4736       i = comp_unit_die->num_attrs;
4737       if (stmt_list != NULL)
4738         comp_unit_die->attrs[i++] = *stmt_list;
4739       if (low_pc != NULL)
4740         comp_unit_die->attrs[i++] = *low_pc;
4741       if (high_pc != NULL)
4742         comp_unit_die->attrs[i++] = *high_pc;
4743       if (ranges != NULL)
4744         comp_unit_die->attrs[i++] = *ranges;
4745       if (comp_dir != NULL)
4746         comp_unit_die->attrs[i++] = *comp_dir;
4747       comp_unit_die->num_attrs += num_extra_attrs;
4748
4749       /* Skip dummy compilation units.  */
4750       if (info_ptr >= begin_info_ptr + dwo_unit->length
4751           || peek_abbrev_code (abfd, info_ptr) == 0)
4752         {
4753           do_cleanups (cleanups);
4754           return;
4755         }
4756     }
4757
4758   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4759
4760   if (free_cu_cleanup != NULL)
4761     {
4762       if (keep)
4763         {
4764           /* We've successfully allocated this compilation unit.  Let our
4765              caller clean it up when finished with it.  */
4766           discard_cleanups (free_cu_cleanup);
4767
4768           /* We can only discard free_cu_cleanup and all subsequent cleanups.
4769              So we have to manually free the abbrev table.  */
4770           dwarf2_free_abbrev_table (cu);
4771
4772           /* Link this CU into read_in_chain.  */
4773           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
4774           dwarf2_per_objfile->read_in_chain = this_cu;
4775         }
4776       else
4777         do_cleanups (free_cu_cleanup);
4778     }
4779
4780   do_cleanups (cleanups);
4781 }
4782
4783 /* Read CU/TU THIS_CU in section SECTION,
4784    but do not follow DW_AT_GNU_dwo_name if present.
4785    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
4786    to have already done the lookup to find the DWO/DWP file).
4787
4788    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
4789    THIS_CU->is_debug_types, but nothing else.
4790
4791    We fill in THIS_CU->length.
4792
4793    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
4794    linker) then DIE_READER_FUNC will not get called.
4795
4796    THIS_CU->cu is always freed when done.
4797    This is done in order to not leave THIS_CU->cu in a state where we have
4798    to care whether it refers to the "main" CU or the DWO CU.  */
4799
4800 static void
4801 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
4802                                    struct dwarf2_section_info *abbrev_section,
4803                                    struct dwo_file *dwo_file,
4804                                    die_reader_func_ftype *die_reader_func,
4805                                    void *data)
4806 {
4807   struct objfile *objfile = dwarf2_per_objfile->objfile;
4808   struct dwarf2_section_info *section = this_cu->info_or_types_section;
4809   bfd *abfd = section->asection->owner;
4810   struct dwarf2_cu cu;
4811   gdb_byte *begin_info_ptr, *info_ptr;
4812   struct die_reader_specs reader;
4813   struct cleanup *cleanups;
4814   struct die_info *comp_unit_die;
4815   int has_children;
4816
4817   if (dwarf2_die_debug)
4818     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
4819                         this_cu->is_debug_types ? "type" : "comp",
4820                         this_cu->offset.sect_off);
4821
4822   gdb_assert (this_cu->cu == NULL);
4823
4824   /* This is cheap if the section is already read in.  */
4825   dwarf2_read_section (objfile, section);
4826
4827   init_one_comp_unit (&cu, this_cu);
4828
4829   cleanups = make_cleanup (free_stack_comp_unit, &cu);
4830
4831   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
4832   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
4833                                             abbrev_section, info_ptr,
4834                                             this_cu->is_debug_types);
4835
4836   this_cu->length = get_cu_length (&cu.header);
4837
4838   /* Skip dummy compilation units.  */
4839   if (info_ptr >= begin_info_ptr + this_cu->length
4840       || peek_abbrev_code (abfd, info_ptr) == 0)
4841     {
4842       do_cleanups (cleanups);
4843       return;
4844     }
4845
4846   dwarf2_read_abbrevs (&cu, abbrev_section);
4847   make_cleanup (dwarf2_free_abbrev_table, &cu);
4848
4849   init_cu_die_reader (&reader, &cu, section, dwo_file);
4850   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
4851
4852   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
4853
4854   do_cleanups (cleanups);
4855 }
4856
4857 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
4858    does not lookup the specified DWO file.
4859    This cannot be used to read DWO files.
4860
4861    THIS_CU->cu is always freed when done.
4862    This is done in order to not leave THIS_CU->cu in a state where we have
4863    to care whether it refers to the "main" CU or the DWO CU.
4864    We can revisit this if the data shows there's a performance issue.  */
4865
4866 static void
4867 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
4868                                 die_reader_func_ftype *die_reader_func,
4869                                 void *data)
4870 {
4871   init_cutu_and_read_dies_no_follow (this_cu,
4872                                      get_abbrev_section_for_cu (this_cu),
4873                                      NULL,
4874                                      die_reader_func, data);
4875 }
4876
4877 /* Create a psymtab named NAME and assign it to PER_CU.
4878
4879    The caller must fill in the following details:
4880    dirname, textlow, texthigh.  */
4881
4882 static struct partial_symtab *
4883 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
4884 {
4885   struct objfile *objfile = per_cu->objfile;
4886   struct partial_symtab *pst;
4887
4888   pst = start_psymtab_common (objfile, objfile->section_offsets,
4889                               name, 0,
4890                               objfile->global_psymbols.next,
4891                               objfile->static_psymbols.next);
4892
4893   pst->psymtabs_addrmap_supported = 1;
4894
4895   /* This is the glue that links PST into GDB's symbol API.  */
4896   pst->read_symtab_private = per_cu;
4897   pst->read_symtab = dwarf2_read_symtab;
4898   per_cu->v.psymtab = pst;
4899
4900   return pst;
4901 }
4902
4903 /* die_reader_func for process_psymtab_comp_unit.  */
4904
4905 static void
4906 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
4907                                   gdb_byte *info_ptr,
4908                                   struct die_info *comp_unit_die,
4909                                   int has_children,
4910                                   void *data)
4911 {
4912   struct dwarf2_cu *cu = reader->cu;
4913   struct objfile *objfile = cu->objfile;
4914   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
4915   struct attribute *attr;
4916   CORE_ADDR baseaddr;
4917   CORE_ADDR best_lowpc = 0, best_highpc = 0;
4918   struct partial_symtab *pst;
4919   int has_pc_info;
4920   const char *filename;
4921   int *want_partial_unit_ptr = data;
4922
4923   if (comp_unit_die->tag == DW_TAG_partial_unit
4924       && (want_partial_unit_ptr == NULL
4925           || !*want_partial_unit_ptr))
4926     return;
4927
4928   gdb_assert (! per_cu->is_debug_types);
4929
4930   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
4931
4932   cu->list_in_scope = &file_symbols;
4933
4934   /* Allocate a new partial symbol table structure.  */
4935   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
4936   if (attr == NULL || !DW_STRING (attr))
4937     filename = "";
4938   else
4939     filename = DW_STRING (attr);
4940
4941   pst = create_partial_symtab (per_cu, filename);
4942
4943   /* This must be done before calling dwarf2_build_include_psymtabs.  */
4944   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
4945   if (attr != NULL)
4946     pst->dirname = DW_STRING (attr);
4947
4948   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
4949
4950   dwarf2_find_base_address (comp_unit_die, cu);
4951
4952   /* Possibly set the default values of LOWPC and HIGHPC from
4953      `DW_AT_ranges'.  */
4954   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
4955                                       &best_highpc, cu, pst);
4956   if (has_pc_info == 1 && best_lowpc < best_highpc)
4957     /* Store the contiguous range if it is not empty; it can be empty for
4958        CUs with no code.  */
4959     addrmap_set_empty (objfile->psymtabs_addrmap,
4960                        best_lowpc + baseaddr,
4961                        best_highpc + baseaddr - 1, pst);
4962
4963   /* Check if comp unit has_children.
4964      If so, read the rest of the partial symbols from this comp unit.
4965      If not, there's no more debug_info for this comp unit.  */
4966   if (has_children)
4967     {
4968       struct partial_die_info *first_die;
4969       CORE_ADDR lowpc, highpc;
4970
4971       lowpc = ((CORE_ADDR) -1);
4972       highpc = ((CORE_ADDR) 0);
4973
4974       first_die = load_partial_dies (reader, info_ptr, 1);
4975
4976       scan_partial_symbols (first_die, &lowpc, &highpc,
4977                             ! has_pc_info, cu);
4978
4979       /* If we didn't find a lowpc, set it to highpc to avoid
4980          complaints from `maint check'.  */
4981       if (lowpc == ((CORE_ADDR) -1))
4982         lowpc = highpc;
4983
4984       /* If the compilation unit didn't have an explicit address range,
4985          then use the information extracted from its child dies.  */
4986       if (! has_pc_info)
4987         {
4988           best_lowpc = lowpc;
4989           best_highpc = highpc;
4990         }
4991     }
4992   pst->textlow = best_lowpc + baseaddr;
4993   pst->texthigh = best_highpc + baseaddr;
4994
4995   pst->n_global_syms = objfile->global_psymbols.next -
4996     (objfile->global_psymbols.list + pst->globals_offset);
4997   pst->n_static_syms = objfile->static_psymbols.next -
4998     (objfile->static_psymbols.list + pst->statics_offset);
4999   sort_pst_symbols (objfile, pst);
5000
5001   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
5002     {
5003       int i;
5004       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5005       struct dwarf2_per_cu_data *iter;
5006
5007       /* Fill in 'dependencies' here; we fill in 'users' in a
5008          post-pass.  */
5009       pst->number_of_dependencies = len;
5010       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5011                                          len * sizeof (struct symtab *));
5012       for (i = 0;
5013            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
5014                         i, iter);
5015            ++i)
5016         pst->dependencies[i] = iter->v.psymtab;
5017
5018       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
5019     }
5020
5021   /* Get the list of files included in the current compilation unit,
5022      and build a psymtab for each of them.  */
5023   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
5024
5025   if (dwarf2_read_debug)
5026     {
5027       struct gdbarch *gdbarch = get_objfile_arch (objfile);
5028
5029       fprintf_unfiltered (gdb_stdlog,
5030                           "Psymtab for %s unit @0x%x: %s - %s"
5031                           ", %d global, %d static syms\n",
5032                           per_cu->is_debug_types ? "type" : "comp",
5033                           per_cu->offset.sect_off,
5034                           paddress (gdbarch, pst->textlow),
5035                           paddress (gdbarch, pst->texthigh),
5036                           pst->n_global_syms, pst->n_static_syms);
5037     }
5038 }
5039
5040 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5041    Process compilation unit THIS_CU for a psymtab.  */
5042
5043 static void
5044 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
5045                            int want_partial_unit)
5046 {
5047   /* If this compilation unit was already read in, free the
5048      cached copy in order to read it in again.  This is
5049      necessary because we skipped some symbols when we first
5050      read in the compilation unit (see load_partial_dies).
5051      This problem could be avoided, but the benefit is unclear.  */
5052   if (this_cu->cu != NULL)
5053     free_one_cached_comp_unit (this_cu);
5054
5055   gdb_assert (! this_cu->is_debug_types);
5056   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
5057                            process_psymtab_comp_unit_reader,
5058                            &want_partial_unit);
5059
5060   /* Age out any secondary CUs.  */
5061   age_cached_comp_units ();
5062 }
5063
5064 static hashval_t
5065 hash_type_unit_group (const void *item)
5066 {
5067   const struct type_unit_group *tu_group = item;
5068
5069   return hash_stmt_list_entry (&tu_group->hash);
5070 }
5071
5072 static int
5073 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5074 {
5075   const struct type_unit_group *lhs = item_lhs;
5076   const struct type_unit_group *rhs = item_rhs;
5077
5078   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5079 }
5080
5081 /* Allocate a hash table for type unit groups.  */
5082
5083 static htab_t
5084 allocate_type_unit_groups_table (void)
5085 {
5086   return htab_create_alloc_ex (3,
5087                                hash_type_unit_group,
5088                                eq_type_unit_group,
5089                                NULL,
5090                                &dwarf2_per_objfile->objfile->objfile_obstack,
5091                                hashtab_obstack_allocate,
5092                                dummy_obstack_deallocate);
5093 }
5094
5095 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5096    partial symtabs.  We combine several TUs per psymtab to not let the size
5097    of any one psymtab grow too big.  */
5098 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5099 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5100
5101 /* Helper routine for get_type_unit_group.
5102    Create the type_unit_group object used to hold one or more TUs.  */
5103
5104 static struct type_unit_group *
5105 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5106 {
5107   struct objfile *objfile = dwarf2_per_objfile->objfile;
5108   struct dwarf2_per_cu_data *per_cu;
5109   struct type_unit_group *tu_group;
5110
5111   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5112                              struct type_unit_group);
5113   per_cu = &tu_group->per_cu;
5114   per_cu->objfile = objfile;
5115   per_cu->is_debug_types = 1;
5116   per_cu->type_unit_group = tu_group;
5117
5118   if (dwarf2_per_objfile->using_index)
5119     {
5120       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5121                                         struct dwarf2_per_cu_quick_data);
5122       tu_group->t.first_tu = cu->per_cu;
5123     }
5124   else
5125     {
5126       unsigned int line_offset = line_offset_struct.sect_off;
5127       struct partial_symtab *pst;
5128       char *name;
5129
5130       /* Give the symtab a useful name for debug purposes.  */
5131       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5132         name = xstrprintf ("<type_units_%d>",
5133                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5134       else
5135         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5136
5137       pst = create_partial_symtab (per_cu, name);
5138       pst->anonymous = 1;
5139
5140       xfree (name);
5141     }
5142
5143   tu_group->hash.dwo_unit = cu->dwo_unit;
5144   tu_group->hash.line_offset = line_offset_struct;
5145
5146   return tu_group;
5147 }
5148
5149 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5150    STMT_LIST is a DW_AT_stmt_list attribute.  */
5151
5152 static struct type_unit_group *
5153 get_type_unit_group (struct dwarf2_cu *cu, struct attribute *stmt_list)
5154 {
5155   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5156   struct type_unit_group *tu_group;
5157   void **slot;
5158   unsigned int line_offset;
5159   struct type_unit_group type_unit_group_for_lookup;
5160
5161   if (dwarf2_per_objfile->type_unit_groups == NULL)
5162     {
5163       dwarf2_per_objfile->type_unit_groups =
5164         allocate_type_unit_groups_table ();
5165     }
5166
5167   /* Do we need to create a new group, or can we use an existing one?  */
5168
5169   if (stmt_list)
5170     {
5171       line_offset = DW_UNSND (stmt_list);
5172       ++tu_stats->nr_symtab_sharers;
5173     }
5174   else
5175     {
5176       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5177          We can do various things here like create one group per TU or
5178          spread them over multiple groups to split up the expansion work.
5179          To avoid worst case scenarios (too many groups or too large groups)
5180          we, umm, group them in bunches.  */
5181       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5182                      | (tu_stats->nr_stmt_less_type_units
5183                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5184       ++tu_stats->nr_stmt_less_type_units;
5185     }
5186
5187   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5188   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5189   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5190                          &type_unit_group_for_lookup, INSERT);
5191   if (*slot != NULL)
5192     {
5193       tu_group = *slot;
5194       gdb_assert (tu_group != NULL);
5195     }
5196   else
5197     {
5198       sect_offset line_offset_struct;
5199
5200       line_offset_struct.sect_off = line_offset;
5201       tu_group = create_type_unit_group (cu, line_offset_struct);
5202       *slot = tu_group;
5203       ++tu_stats->nr_symtabs;
5204     }
5205
5206   return tu_group;
5207 }
5208
5209 /* Struct used to sort TUs by their abbreviation table offset.  */
5210
5211 struct tu_abbrev_offset
5212 {
5213   struct signatured_type *sig_type;
5214   sect_offset abbrev_offset;
5215 };
5216
5217 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5218
5219 static int
5220 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5221 {
5222   const struct tu_abbrev_offset * const *a = ap;
5223   const struct tu_abbrev_offset * const *b = bp;
5224   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5225   unsigned int boff = (*b)->abbrev_offset.sect_off;
5226
5227   return (aoff > boff) - (aoff < boff);
5228 }
5229
5230 /* A helper function to add a type_unit_group to a table.  */
5231
5232 static int
5233 add_type_unit_group_to_table (void **slot, void *datum)
5234 {
5235   struct type_unit_group *tu_group = *slot;
5236   struct type_unit_group ***datap = datum;
5237
5238   **datap = tu_group;
5239   ++*datap;
5240
5241   return 1;
5242 }
5243
5244 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5245    each one passing FUNC,DATA.
5246
5247    The efficiency is because we sort TUs by the abbrev table they use and
5248    only read each abbrev table once.  In one program there are 200K TUs
5249    sharing 8K abbrev tables.
5250
5251    The main purpose of this function is to support building the
5252    dwarf2_per_objfile->type_unit_groups table.
5253    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5254    can collapse the search space by grouping them by stmt_list.
5255    The savings can be significant, in the same program from above the 200K TUs
5256    share 8K stmt_list tables.
5257
5258    FUNC is expected to call get_type_unit_group, which will create the
5259    struct type_unit_group if necessary and add it to
5260    dwarf2_per_objfile->type_unit_groups.  */
5261
5262 static void
5263 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5264 {
5265   struct objfile *objfile = dwarf2_per_objfile->objfile;
5266   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5267   struct cleanup *cleanups;
5268   struct abbrev_table *abbrev_table;
5269   sect_offset abbrev_offset;
5270   struct tu_abbrev_offset *sorted_by_abbrev;
5271   struct type_unit_group **iter;
5272   int i;
5273
5274   /* It's up to the caller to not call us multiple times.  */
5275   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5276
5277   if (dwarf2_per_objfile->n_type_units == 0)
5278     return;
5279
5280   /* TUs typically share abbrev tables, and there can be way more TUs than
5281      abbrev tables.  Sort by abbrev table to reduce the number of times we
5282      read each abbrev table in.
5283      Alternatives are to punt or to maintain a cache of abbrev tables.
5284      This is simpler and efficient enough for now.
5285
5286      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5287      symtab to use).  Typically TUs with the same abbrev offset have the same
5288      stmt_list value too so in practice this should work well.
5289
5290      The basic algorithm here is:
5291
5292       sort TUs by abbrev table
5293       for each TU with same abbrev table:
5294         read abbrev table if first user
5295         read TU top level DIE
5296           [IWBN if DWO skeletons had DW_AT_stmt_list]
5297         call FUNC  */
5298
5299   if (dwarf2_read_debug)
5300     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5301
5302   /* Sort in a separate table to maintain the order of all_type_units
5303      for .gdb_index: TU indices directly index all_type_units.  */
5304   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5305                               dwarf2_per_objfile->n_type_units);
5306   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5307     {
5308       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5309
5310       sorted_by_abbrev[i].sig_type = sig_type;
5311       sorted_by_abbrev[i].abbrev_offset =
5312         read_abbrev_offset (sig_type->per_cu.info_or_types_section,
5313                             sig_type->per_cu.offset);
5314     }
5315   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5316   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5317          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5318
5319   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5320      called any number of times, so we don't reset tu_stats here.  */
5321
5322   abbrev_offset.sect_off = ~(unsigned) 0;
5323   abbrev_table = NULL;
5324   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5325
5326   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5327     {
5328       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5329
5330       /* Switch to the next abbrev table if necessary.  */
5331       if (abbrev_table == NULL
5332           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5333         {
5334           if (abbrev_table != NULL)
5335             {
5336               abbrev_table_free (abbrev_table);
5337               /* Reset to NULL in case abbrev_table_read_table throws
5338                  an error: abbrev_table_free_cleanup will get called.  */
5339               abbrev_table = NULL;
5340             }
5341           abbrev_offset = tu->abbrev_offset;
5342           abbrev_table =
5343             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5344                                      abbrev_offset);
5345           ++tu_stats->nr_uniq_abbrev_tables;
5346         }
5347
5348       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5349                                func, data);
5350     }
5351
5352   /* Create a vector of pointers to primary type units to make it easy to
5353      iterate over them and CUs.  See dw2_get_primary_cu.  */
5354   dwarf2_per_objfile->n_type_unit_groups =
5355     htab_elements (dwarf2_per_objfile->type_unit_groups);
5356   dwarf2_per_objfile->all_type_unit_groups =
5357     obstack_alloc (&objfile->objfile_obstack,
5358                    dwarf2_per_objfile->n_type_unit_groups
5359                    * sizeof (struct type_unit_group *));
5360   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5361   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5362                           add_type_unit_group_to_table, &iter);
5363   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5364               == dwarf2_per_objfile->n_type_unit_groups);
5365
5366   do_cleanups (cleanups);
5367
5368   if (dwarf2_read_debug)
5369     {
5370       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5371       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5372                           dwarf2_per_objfile->n_type_units);
5373       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5374                           tu_stats->nr_uniq_abbrev_tables);
5375       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5376                           tu_stats->nr_symtabs);
5377       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5378                           tu_stats->nr_symtab_sharers);
5379       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5380                           tu_stats->nr_stmt_less_type_units);
5381     }
5382 }
5383
5384 /* Reader function for build_type_psymtabs.  */
5385
5386 static void
5387 build_type_psymtabs_reader (const struct die_reader_specs *reader,
5388                             gdb_byte *info_ptr,
5389                             struct die_info *type_unit_die,
5390                             int has_children,
5391                             void *data)
5392 {
5393   struct objfile *objfile = dwarf2_per_objfile->objfile;
5394   struct dwarf2_cu *cu = reader->cu;
5395   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5396   struct type_unit_group *tu_group;
5397   struct attribute *attr;
5398   struct partial_die_info *first_die;
5399   CORE_ADDR lowpc, highpc;
5400   struct partial_symtab *pst;
5401
5402   gdb_assert (data == NULL);
5403
5404   if (! has_children)
5405     return;
5406
5407   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
5408   tu_group = get_type_unit_group (cu, attr);
5409
5410   VEC_safe_push (dwarf2_per_cu_ptr, tu_group->t.tus, per_cu);
5411
5412   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
5413   cu->list_in_scope = &file_symbols;
5414   pst = create_partial_symtab (per_cu, "");
5415   pst->anonymous = 1;
5416
5417   first_die = load_partial_dies (reader, info_ptr, 1);
5418
5419   lowpc = (CORE_ADDR) -1;
5420   highpc = (CORE_ADDR) 0;
5421   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
5422
5423   pst->n_global_syms = objfile->global_psymbols.next -
5424     (objfile->global_psymbols.list + pst->globals_offset);
5425   pst->n_static_syms = objfile->static_psymbols.next -
5426     (objfile->static_psymbols.list + pst->statics_offset);
5427   sort_pst_symbols (objfile, pst);
5428 }
5429
5430 /* Traversal function for build_type_psymtabs.  */
5431
5432 static int
5433 build_type_psymtab_dependencies (void **slot, void *info)
5434 {
5435   struct objfile *objfile = dwarf2_per_objfile->objfile;
5436   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
5437   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
5438   struct partial_symtab *pst = per_cu->v.psymtab;
5439   int len = VEC_length (dwarf2_per_cu_ptr, tu_group->t.tus);
5440   struct dwarf2_per_cu_data *iter;
5441   int i;
5442
5443   gdb_assert (len > 0);
5444
5445   pst->number_of_dependencies = len;
5446   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
5447                                      len * sizeof (struct psymtab *));
5448   for (i = 0;
5449        VEC_iterate (dwarf2_per_cu_ptr, tu_group->t.tus, i, iter);
5450        ++i)
5451     {
5452       pst->dependencies[i] = iter->v.psymtab;
5453       iter->type_unit_group = tu_group;
5454     }
5455
5456   VEC_free (dwarf2_per_cu_ptr, tu_group->t.tus);
5457
5458   return 1;
5459 }
5460
5461 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
5462    Build partial symbol tables for the .debug_types comp-units.  */
5463
5464 static void
5465 build_type_psymtabs (struct objfile *objfile)
5466 {
5467   if (! create_all_type_units (objfile))
5468     return;
5469
5470   build_type_unit_groups (build_type_psymtabs_reader, NULL);
5471
5472   /* Now that all TUs have been processed we can fill in the dependencies.  */
5473   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5474                           build_type_psymtab_dependencies, NULL);
5475 }
5476
5477 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
5478
5479 static void
5480 psymtabs_addrmap_cleanup (void *o)
5481 {
5482   struct objfile *objfile = o;
5483
5484   objfile->psymtabs_addrmap = NULL;
5485 }
5486
5487 /* Compute the 'user' field for each psymtab in OBJFILE.  */
5488
5489 static void
5490 set_partial_user (struct objfile *objfile)
5491 {
5492   int i;
5493
5494   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5495     {
5496       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5497       struct partial_symtab *pst = per_cu->v.psymtab;
5498       int j;
5499
5500       if (pst == NULL)
5501         continue;
5502
5503       for (j = 0; j < pst->number_of_dependencies; ++j)
5504         {
5505           /* Set the 'user' field only if it is not already set.  */
5506           if (pst->dependencies[j]->user == NULL)
5507             pst->dependencies[j]->user = pst;
5508         }
5509     }
5510 }
5511
5512 /* Build the partial symbol table by doing a quick pass through the
5513    .debug_info and .debug_abbrev sections.  */
5514
5515 static void
5516 dwarf2_build_psymtabs_hard (struct objfile *objfile)
5517 {
5518   struct cleanup *back_to, *addrmap_cleanup;
5519   struct obstack temp_obstack;
5520   int i;
5521
5522   if (dwarf2_read_debug)
5523     {
5524       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
5525                           objfile->name);
5526     }
5527
5528   dwarf2_per_objfile->reading_partial_symbols = 1;
5529
5530   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
5531
5532   /* Any cached compilation units will be linked by the per-objfile
5533      read_in_chain.  Make sure to free them when we're done.  */
5534   back_to = make_cleanup (free_cached_comp_units, NULL);
5535
5536   build_type_psymtabs (objfile);
5537
5538   create_all_comp_units (objfile);
5539
5540   /* Create a temporary address map on a temporary obstack.  We later
5541      copy this to the final obstack.  */
5542   obstack_init (&temp_obstack);
5543   make_cleanup_obstack_free (&temp_obstack);
5544   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
5545   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
5546
5547   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5548     {
5549       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5550
5551       process_psymtab_comp_unit (per_cu, 0);
5552     }
5553
5554   set_partial_user (objfile);
5555
5556   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
5557                                                     &objfile->objfile_obstack);
5558   discard_cleanups (addrmap_cleanup);
5559
5560   do_cleanups (back_to);
5561
5562   if (dwarf2_read_debug)
5563     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
5564                         objfile->name);
5565 }
5566
5567 /* die_reader_func for load_partial_comp_unit.  */
5568
5569 static void
5570 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
5571                                gdb_byte *info_ptr,
5572                                struct die_info *comp_unit_die,
5573                                int has_children,
5574                                void *data)
5575 {
5576   struct dwarf2_cu *cu = reader->cu;
5577
5578   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
5579
5580   /* Check if comp unit has_children.
5581      If so, read the rest of the partial symbols from this comp unit.
5582      If not, there's no more debug_info for this comp unit.  */
5583   if (has_children)
5584     load_partial_dies (reader, info_ptr, 0);
5585 }
5586
5587 /* Load the partial DIEs for a secondary CU into memory.
5588    This is also used when rereading a primary CU with load_all_dies.  */
5589
5590 static void
5591 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
5592 {
5593   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
5594                            load_partial_comp_unit_reader, NULL);
5595 }
5596
5597 static void
5598 read_comp_units_from_section (struct objfile *objfile,
5599                               struct dwarf2_section_info *section,
5600                               unsigned int is_dwz,
5601                               int *n_allocated,
5602                               int *n_comp_units,
5603                               struct dwarf2_per_cu_data ***all_comp_units)
5604 {
5605   gdb_byte *info_ptr;
5606   bfd *abfd = section->asection->owner;
5607
5608   dwarf2_read_section (objfile, section);
5609
5610   info_ptr = section->buffer;
5611
5612   while (info_ptr < section->buffer + section->size)
5613     {
5614       unsigned int length, initial_length_size;
5615       struct dwarf2_per_cu_data *this_cu;
5616       sect_offset offset;
5617
5618       offset.sect_off = info_ptr - section->buffer;
5619
5620       /* Read just enough information to find out where the next
5621          compilation unit is.  */
5622       length = read_initial_length (abfd, info_ptr, &initial_length_size);
5623
5624       /* Save the compilation unit for later lookup.  */
5625       this_cu = obstack_alloc (&objfile->objfile_obstack,
5626                                sizeof (struct dwarf2_per_cu_data));
5627       memset (this_cu, 0, sizeof (*this_cu));
5628       this_cu->offset = offset;
5629       this_cu->length = length + initial_length_size;
5630       this_cu->is_dwz = is_dwz;
5631       this_cu->objfile = objfile;
5632       this_cu->info_or_types_section = section;
5633
5634       if (*n_comp_units == *n_allocated)
5635         {
5636           *n_allocated *= 2;
5637           *all_comp_units = xrealloc (*all_comp_units,
5638                                       *n_allocated
5639                                       * sizeof (struct dwarf2_per_cu_data *));
5640         }
5641       (*all_comp_units)[*n_comp_units] = this_cu;
5642       ++*n_comp_units;
5643
5644       info_ptr = info_ptr + this_cu->length;
5645     }
5646 }
5647
5648 /* Create a list of all compilation units in OBJFILE.
5649    This is only done for -readnow and building partial symtabs.  */
5650
5651 static void
5652 create_all_comp_units (struct objfile *objfile)
5653 {
5654   int n_allocated;
5655   int n_comp_units;
5656   struct dwarf2_per_cu_data **all_comp_units;
5657
5658   n_comp_units = 0;
5659   n_allocated = 10;
5660   all_comp_units = xmalloc (n_allocated
5661                             * sizeof (struct dwarf2_per_cu_data *));
5662
5663   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
5664                                 &n_allocated, &n_comp_units, &all_comp_units);
5665
5666   if (bfd_get_section_by_name (objfile->obfd, ".gnu_debugaltlink") != NULL)
5667     {
5668       struct dwz_file *dwz = dwarf2_get_dwz_file ();
5669
5670       read_comp_units_from_section (objfile, &dwz->info, 1,
5671                                     &n_allocated, &n_comp_units,
5672                                     &all_comp_units);
5673     }
5674
5675   dwarf2_per_objfile->all_comp_units
5676     = obstack_alloc (&objfile->objfile_obstack,
5677                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5678   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
5679           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
5680   xfree (all_comp_units);
5681   dwarf2_per_objfile->n_comp_units = n_comp_units;
5682 }
5683
5684 /* Process all loaded DIEs for compilation unit CU, starting at
5685    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
5686    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
5687    DW_AT_ranges).  If NEED_PC is set, then this function will set
5688    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
5689    and record the covered ranges in the addrmap.  */
5690
5691 static void
5692 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
5693                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
5694 {
5695   struct partial_die_info *pdi;
5696
5697   /* Now, march along the PDI's, descending into ones which have
5698      interesting children but skipping the children of the other ones,
5699      until we reach the end of the compilation unit.  */
5700
5701   pdi = first_die;
5702
5703   while (pdi != NULL)
5704     {
5705       fixup_partial_die (pdi, cu);
5706
5707       /* Anonymous namespaces or modules have no name but have interesting
5708          children, so we need to look at them.  Ditto for anonymous
5709          enums.  */
5710
5711       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
5712           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
5713           || pdi->tag == DW_TAG_imported_unit)
5714         {
5715           switch (pdi->tag)
5716             {
5717             case DW_TAG_subprogram:
5718               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
5719               break;
5720             case DW_TAG_constant:
5721             case DW_TAG_variable:
5722             case DW_TAG_typedef:
5723             case DW_TAG_union_type:
5724               if (!pdi->is_declaration)
5725                 {
5726                   add_partial_symbol (pdi, cu);
5727                 }
5728               break;
5729             case DW_TAG_class_type:
5730             case DW_TAG_interface_type:
5731             case DW_TAG_structure_type:
5732               if (!pdi->is_declaration)
5733                 {
5734                   add_partial_symbol (pdi, cu);
5735                 }
5736               break;
5737             case DW_TAG_enumeration_type:
5738               if (!pdi->is_declaration)
5739                 add_partial_enumeration (pdi, cu);
5740               break;
5741             case DW_TAG_base_type:
5742             case DW_TAG_subrange_type:
5743               /* File scope base type definitions are added to the partial
5744                  symbol table.  */
5745               add_partial_symbol (pdi, cu);
5746               break;
5747             case DW_TAG_namespace:
5748               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
5749               break;
5750             case DW_TAG_module:
5751               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
5752               break;
5753             case DW_TAG_imported_unit:
5754               {
5755                 struct dwarf2_per_cu_data *per_cu;
5756
5757                 /* For now we don't handle imported units in type units.  */
5758                 if (cu->per_cu->is_debug_types)
5759                   {
5760                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
5761                              " supported in type units [in module %s]"),
5762                            cu->objfile->name);
5763                   }
5764
5765                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
5766                                                            pdi->is_dwz,
5767                                                            cu->objfile);
5768
5769                 /* Go read the partial unit, if needed.  */
5770                 if (per_cu->v.psymtab == NULL)
5771                   process_psymtab_comp_unit (per_cu, 1);
5772
5773                 VEC_safe_push (dwarf2_per_cu_ptr,
5774                                cu->per_cu->imported_symtabs, per_cu);
5775               }
5776               break;
5777             default:
5778               break;
5779             }
5780         }
5781
5782       /* If the die has a sibling, skip to the sibling.  */
5783
5784       pdi = pdi->die_sibling;
5785     }
5786 }
5787
5788 /* Functions used to compute the fully scoped name of a partial DIE.
5789
5790    Normally, this is simple.  For C++, the parent DIE's fully scoped
5791    name is concatenated with "::" and the partial DIE's name.  For
5792    Java, the same thing occurs except that "." is used instead of "::".
5793    Enumerators are an exception; they use the scope of their parent
5794    enumeration type, i.e. the name of the enumeration type is not
5795    prepended to the enumerator.
5796
5797    There are two complexities.  One is DW_AT_specification; in this
5798    case "parent" means the parent of the target of the specification,
5799    instead of the direct parent of the DIE.  The other is compilers
5800    which do not emit DW_TAG_namespace; in this case we try to guess
5801    the fully qualified name of structure types from their members'
5802    linkage names.  This must be done using the DIE's children rather
5803    than the children of any DW_AT_specification target.  We only need
5804    to do this for structures at the top level, i.e. if the target of
5805    any DW_AT_specification (if any; otherwise the DIE itself) does not
5806    have a parent.  */
5807
5808 /* Compute the scope prefix associated with PDI's parent, in
5809    compilation unit CU.  The result will be allocated on CU's
5810    comp_unit_obstack, or a copy of the already allocated PDI->NAME
5811    field.  NULL is returned if no prefix is necessary.  */
5812 static const char *
5813 partial_die_parent_scope (struct partial_die_info *pdi,
5814                           struct dwarf2_cu *cu)
5815 {
5816   const char *grandparent_scope;
5817   struct partial_die_info *parent, *real_pdi;
5818
5819   /* We need to look at our parent DIE; if we have a DW_AT_specification,
5820      then this means the parent of the specification DIE.  */
5821
5822   real_pdi = pdi;
5823   while (real_pdi->has_specification)
5824     real_pdi = find_partial_die (real_pdi->spec_offset,
5825                                  real_pdi->spec_is_dwz, cu);
5826
5827   parent = real_pdi->die_parent;
5828   if (parent == NULL)
5829     return NULL;
5830
5831   if (parent->scope_set)
5832     return parent->scope;
5833
5834   fixup_partial_die (parent, cu);
5835
5836   grandparent_scope = partial_die_parent_scope (parent, cu);
5837
5838   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
5839      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
5840      Work around this problem here.  */
5841   if (cu->language == language_cplus
5842       && parent->tag == DW_TAG_namespace
5843       && strcmp (parent->name, "::") == 0
5844       && grandparent_scope == NULL)
5845     {
5846       parent->scope = NULL;
5847       parent->scope_set = 1;
5848       return NULL;
5849     }
5850
5851   if (pdi->tag == DW_TAG_enumerator)
5852     /* Enumerators should not get the name of the enumeration as a prefix.  */
5853     parent->scope = grandparent_scope;
5854   else if (parent->tag == DW_TAG_namespace
5855       || parent->tag == DW_TAG_module
5856       || parent->tag == DW_TAG_structure_type
5857       || parent->tag == DW_TAG_class_type
5858       || parent->tag == DW_TAG_interface_type
5859       || parent->tag == DW_TAG_union_type
5860       || parent->tag == DW_TAG_enumeration_type)
5861     {
5862       if (grandparent_scope == NULL)
5863         parent->scope = parent->name;
5864       else
5865         parent->scope = typename_concat (&cu->comp_unit_obstack,
5866                                          grandparent_scope,
5867                                          parent->name, 0, cu);
5868     }
5869   else
5870     {
5871       /* FIXME drow/2004-04-01: What should we be doing with
5872          function-local names?  For partial symbols, we should probably be
5873          ignoring them.  */
5874       complaint (&symfile_complaints,
5875                  _("unhandled containing DIE tag %d for DIE at %d"),
5876                  parent->tag, pdi->offset.sect_off);
5877       parent->scope = grandparent_scope;
5878     }
5879
5880   parent->scope_set = 1;
5881   return parent->scope;
5882 }
5883
5884 /* Return the fully scoped name associated with PDI, from compilation unit
5885    CU.  The result will be allocated with malloc.  */
5886
5887 static char *
5888 partial_die_full_name (struct partial_die_info *pdi,
5889                        struct dwarf2_cu *cu)
5890 {
5891   const char *parent_scope;
5892
5893   /* If this is a template instantiation, we can not work out the
5894      template arguments from partial DIEs.  So, unfortunately, we have
5895      to go through the full DIEs.  At least any work we do building
5896      types here will be reused if full symbols are loaded later.  */
5897   if (pdi->has_template_arguments)
5898     {
5899       fixup_partial_die (pdi, cu);
5900
5901       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
5902         {
5903           struct die_info *die;
5904           struct attribute attr;
5905           struct dwarf2_cu *ref_cu = cu;
5906
5907           /* DW_FORM_ref_addr is using section offset.  */
5908           attr.name = 0;
5909           attr.form = DW_FORM_ref_addr;
5910           attr.u.unsnd = pdi->offset.sect_off;
5911           die = follow_die_ref (NULL, &attr, &ref_cu);
5912
5913           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
5914         }
5915     }
5916
5917   parent_scope = partial_die_parent_scope (pdi, cu);
5918   if (parent_scope == NULL)
5919     return NULL;
5920   else
5921     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
5922 }
5923
5924 static void
5925 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
5926 {
5927   struct objfile *objfile = cu->objfile;
5928   CORE_ADDR addr = 0;
5929   const char *actual_name = NULL;
5930   CORE_ADDR baseaddr;
5931   char *built_actual_name;
5932
5933   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5934
5935   built_actual_name = partial_die_full_name (pdi, cu);
5936   if (built_actual_name != NULL)
5937     actual_name = built_actual_name;
5938
5939   if (actual_name == NULL)
5940     actual_name = pdi->name;
5941
5942   switch (pdi->tag)
5943     {
5944     case DW_TAG_subprogram:
5945       if (pdi->is_external || cu->language == language_ada)
5946         {
5947           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
5948              of the global scope.  But in Ada, we want to be able to access
5949              nested procedures globally.  So all Ada subprograms are stored
5950              in the global scope.  */
5951           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5952              mst_text, objfile); */
5953           add_psymbol_to_list (actual_name, strlen (actual_name),
5954                                built_actual_name != NULL,
5955                                VAR_DOMAIN, LOC_BLOCK,
5956                                &objfile->global_psymbols,
5957                                0, pdi->lowpc + baseaddr,
5958                                cu->language, objfile);
5959         }
5960       else
5961         {
5962           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
5963              mst_file_text, objfile); */
5964           add_psymbol_to_list (actual_name, strlen (actual_name),
5965                                built_actual_name != NULL,
5966                                VAR_DOMAIN, LOC_BLOCK,
5967                                &objfile->static_psymbols,
5968                                0, pdi->lowpc + baseaddr,
5969                                cu->language, objfile);
5970         }
5971       break;
5972     case DW_TAG_constant:
5973       {
5974         struct psymbol_allocation_list *list;
5975
5976         if (pdi->is_external)
5977           list = &objfile->global_psymbols;
5978         else
5979           list = &objfile->static_psymbols;
5980         add_psymbol_to_list (actual_name, strlen (actual_name),
5981                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
5982                              list, 0, 0, cu->language, objfile);
5983       }
5984       break;
5985     case DW_TAG_variable:
5986       if (pdi->d.locdesc)
5987         addr = decode_locdesc (pdi->d.locdesc, cu);
5988
5989       if (pdi->d.locdesc
5990           && addr == 0
5991           && !dwarf2_per_objfile->has_section_at_zero)
5992         {
5993           /* A global or static variable may also have been stripped
5994              out by the linker if unused, in which case its address
5995              will be nullified; do not add such variables into partial
5996              symbol table then.  */
5997         }
5998       else if (pdi->is_external)
5999         {
6000           /* Global Variable.
6001              Don't enter into the minimal symbol tables as there is
6002              a minimal symbol table entry from the ELF symbols already.
6003              Enter into partial symbol table if it has a location
6004              descriptor or a type.
6005              If the location descriptor is missing, new_symbol will create
6006              a LOC_UNRESOLVED symbol, the address of the variable will then
6007              be determined from the minimal symbol table whenever the variable
6008              is referenced.
6009              The address for the partial symbol table entry is not
6010              used by GDB, but it comes in handy for debugging partial symbol
6011              table building.  */
6012
6013           if (pdi->d.locdesc || pdi->has_type)
6014             add_psymbol_to_list (actual_name, strlen (actual_name),
6015                                  built_actual_name != NULL,
6016                                  VAR_DOMAIN, LOC_STATIC,
6017                                  &objfile->global_psymbols,
6018                                  0, addr + baseaddr,
6019                                  cu->language, objfile);
6020         }
6021       else
6022         {
6023           /* Static Variable.  Skip symbols without location descriptors.  */
6024           if (pdi->d.locdesc == NULL)
6025             {
6026               xfree (built_actual_name);
6027               return;
6028             }
6029           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6030              mst_file_data, objfile); */
6031           add_psymbol_to_list (actual_name, strlen (actual_name),
6032                                built_actual_name != NULL,
6033                                VAR_DOMAIN, LOC_STATIC,
6034                                &objfile->static_psymbols,
6035                                0, addr + baseaddr,
6036                                cu->language, objfile);
6037         }
6038       break;
6039     case DW_TAG_typedef:
6040     case DW_TAG_base_type:
6041     case DW_TAG_subrange_type:
6042       add_psymbol_to_list (actual_name, strlen (actual_name),
6043                            built_actual_name != NULL,
6044                            VAR_DOMAIN, LOC_TYPEDEF,
6045                            &objfile->static_psymbols,
6046                            0, (CORE_ADDR) 0, cu->language, objfile);
6047       break;
6048     case DW_TAG_namespace:
6049       add_psymbol_to_list (actual_name, strlen (actual_name),
6050                            built_actual_name != NULL,
6051                            VAR_DOMAIN, LOC_TYPEDEF,
6052                            &objfile->global_psymbols,
6053                            0, (CORE_ADDR) 0, cu->language, objfile);
6054       break;
6055     case DW_TAG_class_type:
6056     case DW_TAG_interface_type:
6057     case DW_TAG_structure_type:
6058     case DW_TAG_union_type:
6059     case DW_TAG_enumeration_type:
6060       /* Skip external references.  The DWARF standard says in the section
6061          about "Structure, Union, and Class Type Entries": "An incomplete
6062          structure, union or class type is represented by a structure,
6063          union or class entry that does not have a byte size attribute
6064          and that has a DW_AT_declaration attribute."  */
6065       if (!pdi->has_byte_size && pdi->is_declaration)
6066         {
6067           xfree (built_actual_name);
6068           return;
6069         }
6070
6071       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6072          static vs. global.  */
6073       add_psymbol_to_list (actual_name, strlen (actual_name),
6074                            built_actual_name != NULL,
6075                            STRUCT_DOMAIN, LOC_TYPEDEF,
6076                            (cu->language == language_cplus
6077                             || cu->language == language_java)
6078                            ? &objfile->global_psymbols
6079                            : &objfile->static_psymbols,
6080                            0, (CORE_ADDR) 0, cu->language, objfile);
6081
6082       break;
6083     case DW_TAG_enumerator:
6084       add_psymbol_to_list (actual_name, strlen (actual_name),
6085                            built_actual_name != NULL,
6086                            VAR_DOMAIN, LOC_CONST,
6087                            (cu->language == language_cplus
6088                             || cu->language == language_java)
6089                            ? &objfile->global_psymbols
6090                            : &objfile->static_psymbols,
6091                            0, (CORE_ADDR) 0, cu->language, objfile);
6092       break;
6093     default:
6094       break;
6095     }
6096
6097   xfree (built_actual_name);
6098 }
6099
6100 /* Read a partial die corresponding to a namespace; also, add a symbol
6101    corresponding to that namespace to the symbol table.  NAMESPACE is
6102    the name of the enclosing namespace.  */
6103
6104 static void
6105 add_partial_namespace (struct partial_die_info *pdi,
6106                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6107                        int need_pc, struct dwarf2_cu *cu)
6108 {
6109   /* Add a symbol for the namespace.  */
6110
6111   add_partial_symbol (pdi, cu);
6112
6113   /* Now scan partial symbols in that namespace.  */
6114
6115   if (pdi->has_children)
6116     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6117 }
6118
6119 /* Read a partial die corresponding to a Fortran module.  */
6120
6121 static void
6122 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6123                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6124 {
6125   /* Now scan partial symbols in that module.  */
6126
6127   if (pdi->has_children)
6128     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6129 }
6130
6131 /* Read a partial die corresponding to a subprogram and create a partial
6132    symbol for that subprogram.  When the CU language allows it, this
6133    routine also defines a partial symbol for each nested subprogram
6134    that this subprogram contains.
6135
6136    DIE my also be a lexical block, in which case we simply search
6137    recursively for suprograms defined inside that lexical block.
6138    Again, this is only performed when the CU language allows this
6139    type of definitions.  */
6140
6141 static void
6142 add_partial_subprogram (struct partial_die_info *pdi,
6143                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6144                         int need_pc, struct dwarf2_cu *cu)
6145 {
6146   if (pdi->tag == DW_TAG_subprogram)
6147     {
6148       if (pdi->has_pc_info)
6149         {
6150           if (pdi->lowpc < *lowpc)
6151             *lowpc = pdi->lowpc;
6152           if (pdi->highpc > *highpc)
6153             *highpc = pdi->highpc;
6154           if (need_pc)
6155             {
6156               CORE_ADDR baseaddr;
6157               struct objfile *objfile = cu->objfile;
6158
6159               baseaddr = ANOFFSET (objfile->section_offsets,
6160                                    SECT_OFF_TEXT (objfile));
6161               addrmap_set_empty (objfile->psymtabs_addrmap,
6162                                  pdi->lowpc + baseaddr,
6163                                  pdi->highpc - 1 + baseaddr,
6164                                  cu->per_cu->v.psymtab);
6165             }
6166         }
6167
6168       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6169         {
6170           if (!pdi->is_declaration)
6171             /* Ignore subprogram DIEs that do not have a name, they are
6172                illegal.  Do not emit a complaint at this point, we will
6173                do so when we convert this psymtab into a symtab.  */
6174             if (pdi->name)
6175               add_partial_symbol (pdi, cu);
6176         }
6177     }
6178
6179   if (! pdi->has_children)
6180     return;
6181
6182   if (cu->language == language_ada)
6183     {
6184       pdi = pdi->die_child;
6185       while (pdi != NULL)
6186         {
6187           fixup_partial_die (pdi, cu);
6188           if (pdi->tag == DW_TAG_subprogram
6189               || pdi->tag == DW_TAG_lexical_block)
6190             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6191           pdi = pdi->die_sibling;
6192         }
6193     }
6194 }
6195
6196 /* Read a partial die corresponding to an enumeration type.  */
6197
6198 static void
6199 add_partial_enumeration (struct partial_die_info *enum_pdi,
6200                          struct dwarf2_cu *cu)
6201 {
6202   struct partial_die_info *pdi;
6203
6204   if (enum_pdi->name != NULL)
6205     add_partial_symbol (enum_pdi, cu);
6206
6207   pdi = enum_pdi->die_child;
6208   while (pdi)
6209     {
6210       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6211         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6212       else
6213         add_partial_symbol (pdi, cu);
6214       pdi = pdi->die_sibling;
6215     }
6216 }
6217
6218 /* Return the initial uleb128 in the die at INFO_PTR.  */
6219
6220 static unsigned int
6221 peek_abbrev_code (bfd *abfd, gdb_byte *info_ptr)
6222 {
6223   unsigned int bytes_read;
6224
6225   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6226 }
6227
6228 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6229    Return the corresponding abbrev, or NULL if the number is zero (indicating
6230    an empty DIE).  In either case *BYTES_READ will be set to the length of
6231    the initial number.  */
6232
6233 static struct abbrev_info *
6234 peek_die_abbrev (gdb_byte *info_ptr, unsigned int *bytes_read,
6235                  struct dwarf2_cu *cu)
6236 {
6237   bfd *abfd = cu->objfile->obfd;
6238   unsigned int abbrev_number;
6239   struct abbrev_info *abbrev;
6240
6241   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6242
6243   if (abbrev_number == 0)
6244     return NULL;
6245
6246   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6247   if (!abbrev)
6248     {
6249       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6250              abbrev_number, bfd_get_filename (abfd));
6251     }
6252
6253   return abbrev;
6254 }
6255
6256 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6257    Returns a pointer to the end of a series of DIEs, terminated by an empty
6258    DIE.  Any children of the skipped DIEs will also be skipped.  */
6259
6260 static gdb_byte *
6261 skip_children (const struct die_reader_specs *reader, gdb_byte *info_ptr)
6262 {
6263   struct dwarf2_cu *cu = reader->cu;
6264   struct abbrev_info *abbrev;
6265   unsigned int bytes_read;
6266
6267   while (1)
6268     {
6269       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6270       if (abbrev == NULL)
6271         return info_ptr + bytes_read;
6272       else
6273         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6274     }
6275 }
6276
6277 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6278    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6279    abbrev corresponding to that skipped uleb128 should be passed in
6280    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6281    children.  */
6282
6283 static gdb_byte *
6284 skip_one_die (const struct die_reader_specs *reader, gdb_byte *info_ptr,
6285               struct abbrev_info *abbrev)
6286 {
6287   unsigned int bytes_read;
6288   struct attribute attr;
6289   bfd *abfd = reader->abfd;
6290   struct dwarf2_cu *cu = reader->cu;
6291   gdb_byte *buffer = reader->buffer;
6292   const gdb_byte *buffer_end = reader->buffer_end;
6293   gdb_byte *start_info_ptr = info_ptr;
6294   unsigned int form, i;
6295
6296   for (i = 0; i < abbrev->num_attrs; i++)
6297     {
6298       /* The only abbrev we care about is DW_AT_sibling.  */
6299       if (abbrev->attrs[i].name == DW_AT_sibling)
6300         {
6301           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
6302           if (attr.form == DW_FORM_ref_addr)
6303             complaint (&symfile_complaints,
6304                        _("ignoring absolute DW_AT_sibling"));
6305           else
6306             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
6307         }
6308
6309       /* If it isn't DW_AT_sibling, skip this attribute.  */
6310       form = abbrev->attrs[i].form;
6311     skip_attribute:
6312       switch (form)
6313         {
6314         case DW_FORM_ref_addr:
6315           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
6316              and later it is offset sized.  */
6317           if (cu->header.version == 2)
6318             info_ptr += cu->header.addr_size;
6319           else
6320             info_ptr += cu->header.offset_size;
6321           break;
6322         case DW_FORM_GNU_ref_alt:
6323           info_ptr += cu->header.offset_size;
6324           break;
6325         case DW_FORM_addr:
6326           info_ptr += cu->header.addr_size;
6327           break;
6328         case DW_FORM_data1:
6329         case DW_FORM_ref1:
6330         case DW_FORM_flag:
6331           info_ptr += 1;
6332           break;
6333         case DW_FORM_flag_present:
6334           break;
6335         case DW_FORM_data2:
6336         case DW_FORM_ref2:
6337           info_ptr += 2;
6338           break;
6339         case DW_FORM_data4:
6340         case DW_FORM_ref4:
6341           info_ptr += 4;
6342           break;
6343         case DW_FORM_data8:
6344         case DW_FORM_ref8:
6345         case DW_FORM_ref_sig8:
6346           info_ptr += 8;
6347           break;
6348         case DW_FORM_string:
6349           read_direct_string (abfd, info_ptr, &bytes_read);
6350           info_ptr += bytes_read;
6351           break;
6352         case DW_FORM_sec_offset:
6353         case DW_FORM_strp:
6354         case DW_FORM_GNU_strp_alt:
6355           info_ptr += cu->header.offset_size;
6356           break;
6357         case DW_FORM_exprloc:
6358         case DW_FORM_block:
6359           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6360           info_ptr += bytes_read;
6361           break;
6362         case DW_FORM_block1:
6363           info_ptr += 1 + read_1_byte (abfd, info_ptr);
6364           break;
6365         case DW_FORM_block2:
6366           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
6367           break;
6368         case DW_FORM_block4:
6369           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
6370           break;
6371         case DW_FORM_sdata:
6372         case DW_FORM_udata:
6373         case DW_FORM_ref_udata:
6374         case DW_FORM_GNU_addr_index:
6375         case DW_FORM_GNU_str_index:
6376           info_ptr = (gdb_byte *) safe_skip_leb128 (info_ptr, buffer_end);
6377           break;
6378         case DW_FORM_indirect:
6379           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6380           info_ptr += bytes_read;
6381           /* We need to continue parsing from here, so just go back to
6382              the top.  */
6383           goto skip_attribute;
6384
6385         default:
6386           error (_("Dwarf Error: Cannot handle %s "
6387                    "in DWARF reader [in module %s]"),
6388                  dwarf_form_name (form),
6389                  bfd_get_filename (abfd));
6390         }
6391     }
6392
6393   if (abbrev->has_children)
6394     return skip_children (reader, info_ptr);
6395   else
6396     return info_ptr;
6397 }
6398
6399 /* Locate ORIG_PDI's sibling.
6400    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
6401
6402 static gdb_byte *
6403 locate_pdi_sibling (const struct die_reader_specs *reader,
6404                     struct partial_die_info *orig_pdi,
6405                     gdb_byte *info_ptr)
6406 {
6407   /* Do we know the sibling already?  */
6408
6409   if (orig_pdi->sibling)
6410     return orig_pdi->sibling;
6411
6412   /* Are there any children to deal with?  */
6413
6414   if (!orig_pdi->has_children)
6415     return info_ptr;
6416
6417   /* Skip the children the long way.  */
6418
6419   return skip_children (reader, info_ptr);
6420 }
6421
6422 /* Expand this partial symbol table into a full symbol table.  SELF is
6423    not NULL.  */
6424
6425 static void
6426 dwarf2_read_symtab (struct partial_symtab *self,
6427                     struct objfile *objfile)
6428 {
6429   if (self->readin)
6430     {
6431       warning (_("bug: psymtab for %s is already read in."),
6432                self->filename);
6433     }
6434   else
6435     {
6436       if (info_verbose)
6437         {
6438           printf_filtered (_("Reading in symbols for %s..."),
6439                            self->filename);
6440           gdb_flush (gdb_stdout);
6441         }
6442
6443       /* Restore our global data.  */
6444       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
6445
6446       /* If this psymtab is constructed from a debug-only objfile, the
6447          has_section_at_zero flag will not necessarily be correct.  We
6448          can get the correct value for this flag by looking at the data
6449          associated with the (presumably stripped) associated objfile.  */
6450       if (objfile->separate_debug_objfile_backlink)
6451         {
6452           struct dwarf2_per_objfile *dpo_backlink
6453             = objfile_data (objfile->separate_debug_objfile_backlink,
6454                             dwarf2_objfile_data_key);
6455
6456           dwarf2_per_objfile->has_section_at_zero
6457             = dpo_backlink->has_section_at_zero;
6458         }
6459
6460       dwarf2_per_objfile->reading_partial_symbols = 0;
6461
6462       psymtab_to_symtab_1 (self);
6463
6464       /* Finish up the debug error message.  */
6465       if (info_verbose)
6466         printf_filtered (_("done.\n"));
6467     }
6468
6469   process_cu_includes ();
6470 }
6471 \f
6472 /* Reading in full CUs.  */
6473
6474 /* Add PER_CU to the queue.  */
6475
6476 static void
6477 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
6478                  enum language pretend_language)
6479 {
6480   struct dwarf2_queue_item *item;
6481
6482   per_cu->queued = 1;
6483   item = xmalloc (sizeof (*item));
6484   item->per_cu = per_cu;
6485   item->pretend_language = pretend_language;
6486   item->next = NULL;
6487
6488   if (dwarf2_queue == NULL)
6489     dwarf2_queue = item;
6490   else
6491     dwarf2_queue_tail->next = item;
6492
6493   dwarf2_queue_tail = item;
6494 }
6495
6496 /* THIS_CU has a reference to PER_CU.  If necessary, load the new compilation
6497    unit and add it to our queue.
6498    The result is non-zero if PER_CU was queued, otherwise the result is zero
6499    meaning either PER_CU is already queued or it is already loaded.  */
6500
6501 static int
6502 maybe_queue_comp_unit (struct dwarf2_cu *this_cu,
6503                        struct dwarf2_per_cu_data *per_cu,
6504                        enum language pretend_language)
6505 {
6506   /* We may arrive here during partial symbol reading, if we need full
6507      DIEs to process an unusual case (e.g. template arguments).  Do
6508      not queue PER_CU, just tell our caller to load its DIEs.  */
6509   if (dwarf2_per_objfile->reading_partial_symbols)
6510     {
6511       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
6512         return 1;
6513       return 0;
6514     }
6515
6516   /* Mark the dependence relation so that we don't flush PER_CU
6517      too early.  */
6518   dwarf2_add_dependence (this_cu, per_cu);
6519
6520   /* If it's already on the queue, we have nothing to do.  */
6521   if (per_cu->queued)
6522     return 0;
6523
6524   /* If the compilation unit is already loaded, just mark it as
6525      used.  */
6526   if (per_cu->cu != NULL)
6527     {
6528       per_cu->cu->last_used = 0;
6529       return 0;
6530     }
6531
6532   /* Add it to the queue.  */
6533   queue_comp_unit (per_cu, pretend_language);
6534
6535   return 1;
6536 }
6537
6538 /* Process the queue.  */
6539
6540 static void
6541 process_queue (void)
6542 {
6543   struct dwarf2_queue_item *item, *next_item;
6544
6545   if (dwarf2_read_debug)
6546     {
6547       fprintf_unfiltered (gdb_stdlog,
6548                           "Expanding one or more symtabs of objfile %s ...\n",
6549                           dwarf2_per_objfile->objfile->name);
6550     }
6551
6552   /* The queue starts out with one item, but following a DIE reference
6553      may load a new CU, adding it to the end of the queue.  */
6554   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
6555     {
6556       if (dwarf2_per_objfile->using_index
6557           ? !item->per_cu->v.quick->symtab
6558           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
6559         {
6560           struct dwarf2_per_cu_data *per_cu = item->per_cu;
6561
6562           if (dwarf2_read_debug)
6563             {
6564               fprintf_unfiltered (gdb_stdlog,
6565                                   "Expanding symtab of %s at offset 0x%x\n",
6566                                   per_cu->is_debug_types ? "TU" : "CU",
6567                                   per_cu->offset.sect_off);
6568             }
6569
6570           if (per_cu->is_debug_types)
6571             process_full_type_unit (per_cu, item->pretend_language);
6572           else
6573             process_full_comp_unit (per_cu, item->pretend_language);
6574
6575           if (dwarf2_read_debug)
6576             {
6577               fprintf_unfiltered (gdb_stdlog,
6578                                   "Done expanding %s at offset 0x%x\n",
6579                                   per_cu->is_debug_types ? "TU" : "CU",
6580                                   per_cu->offset.sect_off);
6581             }
6582         }
6583
6584       item->per_cu->queued = 0;
6585       next_item = item->next;
6586       xfree (item);
6587     }
6588
6589   dwarf2_queue_tail = NULL;
6590
6591   if (dwarf2_read_debug)
6592     {
6593       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
6594                           dwarf2_per_objfile->objfile->name);
6595     }
6596 }
6597
6598 /* Free all allocated queue entries.  This function only releases anything if
6599    an error was thrown; if the queue was processed then it would have been
6600    freed as we went along.  */
6601
6602 static void
6603 dwarf2_release_queue (void *dummy)
6604 {
6605   struct dwarf2_queue_item *item, *last;
6606
6607   item = dwarf2_queue;
6608   while (item)
6609     {
6610       /* Anything still marked queued is likely to be in an
6611          inconsistent state, so discard it.  */
6612       if (item->per_cu->queued)
6613         {
6614           if (item->per_cu->cu != NULL)
6615             free_one_cached_comp_unit (item->per_cu);
6616           item->per_cu->queued = 0;
6617         }
6618
6619       last = item;
6620       item = item->next;
6621       xfree (last);
6622     }
6623
6624   dwarf2_queue = dwarf2_queue_tail = NULL;
6625 }
6626
6627 /* Read in full symbols for PST, and anything it depends on.  */
6628
6629 static void
6630 psymtab_to_symtab_1 (struct partial_symtab *pst)
6631 {
6632   struct dwarf2_per_cu_data *per_cu;
6633   int i;
6634
6635   if (pst->readin)
6636     return;
6637
6638   for (i = 0; i < pst->number_of_dependencies; i++)
6639     if (!pst->dependencies[i]->readin
6640         && pst->dependencies[i]->user == NULL)
6641       {
6642         /* Inform about additional files that need to be read in.  */
6643         if (info_verbose)
6644           {
6645             /* FIXME: i18n: Need to make this a single string.  */
6646             fputs_filtered (" ", gdb_stdout);
6647             wrap_here ("");
6648             fputs_filtered ("and ", gdb_stdout);
6649             wrap_here ("");
6650             printf_filtered ("%s...", pst->dependencies[i]->filename);
6651             wrap_here ("");     /* Flush output.  */
6652             gdb_flush (gdb_stdout);
6653           }
6654         psymtab_to_symtab_1 (pst->dependencies[i]);
6655       }
6656
6657   per_cu = pst->read_symtab_private;
6658
6659   if (per_cu == NULL)
6660     {
6661       /* It's an include file, no symbols to read for it.
6662          Everything is in the parent symtab.  */
6663       pst->readin = 1;
6664       return;
6665     }
6666
6667   dw2_do_instantiate_symtab (per_cu);
6668 }
6669
6670 /* Trivial hash function for die_info: the hash value of a DIE
6671    is its offset in .debug_info for this objfile.  */
6672
6673 static hashval_t
6674 die_hash (const void *item)
6675 {
6676   const struct die_info *die = item;
6677
6678   return die->offset.sect_off;
6679 }
6680
6681 /* Trivial comparison function for die_info structures: two DIEs
6682    are equal if they have the same offset.  */
6683
6684 static int
6685 die_eq (const void *item_lhs, const void *item_rhs)
6686 {
6687   const struct die_info *die_lhs = item_lhs;
6688   const struct die_info *die_rhs = item_rhs;
6689
6690   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
6691 }
6692
6693 /* die_reader_func for load_full_comp_unit.
6694    This is identical to read_signatured_type_reader,
6695    but is kept separate for now.  */
6696
6697 static void
6698 load_full_comp_unit_reader (const struct die_reader_specs *reader,
6699                             gdb_byte *info_ptr,
6700                             struct die_info *comp_unit_die,
6701                             int has_children,
6702                             void *data)
6703 {
6704   struct dwarf2_cu *cu = reader->cu;
6705   enum language *language_ptr = data;
6706
6707   gdb_assert (cu->die_hash == NULL);
6708   cu->die_hash =
6709     htab_create_alloc_ex (cu->header.length / 12,
6710                           die_hash,
6711                           die_eq,
6712                           NULL,
6713                           &cu->comp_unit_obstack,
6714                           hashtab_obstack_allocate,
6715                           dummy_obstack_deallocate);
6716
6717   if (has_children)
6718     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
6719                                                   &info_ptr, comp_unit_die);
6720   cu->dies = comp_unit_die;
6721   /* comp_unit_die is not stored in die_hash, no need.  */
6722
6723   /* We try not to read any attributes in this function, because not
6724      all CUs needed for references have been loaded yet, and symbol
6725      table processing isn't initialized.  But we have to set the CU language,
6726      or we won't be able to build types correctly.
6727      Similarly, if we do not read the producer, we can not apply
6728      producer-specific interpretation.  */
6729   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
6730 }
6731
6732 /* Load the DIEs associated with PER_CU into memory.  */
6733
6734 static void
6735 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
6736                      enum language pretend_language)
6737 {
6738   gdb_assert (! this_cu->is_debug_types);
6739
6740   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6741                            load_full_comp_unit_reader, &pretend_language);
6742 }
6743
6744 /* Add a DIE to the delayed physname list.  */
6745
6746 static void
6747 add_to_method_list (struct type *type, int fnfield_index, int index,
6748                     const char *name, struct die_info *die,
6749                     struct dwarf2_cu *cu)
6750 {
6751   struct delayed_method_info mi;
6752   mi.type = type;
6753   mi.fnfield_index = fnfield_index;
6754   mi.index = index;
6755   mi.name = name;
6756   mi.die = die;
6757   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
6758 }
6759
6760 /* A cleanup for freeing the delayed method list.  */
6761
6762 static void
6763 free_delayed_list (void *ptr)
6764 {
6765   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
6766   if (cu->method_list != NULL)
6767     {
6768       VEC_free (delayed_method_info, cu->method_list);
6769       cu->method_list = NULL;
6770     }
6771 }
6772
6773 /* Compute the physnames of any methods on the CU's method list.
6774
6775    The computation of method physnames is delayed in order to avoid the
6776    (bad) condition that one of the method's formal parameters is of an as yet
6777    incomplete type.  */
6778
6779 static void
6780 compute_delayed_physnames (struct dwarf2_cu *cu)
6781 {
6782   int i;
6783   struct delayed_method_info *mi;
6784   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
6785     {
6786       const char *physname;
6787       struct fn_fieldlist *fn_flp
6788         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
6789       physname = dwarf2_physname (mi->name, mi->die, cu);
6790       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
6791     }
6792 }
6793
6794 /* Go objects should be embedded in a DW_TAG_module DIE,
6795    and it's not clear if/how imported objects will appear.
6796    To keep Go support simple until that's worked out,
6797    go back through what we've read and create something usable.
6798    We could do this while processing each DIE, and feels kinda cleaner,
6799    but that way is more invasive.
6800    This is to, for example, allow the user to type "p var" or "b main"
6801    without having to specify the package name, and allow lookups
6802    of module.object to work in contexts that use the expression
6803    parser.  */
6804
6805 static void
6806 fixup_go_packaging (struct dwarf2_cu *cu)
6807 {
6808   char *package_name = NULL;
6809   struct pending *list;
6810   int i;
6811
6812   for (list = global_symbols; list != NULL; list = list->next)
6813     {
6814       for (i = 0; i < list->nsyms; ++i)
6815         {
6816           struct symbol *sym = list->symbol[i];
6817
6818           if (SYMBOL_LANGUAGE (sym) == language_go
6819               && SYMBOL_CLASS (sym) == LOC_BLOCK)
6820             {
6821               char *this_package_name = go_symbol_package_name (sym);
6822
6823               if (this_package_name == NULL)
6824                 continue;
6825               if (package_name == NULL)
6826                 package_name = this_package_name;
6827               else
6828                 {
6829                   if (strcmp (package_name, this_package_name) != 0)
6830                     complaint (&symfile_complaints,
6831                                _("Symtab %s has objects from two different Go packages: %s and %s"),
6832                                (SYMBOL_SYMTAB (sym)
6833                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
6834                                 : cu->objfile->name),
6835                                this_package_name, package_name);
6836                   xfree (this_package_name);
6837                 }
6838             }
6839         }
6840     }
6841
6842   if (package_name != NULL)
6843     {
6844       struct objfile *objfile = cu->objfile;
6845       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
6846                                                       package_name,
6847                                                       strlen (package_name));
6848       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
6849                                      saved_package_name, objfile);
6850       struct symbol *sym;
6851
6852       TYPE_TAG_NAME (type) = TYPE_NAME (type);
6853
6854       sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
6855       SYMBOL_SET_LANGUAGE (sym, language_go);
6856       SYMBOL_SET_NAMES (sym, saved_package_name,
6857                         strlen (saved_package_name), 0, objfile);
6858       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
6859          e.g., "main" finds the "main" module and not C's main().  */
6860       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
6861       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
6862       SYMBOL_TYPE (sym) = type;
6863
6864       add_symbol_to_list (sym, &global_symbols);
6865
6866       xfree (package_name);
6867     }
6868 }
6869
6870 /* Return the symtab for PER_CU.  This works properly regardless of
6871    whether we're using the index or psymtabs.  */
6872
6873 static struct symtab *
6874 get_symtab (struct dwarf2_per_cu_data *per_cu)
6875 {
6876   return (dwarf2_per_objfile->using_index
6877           ? per_cu->v.quick->symtab
6878           : per_cu->v.psymtab->symtab);
6879 }
6880
6881 /* A helper function for computing the list of all symbol tables
6882    included by PER_CU.  */
6883
6884 static void
6885 recursively_compute_inclusions (VEC (dwarf2_per_cu_ptr) **result,
6886                                 htab_t all_children,
6887                                 struct dwarf2_per_cu_data *per_cu)
6888 {
6889   void **slot;
6890   int ix;
6891   struct dwarf2_per_cu_data *iter;
6892
6893   slot = htab_find_slot (all_children, per_cu, INSERT);
6894   if (*slot != NULL)
6895     {
6896       /* This inclusion and its children have been processed.  */
6897       return;
6898     }
6899
6900   *slot = per_cu;
6901   /* Only add a CU if it has a symbol table.  */
6902   if (get_symtab (per_cu) != NULL)
6903     VEC_safe_push (dwarf2_per_cu_ptr, *result, per_cu);
6904
6905   for (ix = 0;
6906        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
6907        ++ix)
6908     recursively_compute_inclusions (result, all_children, iter);
6909 }
6910
6911 /* Compute the symtab 'includes' fields for the symtab related to
6912    PER_CU.  */
6913
6914 static void
6915 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
6916 {
6917   gdb_assert (! per_cu->is_debug_types);
6918
6919   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
6920     {
6921       int ix, len;
6922       struct dwarf2_per_cu_data *iter;
6923       VEC (dwarf2_per_cu_ptr) *result_children = NULL;
6924       htab_t all_children;
6925       struct symtab *symtab = get_symtab (per_cu);
6926
6927       /* If we don't have a symtab, we can just skip this case.  */
6928       if (symtab == NULL)
6929         return;
6930
6931       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
6932                                         NULL, xcalloc, xfree);
6933
6934       for (ix = 0;
6935            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
6936                         ix, iter);
6937            ++ix)
6938         recursively_compute_inclusions (&result_children, all_children, iter);
6939
6940       /* Now we have a transitive closure of all the included CUs, and
6941          for .gdb_index version 7 the included TUs, so we can convert it
6942          to a list of symtabs.  */
6943       len = VEC_length (dwarf2_per_cu_ptr, result_children);
6944       symtab->includes
6945         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
6946                          (len + 1) * sizeof (struct symtab *));
6947       for (ix = 0;
6948            VEC_iterate (dwarf2_per_cu_ptr, result_children, ix, iter);
6949            ++ix)
6950         symtab->includes[ix] = get_symtab (iter);
6951       symtab->includes[len] = NULL;
6952
6953       VEC_free (dwarf2_per_cu_ptr, result_children);
6954       htab_delete (all_children);
6955     }
6956 }
6957
6958 /* Compute the 'includes' field for the symtabs of all the CUs we just
6959    read.  */
6960
6961 static void
6962 process_cu_includes (void)
6963 {
6964   int ix;
6965   struct dwarf2_per_cu_data *iter;
6966
6967   for (ix = 0;
6968        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
6969                     ix, iter);
6970        ++ix)
6971     {
6972       if (! iter->is_debug_types)
6973         compute_symtab_includes (iter);
6974     }
6975
6976   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
6977 }
6978
6979 /* Generate full symbol information for PER_CU, whose DIEs have
6980    already been loaded into memory.  */
6981
6982 static void
6983 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
6984                         enum language pretend_language)
6985 {
6986   struct dwarf2_cu *cu = per_cu->cu;
6987   struct objfile *objfile = per_cu->objfile;
6988   CORE_ADDR lowpc, highpc;
6989   struct symtab *symtab;
6990   struct cleanup *back_to, *delayed_list_cleanup;
6991   CORE_ADDR baseaddr;
6992   struct block *static_block;
6993
6994   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6995
6996   buildsym_init ();
6997   back_to = make_cleanup (really_free_pendings, NULL);
6998   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
6999
7000   cu->list_in_scope = &file_symbols;
7001
7002   cu->language = pretend_language;
7003   cu->language_defn = language_def (cu->language);
7004
7005   /* Do line number decoding in read_file_scope () */
7006   process_die (cu->dies, cu);
7007
7008   /* For now fudge the Go package.  */
7009   if (cu->language == language_go)
7010     fixup_go_packaging (cu);
7011
7012   /* Now that we have processed all the DIEs in the CU, all the types 
7013      should be complete, and it should now be safe to compute all of the
7014      physnames.  */
7015   compute_delayed_physnames (cu);
7016   do_cleanups (delayed_list_cleanup);
7017
7018   /* Some compilers don't define a DW_AT_high_pc attribute for the
7019      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7020      it, by scanning the DIE's below the compilation unit.  */
7021   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7022
7023   static_block
7024     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0,
7025                                    per_cu->imported_symtabs != NULL);
7026
7027   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7028      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7029      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7030      addrmap to help ensure it has an accurate map of pc values belonging to
7031      this comp unit.  */
7032   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7033
7034   symtab = end_symtab_from_static_block (static_block, objfile,
7035                                          SECT_OFF_TEXT (objfile), 0);
7036
7037   if (symtab != NULL)
7038     {
7039       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7040
7041       /* Set symtab language to language from DW_AT_language.  If the
7042          compilation is from a C file generated by language preprocessors, do
7043          not set the language if it was already deduced by start_subfile.  */
7044       if (!(cu->language == language_c && symtab->language != language_c))
7045         symtab->language = cu->language;
7046
7047       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7048          produce DW_AT_location with location lists but it can be possibly
7049          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7050          there were bugs in prologue debug info, fixed later in GCC-4.5
7051          by "unwind info for epilogues" patch (which is not directly related).
7052
7053          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7054          needed, it would be wrong due to missing DW_AT_producer there.
7055
7056          Still one can confuse GDB by using non-standard GCC compilation
7057          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7058          */ 
7059       if (cu->has_loclist && gcc_4_minor >= 5)
7060         symtab->locations_valid = 1;
7061
7062       if (gcc_4_minor >= 5)
7063         symtab->epilogue_unwind_valid = 1;
7064
7065       symtab->call_site_htab = cu->call_site_htab;
7066     }
7067
7068   if (dwarf2_per_objfile->using_index)
7069     per_cu->v.quick->symtab = symtab;
7070   else
7071     {
7072       struct partial_symtab *pst = per_cu->v.psymtab;
7073       pst->symtab = symtab;
7074       pst->readin = 1;
7075     }
7076
7077   /* Push it for inclusion processing later.  */
7078   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7079
7080   do_cleanups (back_to);
7081 }
7082
7083 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7084    already been loaded into memory.  */
7085
7086 static void
7087 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7088                         enum language pretend_language)
7089 {
7090   struct dwarf2_cu *cu = per_cu->cu;
7091   struct objfile *objfile = per_cu->objfile;
7092   struct symtab *symtab;
7093   struct cleanup *back_to, *delayed_list_cleanup;
7094
7095   buildsym_init ();
7096   back_to = make_cleanup (really_free_pendings, NULL);
7097   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7098
7099   cu->list_in_scope = &file_symbols;
7100
7101   cu->language = pretend_language;
7102   cu->language_defn = language_def (cu->language);
7103
7104   /* The symbol tables are set up in read_type_unit_scope.  */
7105   process_die (cu->dies, cu);
7106
7107   /* For now fudge the Go package.  */
7108   if (cu->language == language_go)
7109     fixup_go_packaging (cu);
7110
7111   /* Now that we have processed all the DIEs in the CU, all the types 
7112      should be complete, and it should now be safe to compute all of the
7113      physnames.  */
7114   compute_delayed_physnames (cu);
7115   do_cleanups (delayed_list_cleanup);
7116
7117   /* TUs share symbol tables.
7118      If this is the first TU to use this symtab, complete the construction
7119      of it with end_expandable_symtab.  Otherwise, complete the addition of
7120      this TU's symbols to the existing symtab.  */
7121   if (per_cu->type_unit_group->primary_symtab == NULL)
7122     {
7123       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7124       per_cu->type_unit_group->primary_symtab = symtab;
7125
7126       if (symtab != NULL)
7127         {
7128           /* Set symtab language to language from DW_AT_language.  If the
7129              compilation is from a C file generated by language preprocessors,
7130              do not set the language if it was already deduced by
7131              start_subfile.  */
7132           if (!(cu->language == language_c && symtab->language != language_c))
7133             symtab->language = cu->language;
7134         }
7135     }
7136   else
7137     {
7138       augment_type_symtab (objfile,
7139                            per_cu->type_unit_group->primary_symtab);
7140       symtab = per_cu->type_unit_group->primary_symtab;
7141     }
7142
7143   if (dwarf2_per_objfile->using_index)
7144     per_cu->v.quick->symtab = symtab;
7145   else
7146     {
7147       struct partial_symtab *pst = per_cu->v.psymtab;
7148       pst->symtab = symtab;
7149       pst->readin = 1;
7150     }
7151
7152   do_cleanups (back_to);
7153 }
7154
7155 /* Process an imported unit DIE.  */
7156
7157 static void
7158 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7159 {
7160   struct attribute *attr;
7161
7162   /* For now we don't handle imported units in type units.  */
7163   if (cu->per_cu->is_debug_types)
7164     {
7165       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7166                " supported in type units [in module %s]"),
7167              cu->objfile->name);
7168     }
7169
7170   attr = dwarf2_attr (die, DW_AT_import, cu);
7171   if (attr != NULL)
7172     {
7173       struct dwarf2_per_cu_data *per_cu;
7174       struct symtab *imported_symtab;
7175       sect_offset offset;
7176       int is_dwz;
7177
7178       offset = dwarf2_get_ref_die_offset (attr);
7179       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7180       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7181
7182       /* Queue the unit, if needed.  */
7183       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7184         load_full_comp_unit (per_cu, cu->language);
7185
7186       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7187                      per_cu);
7188     }
7189 }
7190
7191 /* Process a die and its children.  */
7192
7193 static void
7194 process_die (struct die_info *die, struct dwarf2_cu *cu)
7195 {
7196   switch (die->tag)
7197     {
7198     case DW_TAG_padding:
7199       break;
7200     case DW_TAG_compile_unit:
7201     case DW_TAG_partial_unit:
7202       read_file_scope (die, cu);
7203       break;
7204     case DW_TAG_type_unit:
7205       read_type_unit_scope (die, cu);
7206       break;
7207     case DW_TAG_subprogram:
7208     case DW_TAG_inlined_subroutine:
7209       read_func_scope (die, cu);
7210       break;
7211     case DW_TAG_lexical_block:
7212     case DW_TAG_try_block:
7213     case DW_TAG_catch_block:
7214       read_lexical_block_scope (die, cu);
7215       break;
7216     case DW_TAG_GNU_call_site:
7217       read_call_site_scope (die, cu);
7218       break;
7219     case DW_TAG_class_type:
7220     case DW_TAG_interface_type:
7221     case DW_TAG_structure_type:
7222     case DW_TAG_union_type:
7223       process_structure_scope (die, cu);
7224       break;
7225     case DW_TAG_enumeration_type:
7226       process_enumeration_scope (die, cu);
7227       break;
7228
7229     /* These dies have a type, but processing them does not create
7230        a symbol or recurse to process the children.  Therefore we can
7231        read them on-demand through read_type_die.  */
7232     case DW_TAG_subroutine_type:
7233     case DW_TAG_set_type:
7234     case DW_TAG_array_type:
7235     case DW_TAG_pointer_type:
7236     case DW_TAG_ptr_to_member_type:
7237     case DW_TAG_reference_type:
7238     case DW_TAG_string_type:
7239       break;
7240
7241     case DW_TAG_base_type:
7242     case DW_TAG_subrange_type:
7243     case DW_TAG_typedef:
7244       /* Add a typedef symbol for the type definition, if it has a
7245          DW_AT_name.  */
7246       new_symbol (die, read_type_die (die, cu), cu);
7247       break;
7248     case DW_TAG_common_block:
7249       read_common_block (die, cu);
7250       break;
7251     case DW_TAG_common_inclusion:
7252       break;
7253     case DW_TAG_namespace:
7254       cu->processing_has_namespace_info = 1;
7255       read_namespace (die, cu);
7256       break;
7257     case DW_TAG_module:
7258       cu->processing_has_namespace_info = 1;
7259       read_module (die, cu);
7260       break;
7261     case DW_TAG_imported_declaration:
7262     case DW_TAG_imported_module:
7263       cu->processing_has_namespace_info = 1;
7264       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
7265                                  || cu->language != language_fortran))
7266         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
7267                    dwarf_tag_name (die->tag));
7268       read_import_statement (die, cu);
7269       break;
7270
7271     case DW_TAG_imported_unit:
7272       process_imported_unit_die (die, cu);
7273       break;
7274
7275     default:
7276       new_symbol (die, NULL, cu);
7277       break;
7278     }
7279 }
7280 \f
7281 /* DWARF name computation.  */
7282
7283 /* A helper function for dwarf2_compute_name which determines whether DIE
7284    needs to have the name of the scope prepended to the name listed in the
7285    die.  */
7286
7287 static int
7288 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
7289 {
7290   struct attribute *attr;
7291
7292   switch (die->tag)
7293     {
7294     case DW_TAG_namespace:
7295     case DW_TAG_typedef:
7296     case DW_TAG_class_type:
7297     case DW_TAG_interface_type:
7298     case DW_TAG_structure_type:
7299     case DW_TAG_union_type:
7300     case DW_TAG_enumeration_type:
7301     case DW_TAG_enumerator:
7302     case DW_TAG_subprogram:
7303     case DW_TAG_member:
7304       return 1;
7305
7306     case DW_TAG_variable:
7307     case DW_TAG_constant:
7308       /* We only need to prefix "globally" visible variables.  These include
7309          any variable marked with DW_AT_external or any variable that
7310          lives in a namespace.  [Variables in anonymous namespaces
7311          require prefixing, but they are not DW_AT_external.]  */
7312
7313       if (dwarf2_attr (die, DW_AT_specification, cu))
7314         {
7315           struct dwarf2_cu *spec_cu = cu;
7316
7317           return die_needs_namespace (die_specification (die, &spec_cu),
7318                                       spec_cu);
7319         }
7320
7321       attr = dwarf2_attr (die, DW_AT_external, cu);
7322       if (attr == NULL && die->parent->tag != DW_TAG_namespace
7323           && die->parent->tag != DW_TAG_module)
7324         return 0;
7325       /* A variable in a lexical block of some kind does not need a
7326          namespace, even though in C++ such variables may be external
7327          and have a mangled name.  */
7328       if (die->parent->tag ==  DW_TAG_lexical_block
7329           || die->parent->tag ==  DW_TAG_try_block
7330           || die->parent->tag ==  DW_TAG_catch_block
7331           || die->parent->tag == DW_TAG_subprogram)
7332         return 0;
7333       return 1;
7334
7335     default:
7336       return 0;
7337     }
7338 }
7339
7340 /* Retrieve the last character from a mem_file.  */
7341
7342 static void
7343 do_ui_file_peek_last (void *object, const char *buffer, long length)
7344 {
7345   char *last_char_p = (char *) object;
7346
7347   if (length > 0)
7348     *last_char_p = buffer[length - 1];
7349 }
7350
7351 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
7352    compute the physname for the object, which include a method's:
7353    - formal parameters (C++/Java),
7354    - receiver type (Go),
7355    - return type (Java).
7356
7357    The term "physname" is a bit confusing.
7358    For C++, for example, it is the demangled name.
7359    For Go, for example, it's the mangled name.
7360
7361    For Ada, return the DIE's linkage name rather than the fully qualified
7362    name.  PHYSNAME is ignored..
7363
7364    The result is allocated on the objfile_obstack and canonicalized.  */
7365
7366 static const char *
7367 dwarf2_compute_name (const char *name,
7368                      struct die_info *die, struct dwarf2_cu *cu,
7369                      int physname)
7370 {
7371   struct objfile *objfile = cu->objfile;
7372
7373   if (name == NULL)
7374     name = dwarf2_name (die, cu);
7375
7376   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
7377      compute it by typename_concat inside GDB.  */
7378   if (cu->language == language_ada
7379       || (cu->language == language_fortran && physname))
7380     {
7381       /* For Ada unit, we prefer the linkage name over the name, as
7382          the former contains the exported name, which the user expects
7383          to be able to reference.  Ideally, we want the user to be able
7384          to reference this entity using either natural or linkage name,
7385          but we haven't started looking at this enhancement yet.  */
7386       struct attribute *attr;
7387
7388       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7389       if (attr == NULL)
7390         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7391       if (attr && DW_STRING (attr))
7392         return DW_STRING (attr);
7393     }
7394
7395   /* These are the only languages we know how to qualify names in.  */
7396   if (name != NULL
7397       && (cu->language == language_cplus || cu->language == language_java
7398           || cu->language == language_fortran))
7399     {
7400       if (die_needs_namespace (die, cu))
7401         {
7402           long length;
7403           const char *prefix;
7404           struct ui_file *buf;
7405
7406           prefix = determine_prefix (die, cu);
7407           buf = mem_fileopen ();
7408           if (*prefix != '\0')
7409             {
7410               char *prefixed_name = typename_concat (NULL, prefix, name,
7411                                                      physname, cu);
7412
7413               fputs_unfiltered (prefixed_name, buf);
7414               xfree (prefixed_name);
7415             }
7416           else
7417             fputs_unfiltered (name, buf);
7418
7419           /* Template parameters may be specified in the DIE's DW_AT_name, or
7420              as children with DW_TAG_template_type_param or
7421              DW_TAG_value_type_param.  If the latter, add them to the name
7422              here.  If the name already has template parameters, then
7423              skip this step; some versions of GCC emit both, and
7424              it is more efficient to use the pre-computed name.
7425
7426              Something to keep in mind about this process: it is very
7427              unlikely, or in some cases downright impossible, to produce
7428              something that will match the mangled name of a function.
7429              If the definition of the function has the same debug info,
7430              we should be able to match up with it anyway.  But fallbacks
7431              using the minimal symbol, for instance to find a method
7432              implemented in a stripped copy of libstdc++, will not work.
7433              If we do not have debug info for the definition, we will have to
7434              match them up some other way.
7435
7436              When we do name matching there is a related problem with function
7437              templates; two instantiated function templates are allowed to
7438              differ only by their return types, which we do not add here.  */
7439
7440           if (cu->language == language_cplus && strchr (name, '<') == NULL)
7441             {
7442               struct attribute *attr;
7443               struct die_info *child;
7444               int first = 1;
7445
7446               die->building_fullname = 1;
7447
7448               for (child = die->child; child != NULL; child = child->sibling)
7449                 {
7450                   struct type *type;
7451                   LONGEST value;
7452                   gdb_byte *bytes;
7453                   struct dwarf2_locexpr_baton *baton;
7454                   struct value *v;
7455
7456                   if (child->tag != DW_TAG_template_type_param
7457                       && child->tag != DW_TAG_template_value_param)
7458                     continue;
7459
7460                   if (first)
7461                     {
7462                       fputs_unfiltered ("<", buf);
7463                       first = 0;
7464                     }
7465                   else
7466                     fputs_unfiltered (", ", buf);
7467
7468                   attr = dwarf2_attr (child, DW_AT_type, cu);
7469                   if (attr == NULL)
7470                     {
7471                       complaint (&symfile_complaints,
7472                                  _("template parameter missing DW_AT_type"));
7473                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
7474                       continue;
7475                     }
7476                   type = die_type (child, cu);
7477
7478                   if (child->tag == DW_TAG_template_type_param)
7479                     {
7480                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
7481                       continue;
7482                     }
7483
7484                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
7485                   if (attr == NULL)
7486                     {
7487                       complaint (&symfile_complaints,
7488                                  _("template parameter missing "
7489                                    "DW_AT_const_value"));
7490                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
7491                       continue;
7492                     }
7493
7494                   dwarf2_const_value_attr (attr, type, name,
7495                                            &cu->comp_unit_obstack, cu,
7496                                            &value, &bytes, &baton);
7497
7498                   if (TYPE_NOSIGN (type))
7499                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
7500                        changed, this can use value_print instead.  */
7501                     c_printchar (value, type, buf);
7502                   else
7503                     {
7504                       struct value_print_options opts;
7505
7506                       if (baton != NULL)
7507                         v = dwarf2_evaluate_loc_desc (type, NULL,
7508                                                       baton->data,
7509                                                       baton->size,
7510                                                       baton->per_cu);
7511                       else if (bytes != NULL)
7512                         {
7513                           v = allocate_value (type);
7514                           memcpy (value_contents_writeable (v), bytes,
7515                                   TYPE_LENGTH (type));
7516                         }
7517                       else
7518                         v = value_from_longest (type, value);
7519
7520                       /* Specify decimal so that we do not depend on
7521                          the radix.  */
7522                       get_formatted_print_options (&opts, 'd');
7523                       opts.raw = 1;
7524                       value_print (v, buf, &opts);
7525                       release_value (v);
7526                       value_free (v);
7527                     }
7528                 }
7529
7530               die->building_fullname = 0;
7531
7532               if (!first)
7533                 {
7534                   /* Close the argument list, with a space if necessary
7535                      (nested templates).  */
7536                   char last_char = '\0';
7537                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
7538                   if (last_char == '>')
7539                     fputs_unfiltered (" >", buf);
7540                   else
7541                     fputs_unfiltered (">", buf);
7542                 }
7543             }
7544
7545           /* For Java and C++ methods, append formal parameter type
7546              information, if PHYSNAME.  */
7547
7548           if (physname && die->tag == DW_TAG_subprogram
7549               && (cu->language == language_cplus
7550                   || cu->language == language_java))
7551             {
7552               struct type *type = read_type_die (die, cu);
7553
7554               c_type_print_args (type, buf, 1, cu->language,
7555                                  &type_print_raw_options);
7556
7557               if (cu->language == language_java)
7558                 {
7559                   /* For java, we must append the return type to method
7560                      names.  */
7561                   if (die->tag == DW_TAG_subprogram)
7562                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
7563                                      0, 0, &type_print_raw_options);
7564                 }
7565               else if (cu->language == language_cplus)
7566                 {
7567                   /* Assume that an artificial first parameter is
7568                      "this", but do not crash if it is not.  RealView
7569                      marks unnamed (and thus unused) parameters as
7570                      artificial; there is no way to differentiate
7571                      the two cases.  */
7572                   if (TYPE_NFIELDS (type) > 0
7573                       && TYPE_FIELD_ARTIFICIAL (type, 0)
7574                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
7575                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
7576                                                                         0))))
7577                     fputs_unfiltered (" const", buf);
7578                 }
7579             }
7580
7581           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
7582                                        &length);
7583           ui_file_delete (buf);
7584
7585           if (cu->language == language_cplus)
7586             {
7587               const char *cname
7588                 = dwarf2_canonicalize_name (name, cu,
7589                                             &objfile->objfile_obstack);
7590
7591               if (cname != NULL)
7592                 name = cname;
7593             }
7594         }
7595     }
7596
7597   return name;
7598 }
7599
7600 /* Return the fully qualified name of DIE, based on its DW_AT_name.
7601    If scope qualifiers are appropriate they will be added.  The result
7602    will be allocated on the objfile_obstack, or NULL if the DIE does
7603    not have a name.  NAME may either be from a previous call to
7604    dwarf2_name or NULL.
7605
7606    The output string will be canonicalized (if C++/Java).  */
7607
7608 static const char *
7609 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7610 {
7611   return dwarf2_compute_name (name, die, cu, 0);
7612 }
7613
7614 /* Construct a physname for the given DIE in CU.  NAME may either be
7615    from a previous call to dwarf2_name or NULL.  The result will be
7616    allocated on the objfile_objstack or NULL if the DIE does not have a
7617    name.
7618
7619    The output string will be canonicalized (if C++/Java).  */
7620
7621 static const char *
7622 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
7623 {
7624   struct objfile *objfile = cu->objfile;
7625   struct attribute *attr;
7626   const char *retval, *mangled = NULL, *canon = NULL;
7627   struct cleanup *back_to;
7628   int need_copy = 1;
7629
7630   /* In this case dwarf2_compute_name is just a shortcut not building anything
7631      on its own.  */
7632   if (!die_needs_namespace (die, cu))
7633     return dwarf2_compute_name (name, die, cu, 1);
7634
7635   back_to = make_cleanup (null_cleanup, NULL);
7636
7637   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
7638   if (!attr)
7639     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
7640
7641   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
7642      has computed.  */
7643   if (attr && DW_STRING (attr))
7644     {
7645       char *demangled;
7646
7647       mangled = DW_STRING (attr);
7648
7649       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
7650          type.  It is easier for GDB users to search for such functions as
7651          `name(params)' than `long name(params)'.  In such case the minimal
7652          symbol names do not match the full symbol names but for template
7653          functions there is never a need to look up their definition from their
7654          declaration so the only disadvantage remains the minimal symbol
7655          variant `long name(params)' does not have the proper inferior type.
7656          */
7657
7658       if (cu->language == language_go)
7659         {
7660           /* This is a lie, but we already lie to the caller new_symbol_full.
7661              new_symbol_full assumes we return the mangled name.
7662              This just undoes that lie until things are cleaned up.  */
7663           demangled = NULL;
7664         }
7665       else
7666         {
7667           demangled = cplus_demangle (mangled,
7668                                       (DMGL_PARAMS | DMGL_ANSI
7669                                        | (cu->language == language_java
7670                                           ? DMGL_JAVA | DMGL_RET_POSTFIX
7671                                           : DMGL_RET_DROP)));
7672         }
7673       if (demangled)
7674         {
7675           make_cleanup (xfree, demangled);
7676           canon = demangled;
7677         }
7678       else
7679         {
7680           canon = mangled;
7681           need_copy = 0;
7682         }
7683     }
7684
7685   if (canon == NULL || check_physname)
7686     {
7687       const char *physname = dwarf2_compute_name (name, die, cu, 1);
7688
7689       if (canon != NULL && strcmp (physname, canon) != 0)
7690         {
7691           /* It may not mean a bug in GDB.  The compiler could also
7692              compute DW_AT_linkage_name incorrectly.  But in such case
7693              GDB would need to be bug-to-bug compatible.  */
7694
7695           complaint (&symfile_complaints,
7696                      _("Computed physname <%s> does not match demangled <%s> "
7697                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
7698                      physname, canon, mangled, die->offset.sect_off, objfile->name);
7699
7700           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
7701              is available here - over computed PHYSNAME.  It is safer
7702              against both buggy GDB and buggy compilers.  */
7703
7704           retval = canon;
7705         }
7706       else
7707         {
7708           retval = physname;
7709           need_copy = 0;
7710         }
7711     }
7712   else
7713     retval = canon;
7714
7715   if (need_copy)
7716     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
7717
7718   do_cleanups (back_to);
7719   return retval;
7720 }
7721
7722 /* Read the import statement specified by the given die and record it.  */
7723
7724 static void
7725 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
7726 {
7727   struct objfile *objfile = cu->objfile;
7728   struct attribute *import_attr;
7729   struct die_info *imported_die, *child_die;
7730   struct dwarf2_cu *imported_cu;
7731   const char *imported_name;
7732   const char *imported_name_prefix;
7733   const char *canonical_name;
7734   const char *import_alias;
7735   const char *imported_declaration = NULL;
7736   const char *import_prefix;
7737   VEC (const_char_ptr) *excludes = NULL;
7738   struct cleanup *cleanups;
7739
7740   import_attr = dwarf2_attr (die, DW_AT_import, cu);
7741   if (import_attr == NULL)
7742     {
7743       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7744                  dwarf_tag_name (die->tag));
7745       return;
7746     }
7747
7748   imported_cu = cu;
7749   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
7750   imported_name = dwarf2_name (imported_die, imported_cu);
7751   if (imported_name == NULL)
7752     {
7753       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
7754
7755         The import in the following code:
7756         namespace A
7757           {
7758             typedef int B;
7759           }
7760
7761         int main ()
7762           {
7763             using A::B;
7764             B b;
7765             return b;
7766           }
7767
7768         ...
7769          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
7770             <52>   DW_AT_decl_file   : 1
7771             <53>   DW_AT_decl_line   : 6
7772             <54>   DW_AT_import      : <0x75>
7773          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
7774             <59>   DW_AT_name        : B
7775             <5b>   DW_AT_decl_file   : 1
7776             <5c>   DW_AT_decl_line   : 2
7777             <5d>   DW_AT_type        : <0x6e>
7778         ...
7779          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
7780             <76>   DW_AT_byte_size   : 4
7781             <77>   DW_AT_encoding    : 5        (signed)
7782
7783         imports the wrong die ( 0x75 instead of 0x58 ).
7784         This case will be ignored until the gcc bug is fixed.  */
7785       return;
7786     }
7787
7788   /* Figure out the local name after import.  */
7789   import_alias = dwarf2_name (die, cu);
7790
7791   /* Figure out where the statement is being imported to.  */
7792   import_prefix = determine_prefix (die, cu);
7793
7794   /* Figure out what the scope of the imported die is and prepend it
7795      to the name of the imported die.  */
7796   imported_name_prefix = determine_prefix (imported_die, imported_cu);
7797
7798   if (imported_die->tag != DW_TAG_namespace
7799       && imported_die->tag != DW_TAG_module)
7800     {
7801       imported_declaration = imported_name;
7802       canonical_name = imported_name_prefix;
7803     }
7804   else if (strlen (imported_name_prefix) > 0)
7805     canonical_name = obconcat (&objfile->objfile_obstack,
7806                                imported_name_prefix, "::", imported_name,
7807                                (char *) NULL);
7808   else
7809     canonical_name = imported_name;
7810
7811   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
7812
7813   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
7814     for (child_die = die->child; child_die && child_die->tag;
7815          child_die = sibling_die (child_die))
7816       {
7817         /* DWARF-4: A Fortran use statement with a “rename list” may be
7818            represented by an imported module entry with an import attribute
7819            referring to the module and owned entries corresponding to those
7820            entities that are renamed as part of being imported.  */
7821
7822         if (child_die->tag != DW_TAG_imported_declaration)
7823           {
7824             complaint (&symfile_complaints,
7825                        _("child DW_TAG_imported_declaration expected "
7826                          "- DIE at 0x%x [in module %s]"),
7827                        child_die->offset.sect_off, objfile->name);
7828             continue;
7829           }
7830
7831         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
7832         if (import_attr == NULL)
7833           {
7834             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
7835                        dwarf_tag_name (child_die->tag));
7836             continue;
7837           }
7838
7839         imported_cu = cu;
7840         imported_die = follow_die_ref_or_sig (child_die, import_attr,
7841                                               &imported_cu);
7842         imported_name = dwarf2_name (imported_die, imported_cu);
7843         if (imported_name == NULL)
7844           {
7845             complaint (&symfile_complaints,
7846                        _("child DW_TAG_imported_declaration has unknown "
7847                          "imported name - DIE at 0x%x [in module %s]"),
7848                        child_die->offset.sect_off, objfile->name);
7849             continue;
7850           }
7851
7852         VEC_safe_push (const_char_ptr, excludes, imported_name);
7853
7854         process_die (child_die, cu);
7855       }
7856
7857   cp_add_using_directive (import_prefix,
7858                           canonical_name,
7859                           import_alias,
7860                           imported_declaration,
7861                           excludes,
7862                           0,
7863                           &objfile->objfile_obstack);
7864
7865   do_cleanups (cleanups);
7866 }
7867
7868 /* Cleanup function for handle_DW_AT_stmt_list.  */
7869
7870 static void
7871 free_cu_line_header (void *arg)
7872 {
7873   struct dwarf2_cu *cu = arg;
7874
7875   free_line_header (cu->line_header);
7876   cu->line_header = NULL;
7877 }
7878
7879 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
7880    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
7881    this, it was first present in GCC release 4.3.0.  */
7882
7883 static int
7884 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
7885 {
7886   if (!cu->checked_producer)
7887     check_producer (cu);
7888
7889   return cu->producer_is_gcc_lt_4_3;
7890 }
7891
7892 static void
7893 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
7894                          const char **name, const char **comp_dir)
7895 {
7896   struct attribute *attr;
7897
7898   *name = NULL;
7899   *comp_dir = NULL;
7900
7901   /* Find the filename.  Do not use dwarf2_name here, since the filename
7902      is not a source language identifier.  */
7903   attr = dwarf2_attr (die, DW_AT_name, cu);
7904   if (attr)
7905     {
7906       *name = DW_STRING (attr);
7907     }
7908
7909   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
7910   if (attr)
7911     *comp_dir = DW_STRING (attr);
7912   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
7913            && IS_ABSOLUTE_PATH (*name))
7914     {
7915       char *d = ldirname (*name);
7916
7917       *comp_dir = d;
7918       if (d != NULL)
7919         make_cleanup (xfree, d);
7920     }
7921   if (*comp_dir != NULL)
7922     {
7923       /* Irix 6.2 native cc prepends <machine>.: to the compilation
7924          directory, get rid of it.  */
7925       char *cp = strchr (*comp_dir, ':');
7926
7927       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
7928         *comp_dir = cp + 1;
7929     }
7930
7931   if (*name == NULL)
7932     *name = "<unknown>";
7933 }
7934
7935 /* Handle DW_AT_stmt_list for a compilation unit.
7936    DIE is the DW_TAG_compile_unit die for CU.
7937    COMP_DIR is the compilation directory.
7938    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
7939
7940 static void
7941 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
7942                         const char *comp_dir)
7943 {
7944   struct attribute *attr;
7945
7946   gdb_assert (! cu->per_cu->is_debug_types);
7947
7948   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
7949   if (attr)
7950     {
7951       unsigned int line_offset = DW_UNSND (attr);
7952       struct line_header *line_header
7953         = dwarf_decode_line_header (line_offset, cu);
7954
7955       if (line_header)
7956         {
7957           cu->line_header = line_header;
7958           make_cleanup (free_cu_line_header, cu);
7959           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
7960         }
7961     }
7962 }
7963
7964 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
7965
7966 static void
7967 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
7968 {
7969   struct objfile *objfile = dwarf2_per_objfile->objfile;
7970   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
7971   CORE_ADDR lowpc = ((CORE_ADDR) -1);
7972   CORE_ADDR highpc = ((CORE_ADDR) 0);
7973   struct attribute *attr;
7974   const char *name = NULL;
7975   const char *comp_dir = NULL;
7976   struct die_info *child_die;
7977   bfd *abfd = objfile->obfd;
7978   CORE_ADDR baseaddr;
7979
7980   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7981
7982   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
7983
7984   /* If we didn't find a lowpc, set it to highpc to avoid complaints
7985      from finish_block.  */
7986   if (lowpc == ((CORE_ADDR) -1))
7987     lowpc = highpc;
7988   lowpc += baseaddr;
7989   highpc += baseaddr;
7990
7991   find_file_and_directory (die, cu, &name, &comp_dir);
7992
7993   prepare_one_comp_unit (cu, die, cu->language);
7994
7995   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
7996      standardised yet.  As a workaround for the language detection we fall
7997      back to the DW_AT_producer string.  */
7998   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
7999     cu->language = language_opencl;
8000
8001   /* Similar hack for Go.  */
8002   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8003     set_cu_language (DW_LANG_Go, cu);
8004
8005   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8006
8007   /* Decode line number information if present.  We do this before
8008      processing child DIEs, so that the line header table is available
8009      for DW_AT_decl_file.  */
8010   handle_DW_AT_stmt_list (die, cu, comp_dir);
8011
8012   /* Process all dies in compilation unit.  */
8013   if (die->child != NULL)
8014     {
8015       child_die = die->child;
8016       while (child_die && child_die->tag)
8017         {
8018           process_die (child_die, cu);
8019           child_die = sibling_die (child_die);
8020         }
8021     }
8022
8023   /* Decode macro information, if present.  Dwarf 2 macro information
8024      refers to information in the line number info statement program
8025      header, so we can only read it if we've read the header
8026      successfully.  */
8027   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8028   if (attr && cu->line_header)
8029     {
8030       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8031         complaint (&symfile_complaints,
8032                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8033
8034       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8035     }
8036   else
8037     {
8038       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8039       if (attr && cu->line_header)
8040         {
8041           unsigned int macro_offset = DW_UNSND (attr);
8042
8043           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8044         }
8045     }
8046
8047   do_cleanups (back_to);
8048 }
8049
8050 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8051    Create the set of symtabs used by this TU, or if this TU is sharing
8052    symtabs with another TU and the symtabs have already been created
8053    then restore those symtabs in the line header.
8054    We don't need the pc/line-number mapping for type units.  */
8055
8056 static void
8057 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8058 {
8059   struct objfile *objfile = dwarf2_per_objfile->objfile;
8060   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8061   struct type_unit_group *tu_group;
8062   int first_time;
8063   struct line_header *lh;
8064   struct attribute *attr;
8065   unsigned int i, line_offset;
8066
8067   gdb_assert (per_cu->is_debug_types);
8068
8069   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8070
8071   /* If we're using .gdb_index (includes -readnow) then
8072      per_cu->s.type_unit_group may not have been set up yet.  */
8073   if (per_cu->type_unit_group == NULL)
8074     per_cu->type_unit_group = get_type_unit_group (cu, attr);
8075   tu_group = per_cu->type_unit_group;
8076
8077   /* If we've already processed this stmt_list there's no real need to
8078      do it again, we could fake it and just recreate the part we need
8079      (file name,index -> symtab mapping).  If data shows this optimization
8080      is useful we can do it then.  */
8081   first_time = tu_group->primary_symtab == NULL;
8082
8083   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8084      debug info.  */
8085   lh = NULL;
8086   if (attr != NULL)
8087     {
8088       line_offset = DW_UNSND (attr);
8089       lh = dwarf_decode_line_header (line_offset, cu);
8090     }
8091   if (lh == NULL)
8092     {
8093       if (first_time)
8094         dwarf2_start_symtab (cu, "", NULL, 0);
8095       else
8096         {
8097           gdb_assert (tu_group->symtabs == NULL);
8098           restart_symtab (0);
8099         }
8100       /* Note: The primary symtab will get allocated at the end.  */
8101       return;
8102     }
8103
8104   cu->line_header = lh;
8105   make_cleanup (free_cu_line_header, cu);
8106
8107   if (first_time)
8108     {
8109       dwarf2_start_symtab (cu, "", NULL, 0);
8110
8111       tu_group->num_symtabs = lh->num_file_names;
8112       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8113
8114       for (i = 0; i < lh->num_file_names; ++i)
8115         {
8116           char *dir = NULL;
8117           struct file_entry *fe = &lh->file_names[i];
8118
8119           if (fe->dir_index)
8120             dir = lh->include_dirs[fe->dir_index - 1];
8121           dwarf2_start_subfile (fe->name, dir, NULL);
8122
8123           /* Note: We don't have to watch for the main subfile here, type units
8124              don't have DW_AT_name.  */
8125
8126           if (current_subfile->symtab == NULL)
8127             {
8128               /* NOTE: start_subfile will recognize when it's been passed
8129                  a file it has already seen.  So we can't assume there's a
8130                  simple mapping from lh->file_names to subfiles,
8131                  lh->file_names may contain dups.  */
8132               current_subfile->symtab = allocate_symtab (current_subfile->name,
8133                                                          objfile);
8134             }
8135
8136           fe->symtab = current_subfile->symtab;
8137           tu_group->symtabs[i] = fe->symtab;
8138         }
8139     }
8140   else
8141     {
8142       restart_symtab (0);
8143
8144       for (i = 0; i < lh->num_file_names; ++i)
8145         {
8146           struct file_entry *fe = &lh->file_names[i];
8147
8148           fe->symtab = tu_group->symtabs[i];
8149         }
8150     }
8151
8152   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8153      so they don't have a "real" (so to speak) symtab anyway.
8154      There is later code that will assign the main symtab to all symbols
8155      that don't have one.  We need to handle the case of a symbol with a
8156      missing symtab (DW_AT_decl_file) anyway.  */
8157 }
8158
8159 /* Process DW_TAG_type_unit.
8160    For TUs we want to skip the first top level sibling if it's not the
8161    actual type being defined by this TU.  In this case the first top
8162    level sibling is there to provide context only.  */
8163
8164 static void
8165 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8166 {
8167   struct die_info *child_die;
8168
8169   prepare_one_comp_unit (cu, die, language_minimal);
8170
8171   /* Initialize (or reinitialize) the machinery for building symtabs.
8172      We do this before processing child DIEs, so that the line header table
8173      is available for DW_AT_decl_file.  */
8174   setup_type_unit_groups (die, cu);
8175
8176   if (die->child != NULL)
8177     {
8178       child_die = die->child;
8179       while (child_die && child_die->tag)
8180         {
8181           process_die (child_die, cu);
8182           child_die = sibling_die (child_die);
8183         }
8184     }
8185 }
8186 \f
8187 /* DWO/DWP files.
8188
8189    http://gcc.gnu.org/wiki/DebugFission
8190    http://gcc.gnu.org/wiki/DebugFissionDWP
8191
8192    To simplify handling of both DWO files ("object" files with the DWARF info)
8193    and DWP files (a file with the DWOs packaged up into one file), we treat
8194    DWP files as having a collection of virtual DWO files.  */
8195
8196 static hashval_t
8197 hash_dwo_file (const void *item)
8198 {
8199   const struct dwo_file *dwo_file = item;
8200
8201   return htab_hash_string (dwo_file->name);
8202 }
8203
8204 static int
8205 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8206 {
8207   const struct dwo_file *lhs = item_lhs;
8208   const struct dwo_file *rhs = item_rhs;
8209
8210   return strcmp (lhs->name, rhs->name) == 0;
8211 }
8212
8213 /* Allocate a hash table for DWO files.  */
8214
8215 static htab_t
8216 allocate_dwo_file_hash_table (void)
8217 {
8218   struct objfile *objfile = dwarf2_per_objfile->objfile;
8219
8220   return htab_create_alloc_ex (41,
8221                                hash_dwo_file,
8222                                eq_dwo_file,
8223                                NULL,
8224                                &objfile->objfile_obstack,
8225                                hashtab_obstack_allocate,
8226                                dummy_obstack_deallocate);
8227 }
8228
8229 /* Lookup DWO file DWO_NAME.  */
8230
8231 static void **
8232 lookup_dwo_file_slot (const char *dwo_name)
8233 {
8234   struct dwo_file find_entry;
8235   void **slot;
8236
8237   if (dwarf2_per_objfile->dwo_files == NULL)
8238     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
8239
8240   memset (&find_entry, 0, sizeof (find_entry));
8241   find_entry.name = dwo_name;
8242   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
8243
8244   return slot;
8245 }
8246
8247 static hashval_t
8248 hash_dwo_unit (const void *item)
8249 {
8250   const struct dwo_unit *dwo_unit = item;
8251
8252   /* This drops the top 32 bits of the id, but is ok for a hash.  */
8253   return dwo_unit->signature;
8254 }
8255
8256 static int
8257 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
8258 {
8259   const struct dwo_unit *lhs = item_lhs;
8260   const struct dwo_unit *rhs = item_rhs;
8261
8262   /* The signature is assumed to be unique within the DWO file.
8263      So while object file CU dwo_id's always have the value zero,
8264      that's OK, assuming each object file DWO file has only one CU,
8265      and that's the rule for now.  */
8266   return lhs->signature == rhs->signature;
8267 }
8268
8269 /* Allocate a hash table for DWO CUs,TUs.
8270    There is one of these tables for each of CUs,TUs for each DWO file.  */
8271
8272 static htab_t
8273 allocate_dwo_unit_table (struct objfile *objfile)
8274 {
8275   /* Start out with a pretty small number.
8276      Generally DWO files contain only one CU and maybe some TUs.  */
8277   return htab_create_alloc_ex (3,
8278                                hash_dwo_unit,
8279                                eq_dwo_unit,
8280                                NULL,
8281                                &objfile->objfile_obstack,
8282                                hashtab_obstack_allocate,
8283                                dummy_obstack_deallocate);
8284 }
8285
8286 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
8287
8288 struct create_dwo_info_table_data
8289 {
8290   struct dwo_file *dwo_file;
8291   htab_t cu_htab;
8292 };
8293
8294 /* die_reader_func for create_dwo_debug_info_hash_table.  */
8295
8296 static void
8297 create_dwo_debug_info_hash_table_reader (const struct die_reader_specs *reader,
8298                                          gdb_byte *info_ptr,
8299                                          struct die_info *comp_unit_die,
8300                                          int has_children,
8301                                          void *datap)
8302 {
8303   struct dwarf2_cu *cu = reader->cu;
8304   struct objfile *objfile = dwarf2_per_objfile->objfile;
8305   sect_offset offset = cu->per_cu->offset;
8306   struct dwarf2_section_info *section = cu->per_cu->info_or_types_section;
8307   struct create_dwo_info_table_data *data = datap;
8308   struct dwo_file *dwo_file = data->dwo_file;
8309   htab_t cu_htab = data->cu_htab;
8310   void **slot;
8311   struct attribute *attr;
8312   struct dwo_unit *dwo_unit;
8313
8314   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
8315   if (attr == NULL)
8316     {
8317       error (_("Dwarf Error: debug entry at offset 0x%x is missing"
8318                " its dwo_id [in module %s]"),
8319              offset.sect_off, dwo_file->name);
8320       return;
8321     }
8322
8323   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8324   dwo_unit->dwo_file = dwo_file;
8325   dwo_unit->signature = DW_UNSND (attr);
8326   dwo_unit->info_or_types_section = section;
8327   dwo_unit->offset = offset;
8328   dwo_unit->length = cu->per_cu->length;
8329
8330   slot = htab_find_slot (cu_htab, dwo_unit, INSERT);
8331   gdb_assert (slot != NULL);
8332   if (*slot != NULL)
8333     {
8334       const struct dwo_unit *dup_dwo_unit = *slot;
8335
8336       complaint (&symfile_complaints,
8337                  _("debug entry at offset 0x%x is duplicate to the entry at"
8338                    " offset 0x%x, dwo_id 0x%s [in module %s]"),
8339                  offset.sect_off, dup_dwo_unit->offset.sect_off,
8340                  phex (dwo_unit->signature, sizeof (dwo_unit->signature)),
8341                  dwo_file->name);
8342     }
8343   else
8344     *slot = dwo_unit;
8345
8346   if (dwarf2_read_debug)
8347     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id 0x%s\n",
8348                         offset.sect_off,
8349                         phex (dwo_unit->signature,
8350                               sizeof (dwo_unit->signature)));
8351 }
8352
8353 /* Create a hash table to map DWO IDs to their CU entry in
8354    .debug_info.dwo in DWO_FILE.
8355    Note: This function processes DWO files only, not DWP files.  */
8356
8357 static htab_t
8358 create_dwo_debug_info_hash_table (struct dwo_file *dwo_file)
8359 {
8360   struct objfile *objfile = dwarf2_per_objfile->objfile;
8361   struct dwarf2_section_info *section = &dwo_file->sections.info;
8362   bfd *abfd;
8363   htab_t cu_htab;
8364   gdb_byte *info_ptr, *end_ptr;
8365   struct create_dwo_info_table_data create_dwo_info_table_data;
8366
8367   dwarf2_read_section (objfile, section);
8368   info_ptr = section->buffer;
8369
8370   if (info_ptr == NULL)
8371     return NULL;
8372
8373   /* We can't set abfd until now because the section may be empty or
8374      not present, in which case section->asection will be NULL.  */
8375   abfd = section->asection->owner;
8376
8377   if (dwarf2_read_debug)
8378     fprintf_unfiltered (gdb_stdlog, "Reading .debug_info.dwo for %s:\n",
8379                         bfd_get_filename (abfd));
8380
8381   cu_htab = allocate_dwo_unit_table (objfile);
8382
8383   create_dwo_info_table_data.dwo_file = dwo_file;
8384   create_dwo_info_table_data.cu_htab = cu_htab;
8385
8386   end_ptr = info_ptr + section->size;
8387   while (info_ptr < end_ptr)
8388     {
8389       struct dwarf2_per_cu_data per_cu;
8390
8391       memset (&per_cu, 0, sizeof (per_cu));
8392       per_cu.objfile = objfile;
8393       per_cu.is_debug_types = 0;
8394       per_cu.offset.sect_off = info_ptr - section->buffer;
8395       per_cu.info_or_types_section = section;
8396
8397       init_cutu_and_read_dies_no_follow (&per_cu,
8398                                          &dwo_file->sections.abbrev,
8399                                          dwo_file,
8400                                          create_dwo_debug_info_hash_table_reader,
8401                                          &create_dwo_info_table_data);
8402
8403       info_ptr += per_cu.length;
8404     }
8405
8406   return cu_htab;
8407 }
8408
8409 /* DWP file .debug_{cu,tu}_index section format:
8410    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
8411
8412    Both index sections have the same format, and serve to map a 64-bit
8413    signature to a set of section numbers.  Each section begins with a header,
8414    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
8415    indexes, and a pool of 32-bit section numbers.  The index sections will be
8416    aligned at 8-byte boundaries in the file.
8417
8418    The index section header contains two unsigned 32-bit values (using the
8419    byte order of the application binary):
8420
8421     N, the number of compilation units or type units in the index
8422     M, the number of slots in the hash table
8423
8424   (We assume that N and M will not exceed 2^32 - 1.)
8425
8426   The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
8427
8428   The hash table begins at offset 8 in the section, and consists of an array
8429   of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
8430   order of the application binary).  Unused slots in the hash table are 0.
8431   (We rely on the extreme unlikeliness of a signature being exactly 0.)
8432
8433   The parallel table begins immediately after the hash table
8434   (at offset 8 + 8 * M from the beginning of the section), and consists of an
8435   array of 32-bit indexes (using the byte order of the application binary),
8436   corresponding 1-1 with slots in the hash table.  Each entry in the parallel
8437   table contains a 32-bit index into the pool of section numbers.  For unused
8438   hash table slots, the corresponding entry in the parallel table will be 0.
8439
8440   Given a 64-bit compilation unit signature or a type signature S, an entry
8441   in the hash table is located as follows:
8442
8443   1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
8444      the low-order k bits all set to 1.
8445
8446   2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
8447
8448   3) If the hash table entry at index H matches the signature, use that
8449      entry.  If the hash table entry at index H is unused (all zeroes),
8450      terminate the search: the signature is not present in the table.
8451
8452   4) Let H = (H + H') modulo M. Repeat at Step 3.
8453
8454   Because M > N and H' and M are relatively prime, the search is guaranteed
8455   to stop at an unused slot or find the match.
8456
8457   The pool of section numbers begins immediately following the hash table
8458   (at offset 8 + 12 * M from the beginning of the section).  The pool of
8459   section numbers consists of an array of 32-bit words (using the byte order
8460   of the application binary).  Each item in the array is indexed starting
8461   from 0.  The hash table entry provides the index of the first section
8462   number in the set.  Additional section numbers in the set follow, and the
8463   set is terminated by a 0 entry (section number 0 is not used in ELF).
8464
8465   In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
8466   section must be the first entry in the set, and the .debug_abbrev.dwo must
8467   be the second entry. Other members of the set may follow in any order.  */
8468
8469 /* Create a hash table to map DWO IDs to their CU/TU entry in
8470    .debug_{info,types}.dwo in DWP_FILE.
8471    Returns NULL if there isn't one.
8472    Note: This function processes DWP files only, not DWO files.  */
8473
8474 static struct dwp_hash_table *
8475 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
8476 {
8477   struct objfile *objfile = dwarf2_per_objfile->objfile;
8478   bfd *dbfd = dwp_file->dbfd;
8479   char *index_ptr, *index_end;
8480   struct dwarf2_section_info *index;
8481   uint32_t version, nr_units, nr_slots;
8482   struct dwp_hash_table *htab;
8483
8484   if (is_debug_types)
8485     index = &dwp_file->sections.tu_index;
8486   else
8487     index = &dwp_file->sections.cu_index;
8488
8489   if (dwarf2_section_empty_p (index))
8490     return NULL;
8491   dwarf2_read_section (objfile, index);
8492
8493   index_ptr = index->buffer;
8494   index_end = index_ptr + index->size;
8495
8496   version = read_4_bytes (dbfd, index_ptr);
8497   index_ptr += 8; /* Skip the unused word.  */
8498   nr_units = read_4_bytes (dbfd, index_ptr);
8499   index_ptr += 4;
8500   nr_slots = read_4_bytes (dbfd, index_ptr);
8501   index_ptr += 4;
8502
8503   if (version != 1)
8504     {
8505       error (_("Dwarf Error: unsupported DWP file version (%u)"
8506                " [in module %s]"),
8507              version, dwp_file->name);
8508     }
8509   if (nr_slots != (nr_slots & -nr_slots))
8510     {
8511       error (_("Dwarf Error: number of slots in DWP hash table (%u)"
8512                " is not power of 2 [in module %s]"),
8513              nr_slots, dwp_file->name);
8514     }
8515
8516   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
8517   htab->nr_units = nr_units;
8518   htab->nr_slots = nr_slots;
8519   htab->hash_table = index_ptr;
8520   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
8521   htab->section_pool = htab->unit_table + sizeof (uint32_t) * nr_slots;
8522
8523   return htab;
8524 }
8525
8526 /* Update SECTIONS with the data from SECTP.
8527
8528    This function is like the other "locate" section routines that are
8529    passed to bfd_map_over_sections, but in this context the sections to
8530    read comes from the DWP hash table, not the full ELF section table.
8531
8532    The result is non-zero for success, or zero if an error was found.  */
8533
8534 static int
8535 locate_virtual_dwo_sections (asection *sectp,
8536                              struct virtual_dwo_sections *sections)
8537 {
8538   const struct dwop_section_names *names = &dwop_section_names;
8539
8540   if (section_is_p (sectp->name, &names->abbrev_dwo))
8541     {
8542       /* There can be only one.  */
8543       if (sections->abbrev.asection != NULL)
8544         return 0;
8545       sections->abbrev.asection = sectp;
8546       sections->abbrev.size = bfd_get_section_size (sectp);
8547     }
8548   else if (section_is_p (sectp->name, &names->info_dwo)
8549            || section_is_p (sectp->name, &names->types_dwo))
8550     {
8551       /* There can be only one.  */
8552       if (sections->info_or_types.asection != NULL)
8553         return 0;
8554       sections->info_or_types.asection = sectp;
8555       sections->info_or_types.size = bfd_get_section_size (sectp);
8556     }
8557   else if (section_is_p (sectp->name, &names->line_dwo))
8558     {
8559       /* There can be only one.  */
8560       if (sections->line.asection != NULL)
8561         return 0;
8562       sections->line.asection = sectp;
8563       sections->line.size = bfd_get_section_size (sectp);
8564     }
8565   else if (section_is_p (sectp->name, &names->loc_dwo))
8566     {
8567       /* There can be only one.  */
8568       if (sections->loc.asection != NULL)
8569         return 0;
8570       sections->loc.asection = sectp;
8571       sections->loc.size = bfd_get_section_size (sectp);
8572     }
8573   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8574     {
8575       /* There can be only one.  */
8576       if (sections->macinfo.asection != NULL)
8577         return 0;
8578       sections->macinfo.asection = sectp;
8579       sections->macinfo.size = bfd_get_section_size (sectp);
8580     }
8581   else if (section_is_p (sectp->name, &names->macro_dwo))
8582     {
8583       /* There can be only one.  */
8584       if (sections->macro.asection != NULL)
8585         return 0;
8586       sections->macro.asection = sectp;
8587       sections->macro.size = bfd_get_section_size (sectp);
8588     }
8589   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8590     {
8591       /* There can be only one.  */
8592       if (sections->str_offsets.asection != NULL)
8593         return 0;
8594       sections->str_offsets.asection = sectp;
8595       sections->str_offsets.size = bfd_get_section_size (sectp);
8596     }
8597   else
8598     {
8599       /* No other kind of section is valid.  */
8600       return 0;
8601     }
8602
8603   return 1;
8604 }
8605
8606 /* Create a dwo_unit object for the DWO with signature SIGNATURE.
8607    HTAB is the hash table from the DWP file.
8608    SECTION_INDEX is the index of the DWO in HTAB.  */
8609
8610 static struct dwo_unit *
8611 create_dwo_in_dwp (struct dwp_file *dwp_file,
8612                    const struct dwp_hash_table *htab,
8613                    uint32_t section_index,
8614                    ULONGEST signature, int is_debug_types)
8615 {
8616   struct objfile *objfile = dwarf2_per_objfile->objfile;
8617   bfd *dbfd = dwp_file->dbfd;
8618   const char *kind = is_debug_types ? "TU" : "CU";
8619   struct dwo_file *dwo_file;
8620   struct dwo_unit *dwo_unit;
8621   struct virtual_dwo_sections sections;
8622   void **dwo_file_slot;
8623   char *virtual_dwo_name;
8624   struct dwarf2_section_info *cutu;
8625   struct cleanup *cleanups;
8626   int i;
8627
8628   if (dwarf2_read_debug)
8629     {
8630       fprintf_unfiltered (gdb_stdlog, "Reading %s %u/0x%s in DWP file: %s\n",
8631                           kind,
8632                           section_index, phex (signature, sizeof (signature)),
8633                           dwp_file->name);
8634     }
8635
8636   /* Fetch the sections of this DWO.
8637      Put a limit on the number of sections we look for so that bad data
8638      doesn't cause us to loop forever.  */
8639
8640 #define MAX_NR_DWO_SECTIONS \
8641   (1 /* .debug_info or .debug_types */ \
8642    + 1 /* .debug_abbrev */ \
8643    + 1 /* .debug_line */ \
8644    + 1 /* .debug_loc */ \
8645    + 1 /* .debug_str_offsets */ \
8646    + 1 /* .debug_macro */ \
8647    + 1 /* .debug_macinfo */ \
8648    + 1 /* trailing zero */)
8649
8650   memset (&sections, 0, sizeof (sections));
8651   cleanups = make_cleanup (null_cleanup, 0);
8652
8653   for (i = 0; i < MAX_NR_DWO_SECTIONS; ++i)
8654     {
8655       asection *sectp;
8656       uint32_t section_nr =
8657         read_4_bytes (dbfd,
8658                       htab->section_pool
8659                       + (section_index + i) * sizeof (uint32_t));
8660
8661       if (section_nr == 0)
8662         break;
8663       if (section_nr >= dwp_file->num_sections)
8664         {
8665           error (_("Dwarf Error: bad DWP hash table, section number too large"
8666                    " [in module %s]"),
8667                  dwp_file->name);
8668         }
8669
8670       sectp = dwp_file->elf_sections[section_nr];
8671       if (! locate_virtual_dwo_sections (sectp, &sections))
8672         {
8673           error (_("Dwarf Error: bad DWP hash table, invalid section found"
8674                    " [in module %s]"),
8675                  dwp_file->name);
8676         }
8677     }
8678
8679   if (i < 2
8680       || sections.info_or_types.asection == NULL
8681       || sections.abbrev.asection == NULL)
8682     {
8683       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
8684                " [in module %s]"),
8685              dwp_file->name);
8686     }
8687   if (i == MAX_NR_DWO_SECTIONS)
8688     {
8689       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
8690                " [in module %s]"),
8691              dwp_file->name);
8692     }
8693
8694   /* It's easier for the rest of the code if we fake a struct dwo_file and
8695      have dwo_unit "live" in that.  At least for now.
8696
8697      The DWP file can be made up of a random collection of CUs and TUs.
8698      However, for each CU + set of TUs that came from the same original DWO
8699      file, we want to combine them back into a virtual DWO file to save space
8700      (fewer struct dwo_file objects to allocated).  Remember that for really
8701      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
8702
8703   virtual_dwo_name =
8704     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
8705                 sections.abbrev.asection ? sections.abbrev.asection->id : 0,
8706                 sections.line.asection ? sections.line.asection->id : 0,
8707                 sections.loc.asection ? sections.loc.asection->id : 0,
8708                 (sections.str_offsets.asection
8709                 ? sections.str_offsets.asection->id
8710                 : 0));
8711   make_cleanup (xfree, virtual_dwo_name);
8712   /* Can we use an existing virtual DWO file?  */
8713   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name);
8714   /* Create one if necessary.  */
8715   if (*dwo_file_slot == NULL)
8716     {
8717       if (dwarf2_read_debug)
8718         {
8719           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
8720                               virtual_dwo_name);
8721         }
8722       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8723       dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8724                                       virtual_dwo_name,
8725                                       strlen (virtual_dwo_name));
8726       dwo_file->sections.abbrev = sections.abbrev;
8727       dwo_file->sections.line = sections.line;
8728       dwo_file->sections.loc = sections.loc;
8729       dwo_file->sections.macinfo = sections.macinfo;
8730       dwo_file->sections.macro = sections.macro;
8731       dwo_file->sections.str_offsets = sections.str_offsets;
8732       /* The "str" section is global to the entire DWP file.  */
8733       dwo_file->sections.str = dwp_file->sections.str;
8734       /* The info or types section is assigned later to dwo_unit,
8735          there's no need to record it in dwo_file.
8736          Also, we can't simply record type sections in dwo_file because
8737          we record a pointer into the vector in dwo_unit.  As we collect more
8738          types we'll grow the vector and eventually have to reallocate space
8739          for it, invalidating all the pointers into the current copy.  */
8740       *dwo_file_slot = dwo_file;
8741     }
8742   else
8743     {
8744       if (dwarf2_read_debug)
8745         {
8746           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
8747                               virtual_dwo_name);
8748         }
8749       dwo_file = *dwo_file_slot;
8750     }
8751   do_cleanups (cleanups);
8752
8753   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
8754   dwo_unit->dwo_file = dwo_file;
8755   dwo_unit->signature = signature;
8756   dwo_unit->info_or_types_section =
8757     obstack_alloc (&objfile->objfile_obstack,
8758                    sizeof (struct dwarf2_section_info));
8759   *dwo_unit->info_or_types_section = sections.info_or_types;
8760   /* offset, length, type_offset_in_tu are set later.  */
8761
8762   return dwo_unit;
8763 }
8764
8765 /* Lookup the DWO with SIGNATURE in DWP_FILE.  */
8766
8767 static struct dwo_unit *
8768 lookup_dwo_in_dwp (struct dwp_file *dwp_file,
8769                    const struct dwp_hash_table *htab,
8770                    ULONGEST signature, int is_debug_types)
8771 {
8772   bfd *dbfd = dwp_file->dbfd;
8773   uint32_t mask = htab->nr_slots - 1;
8774   uint32_t hash = signature & mask;
8775   uint32_t hash2 = ((signature >> 32) & mask) | 1;
8776   unsigned int i;
8777   void **slot;
8778   struct dwo_unit find_dwo_cu, *dwo_cu;
8779
8780   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
8781   find_dwo_cu.signature = signature;
8782   slot = htab_find_slot (dwp_file->loaded_cutus, &find_dwo_cu, INSERT);
8783
8784   if (*slot != NULL)
8785     return *slot;
8786
8787   /* Use a for loop so that we don't loop forever on bad debug info.  */
8788   for (i = 0; i < htab->nr_slots; ++i)
8789     {
8790       ULONGEST signature_in_table;
8791
8792       signature_in_table =
8793         read_8_bytes (dbfd, htab->hash_table + hash * sizeof (uint64_t));
8794       if (signature_in_table == signature)
8795         {
8796           uint32_t section_index =
8797             read_4_bytes (dbfd, htab->unit_table + hash * sizeof (uint32_t));
8798
8799           *slot = create_dwo_in_dwp (dwp_file, htab, section_index,
8800                                      signature, is_debug_types);
8801           return *slot;
8802         }
8803       if (signature_in_table == 0)
8804         return NULL;
8805       hash = (hash + hash2) & mask;
8806     }
8807
8808   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
8809            " [in module %s]"),
8810          dwp_file->name);
8811 }
8812
8813 /* Subroutine of open_dwop_file to simplify it.
8814    Open the file specified by FILE_NAME and hand it off to BFD for
8815    preliminary analysis.  Return a newly initialized bfd *, which
8816    includes a canonicalized copy of FILE_NAME.
8817    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8818    In case of trouble, return NULL.
8819    NOTE: This function is derived from symfile_bfd_open.  */
8820
8821 static bfd *
8822 try_open_dwop_file (const char *file_name, int is_dwp)
8823 {
8824   bfd *sym_bfd;
8825   int desc, flags;
8826   char *absolute_name;
8827
8828   flags = OPF_TRY_CWD_FIRST;
8829   if (is_dwp)
8830     flags |= OPF_SEARCH_IN_PATH;
8831   desc = openp (debug_file_directory, flags, file_name,
8832                 O_RDONLY | O_BINARY, &absolute_name);
8833   if (desc < 0)
8834     return NULL;
8835
8836   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
8837   if (!sym_bfd)
8838     {
8839       xfree (absolute_name);
8840       return NULL;
8841     }
8842   xfree (absolute_name);
8843   bfd_set_cacheable (sym_bfd, 1);
8844
8845   if (!bfd_check_format (sym_bfd, bfd_object))
8846     {
8847       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
8848       return NULL;
8849     }
8850
8851   return sym_bfd;
8852 }
8853
8854 /* Try to open DWO/DWP file FILE_NAME.
8855    COMP_DIR is the DW_AT_comp_dir attribute.
8856    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
8857    The result is the bfd handle of the file.
8858    If there is a problem finding or opening the file, return NULL.
8859    Upon success, the canonicalized path of the file is stored in the bfd,
8860    same as symfile_bfd_open.  */
8861
8862 static bfd *
8863 open_dwop_file (const char *file_name, const char *comp_dir, int is_dwp)
8864 {
8865   bfd *abfd;
8866
8867   if (IS_ABSOLUTE_PATH (file_name))
8868     return try_open_dwop_file (file_name, is_dwp);
8869
8870   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
8871
8872   if (comp_dir != NULL)
8873     {
8874       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
8875
8876       /* NOTE: If comp_dir is a relative path, this will also try the
8877          search path, which seems useful.  */
8878       abfd = try_open_dwop_file (path_to_try, is_dwp);
8879       xfree (path_to_try);
8880       if (abfd != NULL)
8881         return abfd;
8882     }
8883
8884   /* That didn't work, try debug-file-directory, which, despite its name,
8885      is a list of paths.  */
8886
8887   if (*debug_file_directory == '\0')
8888     return NULL;
8889
8890   return try_open_dwop_file (file_name, is_dwp);
8891 }
8892
8893 /* This function is mapped across the sections and remembers the offset and
8894    size of each of the DWO debugging sections we are interested in.  */
8895
8896 static void
8897 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
8898 {
8899   struct dwo_sections *dwo_sections = dwo_sections_ptr;
8900   const struct dwop_section_names *names = &dwop_section_names;
8901
8902   if (section_is_p (sectp->name, &names->abbrev_dwo))
8903     {
8904       dwo_sections->abbrev.asection = sectp;
8905       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
8906     }
8907   else if (section_is_p (sectp->name, &names->info_dwo))
8908     {
8909       dwo_sections->info.asection = sectp;
8910       dwo_sections->info.size = bfd_get_section_size (sectp);
8911     }
8912   else if (section_is_p (sectp->name, &names->line_dwo))
8913     {
8914       dwo_sections->line.asection = sectp;
8915       dwo_sections->line.size = bfd_get_section_size (sectp);
8916     }
8917   else if (section_is_p (sectp->name, &names->loc_dwo))
8918     {
8919       dwo_sections->loc.asection = sectp;
8920       dwo_sections->loc.size = bfd_get_section_size (sectp);
8921     }
8922   else if (section_is_p (sectp->name, &names->macinfo_dwo))
8923     {
8924       dwo_sections->macinfo.asection = sectp;
8925       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
8926     }
8927   else if (section_is_p (sectp->name, &names->macro_dwo))
8928     {
8929       dwo_sections->macro.asection = sectp;
8930       dwo_sections->macro.size = bfd_get_section_size (sectp);
8931     }
8932   else if (section_is_p (sectp->name, &names->str_dwo))
8933     {
8934       dwo_sections->str.asection = sectp;
8935       dwo_sections->str.size = bfd_get_section_size (sectp);
8936     }
8937   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
8938     {
8939       dwo_sections->str_offsets.asection = sectp;
8940       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
8941     }
8942   else if (section_is_p (sectp->name, &names->types_dwo))
8943     {
8944       struct dwarf2_section_info type_section;
8945
8946       memset (&type_section, 0, sizeof (type_section));
8947       type_section.asection = sectp;
8948       type_section.size = bfd_get_section_size (sectp);
8949       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
8950                      &type_section);
8951     }
8952 }
8953
8954 /* Initialize the use of the DWO file specified by DWO_NAME.
8955    The result is NULL if DWO_NAME can't be found.  */
8956
8957 static struct dwo_file *
8958 open_and_init_dwo_file (const char *dwo_name, const char *comp_dir)
8959 {
8960   struct objfile *objfile = dwarf2_per_objfile->objfile;
8961   struct dwo_file *dwo_file;
8962   bfd *dbfd;
8963   struct cleanup *cleanups;
8964
8965   dbfd = open_dwop_file (dwo_name, comp_dir, 0);
8966   if (dbfd == NULL)
8967     {
8968       if (dwarf2_read_debug)
8969         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
8970       return NULL;
8971     }
8972   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
8973   dwo_file->name = obstack_copy0 (&objfile->objfile_obstack,
8974                                   dwo_name, strlen (dwo_name));
8975   dwo_file->dbfd = dbfd;
8976
8977   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
8978
8979   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
8980
8981   dwo_file->cus = create_dwo_debug_info_hash_table (dwo_file);
8982
8983   dwo_file->tus = create_debug_types_hash_table (dwo_file,
8984                                                  dwo_file->sections.types);
8985
8986   discard_cleanups (cleanups);
8987
8988   if (dwarf2_read_debug)
8989     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
8990
8991   return dwo_file;
8992 }
8993
8994 /* This function is mapped across the sections and remembers the offset and
8995    size of each of the DWP debugging sections we are interested in.  */
8996
8997 static void
8998 dwarf2_locate_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
8999 {
9000   struct dwp_file *dwp_file = dwp_file_ptr;
9001   const struct dwop_section_names *names = &dwop_section_names;
9002   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
9003
9004   /* Record the ELF section number for later lookup: this is what the
9005      .debug_cu_index,.debug_tu_index tables use.  */
9006   gdb_assert (elf_section_nr < dwp_file->num_sections);
9007   dwp_file->elf_sections[elf_section_nr] = sectp;
9008
9009   /* Look for specific sections that we need.  */
9010   if (section_is_p (sectp->name, &names->str_dwo))
9011     {
9012       dwp_file->sections.str.asection = sectp;
9013       dwp_file->sections.str.size = bfd_get_section_size (sectp);
9014     }
9015   else if (section_is_p (sectp->name, &names->cu_index))
9016     {
9017       dwp_file->sections.cu_index.asection = sectp;
9018       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
9019     }
9020   else if (section_is_p (sectp->name, &names->tu_index))
9021     {
9022       dwp_file->sections.tu_index.asection = sectp;
9023       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
9024     }
9025 }
9026
9027 /* Hash function for dwp_file loaded CUs/TUs.  */
9028
9029 static hashval_t
9030 hash_dwp_loaded_cutus (const void *item)
9031 {
9032   const struct dwo_unit *dwo_unit = item;
9033
9034   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
9035   return dwo_unit->signature;
9036 }
9037
9038 /* Equality function for dwp_file loaded CUs/TUs.  */
9039
9040 static int
9041 eq_dwp_loaded_cutus (const void *a, const void *b)
9042 {
9043   const struct dwo_unit *dua = a;
9044   const struct dwo_unit *dub = b;
9045
9046   return dua->signature == dub->signature;
9047 }
9048
9049 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
9050
9051 static htab_t
9052 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
9053 {
9054   return htab_create_alloc_ex (3,
9055                                hash_dwp_loaded_cutus,
9056                                eq_dwp_loaded_cutus,
9057                                NULL,
9058                                &objfile->objfile_obstack,
9059                                hashtab_obstack_allocate,
9060                                dummy_obstack_deallocate);
9061 }
9062
9063 /* Initialize the use of the DWP file for the current objfile.
9064    By convention the name of the DWP file is ${objfile}.dwp.
9065    The result is NULL if it can't be found.  */
9066
9067 static struct dwp_file *
9068 open_and_init_dwp_file (const char *comp_dir)
9069 {
9070   struct objfile *objfile = dwarf2_per_objfile->objfile;
9071   struct dwp_file *dwp_file;
9072   char *dwp_name;
9073   bfd *dbfd;
9074   struct cleanup *cleanups;
9075
9076   dwp_name = xstrprintf ("%s.dwp", dwarf2_per_objfile->objfile->name);
9077   cleanups = make_cleanup (xfree, dwp_name);
9078
9079   dbfd = open_dwop_file (dwp_name, comp_dir, 1);
9080   if (dbfd == NULL)
9081     {
9082       if (dwarf2_read_debug)
9083         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
9084       do_cleanups (cleanups);
9085       return NULL;
9086     }
9087   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
9088   dwp_file->name = obstack_copy0 (&objfile->objfile_obstack,
9089                                   dwp_name, strlen (dwp_name));
9090   dwp_file->dbfd = dbfd;
9091   do_cleanups (cleanups);
9092
9093   cleanups = make_cleanup (free_dwo_file_cleanup, dwp_file);
9094
9095   /* +1: section 0 is unused */
9096   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
9097   dwp_file->elf_sections =
9098     OBSTACK_CALLOC (&objfile->objfile_obstack,
9099                     dwp_file->num_sections, asection *);
9100
9101   bfd_map_over_sections (dbfd, dwarf2_locate_dwp_sections, dwp_file);
9102
9103   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
9104
9105   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
9106
9107   dwp_file->loaded_cutus = allocate_dwp_loaded_cutus_table (objfile);
9108
9109   discard_cleanups (cleanups);
9110
9111   if (dwarf2_read_debug)
9112     {
9113       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
9114       fprintf_unfiltered (gdb_stdlog,
9115                           "    %u CUs, %u TUs\n",
9116                           dwp_file->cus ? dwp_file->cus->nr_units : 0,
9117                           dwp_file->tus ? dwp_file->tus->nr_units : 0);
9118     }
9119
9120   return dwp_file;
9121 }
9122
9123 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
9124    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
9125    or in the DWP file for the objfile, referenced by THIS_UNIT.
9126    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
9127    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
9128
9129    This is called, for example, when wanting to read a variable with a
9130    complex location.  Therefore we don't want to do file i/o for every call.
9131    Therefore we don't want to look for a DWO file on every call.
9132    Therefore we first see if we've already seen SIGNATURE in a DWP file,
9133    then we check if we've already seen DWO_NAME, and only THEN do we check
9134    for a DWO file.
9135
9136    The result is a pointer to the dwo_unit object or NULL if we didn't find it
9137    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
9138
9139 static struct dwo_unit *
9140 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
9141                  const char *dwo_name, const char *comp_dir,
9142                  ULONGEST signature, int is_debug_types)
9143 {
9144   struct objfile *objfile = dwarf2_per_objfile->objfile;
9145   const char *kind = is_debug_types ? "TU" : "CU";
9146   void **dwo_file_slot;
9147   struct dwo_file *dwo_file;
9148   struct dwp_file *dwp_file;
9149
9150   /* Have we already read SIGNATURE from a DWP file?  */
9151
9152   if (! dwarf2_per_objfile->dwp_checked)
9153     {
9154       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file (comp_dir);
9155       dwarf2_per_objfile->dwp_checked = 1;
9156     }
9157   dwp_file = dwarf2_per_objfile->dwp_file;
9158
9159   if (dwp_file != NULL)
9160     {
9161       const struct dwp_hash_table *dwp_htab =
9162         is_debug_types ? dwp_file->tus : dwp_file->cus;
9163
9164       if (dwp_htab != NULL)
9165         {
9166           struct dwo_unit *dwo_cutu =
9167             lookup_dwo_in_dwp (dwp_file, dwp_htab, signature, is_debug_types);
9168
9169           if (dwo_cutu != NULL)
9170             {
9171               if (dwarf2_read_debug)
9172                 {
9173                   fprintf_unfiltered (gdb_stdlog,
9174                                       "Virtual DWO %s %s found: @%s\n",
9175                                       kind, hex_string (signature),
9176                                       host_address_to_string (dwo_cutu));
9177                 }
9178               return dwo_cutu;
9179             }
9180         }
9181     }
9182
9183   /* Have we already seen DWO_NAME?  */
9184
9185   dwo_file_slot = lookup_dwo_file_slot (dwo_name);
9186   if (*dwo_file_slot == NULL)
9187     {
9188       /* Read in the file and build a table of the DWOs it contains.  */
9189       *dwo_file_slot = open_and_init_dwo_file (dwo_name, comp_dir);
9190     }
9191   /* NOTE: This will be NULL if unable to open the file.  */
9192   dwo_file = *dwo_file_slot;
9193
9194   if (dwo_file != NULL)
9195     {
9196       htab_t htab = is_debug_types ? dwo_file->tus : dwo_file->cus;
9197
9198       if (htab != NULL)
9199         {
9200           struct dwo_unit find_dwo_cutu, *dwo_cutu;
9201
9202           memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
9203           find_dwo_cutu.signature = signature;
9204           dwo_cutu = htab_find (htab, &find_dwo_cutu);
9205
9206           if (dwo_cutu != NULL)
9207             {
9208               if (dwarf2_read_debug)
9209                 {
9210                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
9211                                       kind, dwo_name, hex_string (signature),
9212                                       host_address_to_string (dwo_cutu));
9213                 }
9214               return dwo_cutu;
9215             }
9216         }
9217     }
9218
9219   /* We didn't find it.  This could mean a dwo_id mismatch, or
9220      someone deleted the DWO/DWP file, or the search path isn't set up
9221      correctly to find the file.  */
9222
9223   if (dwarf2_read_debug)
9224     {
9225       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
9226                           kind, dwo_name, hex_string (signature));
9227     }
9228
9229   complaint (&symfile_complaints,
9230              _("Could not find DWO CU referenced by CU at offset 0x%x"
9231                " [in module %s]"),
9232              this_unit->offset.sect_off, objfile->name);
9233   return NULL;
9234 }
9235
9236 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
9237    See lookup_dwo_cutu_unit for details.  */
9238
9239 static struct dwo_unit *
9240 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
9241                       const char *dwo_name, const char *comp_dir,
9242                       ULONGEST signature)
9243 {
9244   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
9245 }
9246
9247 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
9248    See lookup_dwo_cutu_unit for details.  */
9249
9250 static struct dwo_unit *
9251 lookup_dwo_type_unit (struct signatured_type *this_tu,
9252                       const char *dwo_name, const char *comp_dir)
9253 {
9254   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
9255 }
9256
9257 /* Free all resources associated with DWO_FILE.
9258    Close the DWO file and munmap the sections.
9259    All memory should be on the objfile obstack.  */
9260
9261 static void
9262 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
9263 {
9264   int ix;
9265   struct dwarf2_section_info *section;
9266
9267   gdb_bfd_unref (dwo_file->dbfd);
9268
9269   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
9270 }
9271
9272 /* Wrapper for free_dwo_file for use in cleanups.  */
9273
9274 static void
9275 free_dwo_file_cleanup (void *arg)
9276 {
9277   struct dwo_file *dwo_file = (struct dwo_file *) arg;
9278   struct objfile *objfile = dwarf2_per_objfile->objfile;
9279
9280   free_dwo_file (dwo_file, objfile);
9281 }
9282
9283 /* Traversal function for free_dwo_files.  */
9284
9285 static int
9286 free_dwo_file_from_slot (void **slot, void *info)
9287 {
9288   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
9289   struct objfile *objfile = (struct objfile *) info;
9290
9291   free_dwo_file (dwo_file, objfile);
9292
9293   return 1;
9294 }
9295
9296 /* Free all resources associated with DWO_FILES.  */
9297
9298 static void
9299 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
9300 {
9301   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
9302 }
9303 \f
9304 /* Read in various DIEs.  */
9305
9306 /* qsort helper for inherit_abstract_dies.  */
9307
9308 static int
9309 unsigned_int_compar (const void *ap, const void *bp)
9310 {
9311   unsigned int a = *(unsigned int *) ap;
9312   unsigned int b = *(unsigned int *) bp;
9313
9314   return (a > b) - (b > a);
9315 }
9316
9317 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
9318    Inherit only the children of the DW_AT_abstract_origin DIE not being
9319    already referenced by DW_AT_abstract_origin from the children of the
9320    current DIE.  */
9321
9322 static void
9323 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
9324 {
9325   struct die_info *child_die;
9326   unsigned die_children_count;
9327   /* CU offsets which were referenced by children of the current DIE.  */
9328   sect_offset *offsets;
9329   sect_offset *offsets_end, *offsetp;
9330   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
9331   struct die_info *origin_die;
9332   /* Iterator of the ORIGIN_DIE children.  */
9333   struct die_info *origin_child_die;
9334   struct cleanup *cleanups;
9335   struct attribute *attr;
9336   struct dwarf2_cu *origin_cu;
9337   struct pending **origin_previous_list_in_scope;
9338
9339   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9340   if (!attr)
9341     return;
9342
9343   /* Note that following die references may follow to a die in a
9344      different cu.  */
9345
9346   origin_cu = cu;
9347   origin_die = follow_die_ref (die, attr, &origin_cu);
9348
9349   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
9350      symbols in.  */
9351   origin_previous_list_in_scope = origin_cu->list_in_scope;
9352   origin_cu->list_in_scope = cu->list_in_scope;
9353
9354   if (die->tag != origin_die->tag
9355       && !(die->tag == DW_TAG_inlined_subroutine
9356            && origin_die->tag == DW_TAG_subprogram))
9357     complaint (&symfile_complaints,
9358                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
9359                die->offset.sect_off, origin_die->offset.sect_off);
9360
9361   child_die = die->child;
9362   die_children_count = 0;
9363   while (child_die && child_die->tag)
9364     {
9365       child_die = sibling_die (child_die);
9366       die_children_count++;
9367     }
9368   offsets = xmalloc (sizeof (*offsets) * die_children_count);
9369   cleanups = make_cleanup (xfree, offsets);
9370
9371   offsets_end = offsets;
9372   child_die = die->child;
9373   while (child_die && child_die->tag)
9374     {
9375       /* For each CHILD_DIE, find the corresponding child of
9376          ORIGIN_DIE.  If there is more than one layer of
9377          DW_AT_abstract_origin, follow them all; there shouldn't be,
9378          but GCC versions at least through 4.4 generate this (GCC PR
9379          40573).  */
9380       struct die_info *child_origin_die = child_die;
9381       struct dwarf2_cu *child_origin_cu = cu;
9382
9383       while (1)
9384         {
9385           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
9386                               child_origin_cu);
9387           if (attr == NULL)
9388             break;
9389           child_origin_die = follow_die_ref (child_origin_die, attr,
9390                                              &child_origin_cu);
9391         }
9392
9393       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
9394          counterpart may exist.  */
9395       if (child_origin_die != child_die)
9396         {
9397           if (child_die->tag != child_origin_die->tag
9398               && !(child_die->tag == DW_TAG_inlined_subroutine
9399                    && child_origin_die->tag == DW_TAG_subprogram))
9400             complaint (&symfile_complaints,
9401                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9402                          "different tags"), child_die->offset.sect_off,
9403                        child_origin_die->offset.sect_off);
9404           if (child_origin_die->parent != origin_die)
9405             complaint (&symfile_complaints,
9406                        _("Child DIE 0x%x and its abstract origin 0x%x have "
9407                          "different parents"), child_die->offset.sect_off,
9408                        child_origin_die->offset.sect_off);
9409           else
9410             *offsets_end++ = child_origin_die->offset;
9411         }
9412       child_die = sibling_die (child_die);
9413     }
9414   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
9415          unsigned_int_compar);
9416   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
9417     if (offsetp[-1].sect_off == offsetp->sect_off)
9418       complaint (&symfile_complaints,
9419                  _("Multiple children of DIE 0x%x refer "
9420                    "to DIE 0x%x as their abstract origin"),
9421                  die->offset.sect_off, offsetp->sect_off);
9422
9423   offsetp = offsets;
9424   origin_child_die = origin_die->child;
9425   while (origin_child_die && origin_child_die->tag)
9426     {
9427       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
9428       while (offsetp < offsets_end
9429              && offsetp->sect_off < origin_child_die->offset.sect_off)
9430         offsetp++;
9431       if (offsetp >= offsets_end
9432           || offsetp->sect_off > origin_child_die->offset.sect_off)
9433         {
9434           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
9435           process_die (origin_child_die, origin_cu);
9436         }
9437       origin_child_die = sibling_die (origin_child_die);
9438     }
9439   origin_cu->list_in_scope = origin_previous_list_in_scope;
9440
9441   do_cleanups (cleanups);
9442 }
9443
9444 static void
9445 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
9446 {
9447   struct objfile *objfile = cu->objfile;
9448   struct context_stack *new;
9449   CORE_ADDR lowpc;
9450   CORE_ADDR highpc;
9451   struct die_info *child_die;
9452   struct attribute *attr, *call_line, *call_file;
9453   const char *name;
9454   CORE_ADDR baseaddr;
9455   struct block *block;
9456   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
9457   VEC (symbolp) *template_args = NULL;
9458   struct template_symbol *templ_func = NULL;
9459
9460   if (inlined_func)
9461     {
9462       /* If we do not have call site information, we can't show the
9463          caller of this inlined function.  That's too confusing, so
9464          only use the scope for local variables.  */
9465       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
9466       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
9467       if (call_line == NULL || call_file == NULL)
9468         {
9469           read_lexical_block_scope (die, cu);
9470           return;
9471         }
9472     }
9473
9474   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9475
9476   name = dwarf2_name (die, cu);
9477
9478   /* Ignore functions with missing or empty names.  These are actually
9479      illegal according to the DWARF standard.  */
9480   if (name == NULL)
9481     {
9482       complaint (&symfile_complaints,
9483                  _("missing name for subprogram DIE at %d"),
9484                  die->offset.sect_off);
9485       return;
9486     }
9487
9488   /* Ignore functions with missing or invalid low and high pc attributes.  */
9489   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9490     {
9491       attr = dwarf2_attr (die, DW_AT_external, cu);
9492       if (!attr || !DW_UNSND (attr))
9493         complaint (&symfile_complaints,
9494                    _("cannot get low and high bounds "
9495                      "for subprogram DIE at %d"),
9496                    die->offset.sect_off);
9497       return;
9498     }
9499
9500   lowpc += baseaddr;
9501   highpc += baseaddr;
9502
9503   /* If we have any template arguments, then we must allocate a
9504      different sort of symbol.  */
9505   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
9506     {
9507       if (child_die->tag == DW_TAG_template_type_param
9508           || child_die->tag == DW_TAG_template_value_param)
9509         {
9510           templ_func = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9511                                        struct template_symbol);
9512           templ_func->base.is_cplus_template_function = 1;
9513           break;
9514         }
9515     }
9516
9517   new = push_context (0, lowpc);
9518   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
9519                                (struct symbol *) templ_func);
9520
9521   /* If there is a location expression for DW_AT_frame_base, record
9522      it.  */
9523   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
9524   if (attr)
9525     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
9526
9527   cu->list_in_scope = &local_symbols;
9528
9529   if (die->child != NULL)
9530     {
9531       child_die = die->child;
9532       while (child_die && child_die->tag)
9533         {
9534           if (child_die->tag == DW_TAG_template_type_param
9535               || child_die->tag == DW_TAG_template_value_param)
9536             {
9537               struct symbol *arg = new_symbol (child_die, NULL, cu);
9538
9539               if (arg != NULL)
9540                 VEC_safe_push (symbolp, template_args, arg);
9541             }
9542           else
9543             process_die (child_die, cu);
9544           child_die = sibling_die (child_die);
9545         }
9546     }
9547
9548   inherit_abstract_dies (die, cu);
9549
9550   /* If we have a DW_AT_specification, we might need to import using
9551      directives from the context of the specification DIE.  See the
9552      comment in determine_prefix.  */
9553   if (cu->language == language_cplus
9554       && dwarf2_attr (die, DW_AT_specification, cu))
9555     {
9556       struct dwarf2_cu *spec_cu = cu;
9557       struct die_info *spec_die = die_specification (die, &spec_cu);
9558
9559       while (spec_die)
9560         {
9561           child_die = spec_die->child;
9562           while (child_die && child_die->tag)
9563             {
9564               if (child_die->tag == DW_TAG_imported_module)
9565                 process_die (child_die, spec_cu);
9566               child_die = sibling_die (child_die);
9567             }
9568
9569           /* In some cases, GCC generates specification DIEs that
9570              themselves contain DW_AT_specification attributes.  */
9571           spec_die = die_specification (spec_die, &spec_cu);
9572         }
9573     }
9574
9575   new = pop_context ();
9576   /* Make a block for the local symbols within.  */
9577   block = finish_block (new->name, &local_symbols, new->old_blocks,
9578                         lowpc, highpc, objfile);
9579
9580   /* For C++, set the block's scope.  */
9581   if ((cu->language == language_cplus || cu->language == language_fortran)
9582       && cu->processing_has_namespace_info)
9583     block_set_scope (block, determine_prefix (die, cu),
9584                      &objfile->objfile_obstack);
9585
9586   /* If we have address ranges, record them.  */
9587   dwarf2_record_block_ranges (die, block, baseaddr, cu);
9588
9589   /* Attach template arguments to function.  */
9590   if (! VEC_empty (symbolp, template_args))
9591     {
9592       gdb_assert (templ_func != NULL);
9593
9594       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
9595       templ_func->template_arguments
9596         = obstack_alloc (&objfile->objfile_obstack,
9597                          (templ_func->n_template_arguments
9598                           * sizeof (struct symbol *)));
9599       memcpy (templ_func->template_arguments,
9600               VEC_address (symbolp, template_args),
9601               (templ_func->n_template_arguments * sizeof (struct symbol *)));
9602       VEC_free (symbolp, template_args);
9603     }
9604
9605   /* In C++, we can have functions nested inside functions (e.g., when
9606      a function declares a class that has methods).  This means that
9607      when we finish processing a function scope, we may need to go
9608      back to building a containing block's symbol lists.  */
9609   local_symbols = new->locals;
9610   using_directives = new->using_directives;
9611
9612   /* If we've finished processing a top-level function, subsequent
9613      symbols go in the file symbol list.  */
9614   if (outermost_context_p ())
9615     cu->list_in_scope = &file_symbols;
9616 }
9617
9618 /* Process all the DIES contained within a lexical block scope.  Start
9619    a new scope, process the dies, and then close the scope.  */
9620
9621 static void
9622 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
9623 {
9624   struct objfile *objfile = cu->objfile;
9625   struct context_stack *new;
9626   CORE_ADDR lowpc, highpc;
9627   struct die_info *child_die;
9628   CORE_ADDR baseaddr;
9629
9630   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9631
9632   /* Ignore blocks with missing or invalid low and high pc attributes.  */
9633   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
9634      as multiple lexical blocks?  Handling children in a sane way would
9635      be nasty.  Might be easier to properly extend generic blocks to
9636      describe ranges.  */
9637   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
9638     return;
9639   lowpc += baseaddr;
9640   highpc += baseaddr;
9641
9642   push_context (0, lowpc);
9643   if (die->child != NULL)
9644     {
9645       child_die = die->child;
9646       while (child_die && child_die->tag)
9647         {
9648           process_die (child_die, cu);
9649           child_die = sibling_die (child_die);
9650         }
9651     }
9652   new = pop_context ();
9653
9654   if (local_symbols != NULL || using_directives != NULL)
9655     {
9656       struct block *block
9657         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
9658                         highpc, objfile);
9659
9660       /* Note that recording ranges after traversing children, as we
9661          do here, means that recording a parent's ranges entails
9662          walking across all its children's ranges as they appear in
9663          the address map, which is quadratic behavior.
9664
9665          It would be nicer to record the parent's ranges before
9666          traversing its children, simply overriding whatever you find
9667          there.  But since we don't even decide whether to create a
9668          block until after we've traversed its children, that's hard
9669          to do.  */
9670       dwarf2_record_block_ranges (die, block, baseaddr, cu);
9671     }
9672   local_symbols = new->locals;
9673   using_directives = new->using_directives;
9674 }
9675
9676 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
9677
9678 static void
9679 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
9680 {
9681   struct objfile *objfile = cu->objfile;
9682   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9683   CORE_ADDR pc, baseaddr;
9684   struct attribute *attr;
9685   struct call_site *call_site, call_site_local;
9686   void **slot;
9687   int nparams;
9688   struct die_info *child_die;
9689
9690   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9691
9692   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
9693   if (!attr)
9694     {
9695       complaint (&symfile_complaints,
9696                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
9697                    "DIE 0x%x [in module %s]"),
9698                  die->offset.sect_off, objfile->name);
9699       return;
9700     }
9701   pc = DW_ADDR (attr) + baseaddr;
9702
9703   if (cu->call_site_htab == NULL)
9704     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
9705                                                NULL, &objfile->objfile_obstack,
9706                                                hashtab_obstack_allocate, NULL);
9707   call_site_local.pc = pc;
9708   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
9709   if (*slot != NULL)
9710     {
9711       complaint (&symfile_complaints,
9712                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
9713                    "DIE 0x%x [in module %s]"),
9714                  paddress (gdbarch, pc), die->offset.sect_off, objfile->name);
9715       return;
9716     }
9717
9718   /* Count parameters at the caller.  */
9719
9720   nparams = 0;
9721   for (child_die = die->child; child_die && child_die->tag;
9722        child_die = sibling_die (child_die))
9723     {
9724       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9725         {
9726           complaint (&symfile_complaints,
9727                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
9728                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9729                      child_die->tag, child_die->offset.sect_off, objfile->name);
9730           continue;
9731         }
9732
9733       nparams++;
9734     }
9735
9736   call_site = obstack_alloc (&objfile->objfile_obstack,
9737                              (sizeof (*call_site)
9738                               + (sizeof (*call_site->parameter)
9739                                  * (nparams - 1))));
9740   *slot = call_site;
9741   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
9742   call_site->pc = pc;
9743
9744   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
9745     {
9746       struct die_info *func_die;
9747
9748       /* Skip also over DW_TAG_inlined_subroutine.  */
9749       for (func_die = die->parent;
9750            func_die && func_die->tag != DW_TAG_subprogram
9751            && func_die->tag != DW_TAG_subroutine_type;
9752            func_die = func_die->parent);
9753
9754       /* DW_AT_GNU_all_call_sites is a superset
9755          of DW_AT_GNU_all_tail_call_sites.  */
9756       if (func_die
9757           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
9758           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
9759         {
9760           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
9761              not complete.  But keep CALL_SITE for look ups via call_site_htab,
9762              both the initial caller containing the real return address PC and
9763              the final callee containing the current PC of a chain of tail
9764              calls do not need to have the tail call list complete.  But any
9765              function candidate for a virtual tail call frame searched via
9766              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
9767              determined unambiguously.  */
9768         }
9769       else
9770         {
9771           struct type *func_type = NULL;
9772
9773           if (func_die)
9774             func_type = get_die_type (func_die, cu);
9775           if (func_type != NULL)
9776             {
9777               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
9778
9779               /* Enlist this call site to the function.  */
9780               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
9781               TYPE_TAIL_CALL_LIST (func_type) = call_site;
9782             }
9783           else
9784             complaint (&symfile_complaints,
9785                        _("Cannot find function owning DW_TAG_GNU_call_site "
9786                          "DIE 0x%x [in module %s]"),
9787                        die->offset.sect_off, objfile->name);
9788         }
9789     }
9790
9791   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
9792   if (attr == NULL)
9793     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
9794   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
9795   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
9796     /* Keep NULL DWARF_BLOCK.  */;
9797   else if (attr_form_is_block (attr))
9798     {
9799       struct dwarf2_locexpr_baton *dlbaton;
9800
9801       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
9802       dlbaton->data = DW_BLOCK (attr)->data;
9803       dlbaton->size = DW_BLOCK (attr)->size;
9804       dlbaton->per_cu = cu->per_cu;
9805
9806       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
9807     }
9808   else if (is_ref_attr (attr))
9809     {
9810       struct dwarf2_cu *target_cu = cu;
9811       struct die_info *target_die;
9812
9813       target_die = follow_die_ref_or_sig (die, attr, &target_cu);
9814       gdb_assert (target_cu->objfile == objfile);
9815       if (die_is_declaration (target_die, target_cu))
9816         {
9817           const char *target_physname = NULL;
9818           struct attribute *target_attr;
9819
9820           /* Prefer the mangled name; otherwise compute the demangled one.  */
9821           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
9822           if (target_attr == NULL)
9823             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
9824                                        target_cu);
9825           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
9826             target_physname = DW_STRING (target_attr);
9827           else
9828             target_physname = dwarf2_physname (NULL, target_die, target_cu);
9829           if (target_physname == NULL)
9830             complaint (&symfile_complaints,
9831                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9832                          "physname, for referencing DIE 0x%x [in module %s]"),
9833                        die->offset.sect_off, objfile->name);
9834           else
9835             SET_FIELD_PHYSNAME (call_site->target, target_physname);
9836         }
9837       else
9838         {
9839           CORE_ADDR lowpc;
9840
9841           /* DW_AT_entry_pc should be preferred.  */
9842           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
9843             complaint (&symfile_complaints,
9844                        _("DW_AT_GNU_call_site_target target DIE has invalid "
9845                          "low pc, for referencing DIE 0x%x [in module %s]"),
9846                        die->offset.sect_off, objfile->name);
9847           else
9848             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
9849         }
9850     }
9851   else
9852     complaint (&symfile_complaints,
9853                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
9854                  "block nor reference, for DIE 0x%x [in module %s]"),
9855                die->offset.sect_off, objfile->name);
9856
9857   call_site->per_cu = cu->per_cu;
9858
9859   for (child_die = die->child;
9860        child_die && child_die->tag;
9861        child_die = sibling_die (child_die))
9862     {
9863       struct call_site_parameter *parameter;
9864       struct attribute *loc, *origin;
9865
9866       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
9867         {
9868           /* Already printed the complaint above.  */
9869           continue;
9870         }
9871
9872       gdb_assert (call_site->parameter_count < nparams);
9873       parameter = &call_site->parameter[call_site->parameter_count];
9874
9875       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
9876          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
9877          register is contained in DW_AT_GNU_call_site_value.  */
9878
9879       loc = dwarf2_attr (child_die, DW_AT_location, cu);
9880       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
9881       if (loc == NULL && origin != NULL && is_ref_attr (origin))
9882         {
9883           sect_offset offset;
9884
9885           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
9886           offset = dwarf2_get_ref_die_offset (origin);
9887           if (!offset_in_cu_p (&cu->header, offset))
9888             {
9889               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
9890                  binding can be done only inside one CU.  Such referenced DIE
9891                  therefore cannot be even moved to DW_TAG_partial_unit.  */
9892               complaint (&symfile_complaints,
9893                          _("DW_AT_abstract_origin offset is not in CU for "
9894                            "DW_TAG_GNU_call_site child DIE 0x%x "
9895                            "[in module %s]"),
9896                          child_die->offset.sect_off, objfile->name);
9897               continue;
9898             }
9899           parameter->u.param_offset.cu_off = (offset.sect_off
9900                                               - cu->header.offset.sect_off);
9901         }
9902       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
9903         {
9904           complaint (&symfile_complaints,
9905                      _("No DW_FORM_block* DW_AT_location for "
9906                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9907                      child_die->offset.sect_off, objfile->name);
9908           continue;
9909         }
9910       else
9911         {
9912           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
9913             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
9914           if (parameter->u.dwarf_reg != -1)
9915             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
9916           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
9917                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
9918                                              &parameter->u.fb_offset))
9919             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
9920           else
9921             {
9922               complaint (&symfile_complaints,
9923                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
9924                            "for DW_FORM_block* DW_AT_location is supported for "
9925                            "DW_TAG_GNU_call_site child DIE 0x%x "
9926                            "[in module %s]"),
9927                          child_die->offset.sect_off, objfile->name);
9928               continue;
9929             }
9930         }
9931
9932       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
9933       if (!attr_form_is_block (attr))
9934         {
9935           complaint (&symfile_complaints,
9936                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
9937                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9938                      child_die->offset.sect_off, objfile->name);
9939           continue;
9940         }
9941       parameter->value = DW_BLOCK (attr)->data;
9942       parameter->value_size = DW_BLOCK (attr)->size;
9943
9944       /* Parameters are not pre-cleared by memset above.  */
9945       parameter->data_value = NULL;
9946       parameter->data_value_size = 0;
9947       call_site->parameter_count++;
9948
9949       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
9950       if (attr)
9951         {
9952           if (!attr_form_is_block (attr))
9953             complaint (&symfile_complaints,
9954                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
9955                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
9956                        child_die->offset.sect_off, objfile->name);
9957           else
9958             {
9959               parameter->data_value = DW_BLOCK (attr)->data;
9960               parameter->data_value_size = DW_BLOCK (attr)->size;
9961             }
9962         }
9963     }
9964 }
9965
9966 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
9967    Return 1 if the attributes are present and valid, otherwise, return 0.
9968    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
9969
9970 static int
9971 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
9972                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
9973                     struct partial_symtab *ranges_pst)
9974 {
9975   struct objfile *objfile = cu->objfile;
9976   struct comp_unit_head *cu_header = &cu->header;
9977   bfd *obfd = objfile->obfd;
9978   unsigned int addr_size = cu_header->addr_size;
9979   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
9980   /* Base address selection entry.  */
9981   CORE_ADDR base;
9982   int found_base;
9983   unsigned int dummy;
9984   gdb_byte *buffer;
9985   CORE_ADDR marker;
9986   int low_set;
9987   CORE_ADDR low = 0;
9988   CORE_ADDR high = 0;
9989   CORE_ADDR baseaddr;
9990
9991   found_base = cu->base_known;
9992   base = cu->base_address;
9993
9994   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
9995   if (offset >= dwarf2_per_objfile->ranges.size)
9996     {
9997       complaint (&symfile_complaints,
9998                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
9999                  offset);
10000       return 0;
10001     }
10002   buffer = dwarf2_per_objfile->ranges.buffer + offset;
10003
10004   /* Read in the largest possible address.  */
10005   marker = read_address (obfd, buffer, cu, &dummy);
10006   if ((marker & mask) == mask)
10007     {
10008       /* If we found the largest possible address, then
10009          read the base address.  */
10010       base = read_address (obfd, buffer + addr_size, cu, &dummy);
10011       buffer += 2 * addr_size;
10012       offset += 2 * addr_size;
10013       found_base = 1;
10014     }
10015
10016   low_set = 0;
10017
10018   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10019
10020   while (1)
10021     {
10022       CORE_ADDR range_beginning, range_end;
10023
10024       range_beginning = read_address (obfd, buffer, cu, &dummy);
10025       buffer += addr_size;
10026       range_end = read_address (obfd, buffer, cu, &dummy);
10027       buffer += addr_size;
10028       offset += 2 * addr_size;
10029
10030       /* An end of list marker is a pair of zero addresses.  */
10031       if (range_beginning == 0 && range_end == 0)
10032         /* Found the end of list entry.  */
10033         break;
10034
10035       /* Each base address selection entry is a pair of 2 values.
10036          The first is the largest possible address, the second is
10037          the base address.  Check for a base address here.  */
10038       if ((range_beginning & mask) == mask)
10039         {
10040           /* If we found the largest possible address, then
10041              read the base address.  */
10042           base = read_address (obfd, buffer + addr_size, cu, &dummy);
10043           found_base = 1;
10044           continue;
10045         }
10046
10047       if (!found_base)
10048         {
10049           /* We have no valid base address for the ranges
10050              data.  */
10051           complaint (&symfile_complaints,
10052                      _("Invalid .debug_ranges data (no base address)"));
10053           return 0;
10054         }
10055
10056       if (range_beginning > range_end)
10057         {
10058           /* Inverted range entries are invalid.  */
10059           complaint (&symfile_complaints,
10060                      _("Invalid .debug_ranges data (inverted range)"));
10061           return 0;
10062         }
10063
10064       /* Empty range entries have no effect.  */
10065       if (range_beginning == range_end)
10066         continue;
10067
10068       range_beginning += base;
10069       range_end += base;
10070
10071       /* A not-uncommon case of bad debug info.
10072          Don't pollute the addrmap with bad data.  */
10073       if (range_beginning + baseaddr == 0
10074           && !dwarf2_per_objfile->has_section_at_zero)
10075         {
10076           complaint (&symfile_complaints,
10077                      _(".debug_ranges entry has start address of zero"
10078                        " [in module %s]"), objfile->name);
10079           continue;
10080         }
10081
10082       if (ranges_pst != NULL)
10083         addrmap_set_empty (objfile->psymtabs_addrmap,
10084                            range_beginning + baseaddr,
10085                            range_end - 1 + baseaddr,
10086                            ranges_pst);
10087
10088       /* FIXME: This is recording everything as a low-high
10089          segment of consecutive addresses.  We should have a
10090          data structure for discontiguous block ranges
10091          instead.  */
10092       if (! low_set)
10093         {
10094           low = range_beginning;
10095           high = range_end;
10096           low_set = 1;
10097         }
10098       else
10099         {
10100           if (range_beginning < low)
10101             low = range_beginning;
10102           if (range_end > high)
10103             high = range_end;
10104         }
10105     }
10106
10107   if (! low_set)
10108     /* If the first entry is an end-of-list marker, the range
10109        describes an empty scope, i.e. no instructions.  */
10110     return 0;
10111
10112   if (low_return)
10113     *low_return = low;
10114   if (high_return)
10115     *high_return = high;
10116   return 1;
10117 }
10118
10119 /* Get low and high pc attributes from a die.  Return 1 if the attributes
10120    are present and valid, otherwise, return 0.  Return -1 if the range is
10121    discontinuous, i.e. derived from DW_AT_ranges information.  */
10122
10123 static int
10124 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
10125                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
10126                       struct partial_symtab *pst)
10127 {
10128   struct attribute *attr;
10129   struct attribute *attr_high;
10130   CORE_ADDR low = 0;
10131   CORE_ADDR high = 0;
10132   int ret = 0;
10133
10134   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10135   if (attr_high)
10136     {
10137       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10138       if (attr)
10139         {
10140           low = DW_ADDR (attr);
10141           if (attr_high->form == DW_FORM_addr
10142               || attr_high->form == DW_FORM_GNU_addr_index)
10143             high = DW_ADDR (attr_high);
10144           else
10145             high = low + DW_UNSND (attr_high);
10146         }
10147       else
10148         /* Found high w/o low attribute.  */
10149         return 0;
10150
10151       /* Found consecutive range of addresses.  */
10152       ret = 1;
10153     }
10154   else
10155     {
10156       attr = dwarf2_attr (die, DW_AT_ranges, cu);
10157       if (attr != NULL)
10158         {
10159           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10160              We take advantage of the fact that DW_AT_ranges does not appear
10161              in DW_TAG_compile_unit of DWO files.  */
10162           int need_ranges_base = die->tag != DW_TAG_compile_unit;
10163           unsigned int ranges_offset = (DW_UNSND (attr)
10164                                         + (need_ranges_base
10165                                            ? cu->ranges_base
10166                                            : 0));
10167
10168           /* Value of the DW_AT_ranges attribute is the offset in the
10169              .debug_ranges section.  */
10170           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
10171             return 0;
10172           /* Found discontinuous range of addresses.  */
10173           ret = -1;
10174         }
10175     }
10176
10177   /* read_partial_die has also the strict LOW < HIGH requirement.  */
10178   if (high <= low)
10179     return 0;
10180
10181   /* When using the GNU linker, .gnu.linkonce. sections are used to
10182      eliminate duplicate copies of functions and vtables and such.
10183      The linker will arbitrarily choose one and discard the others.
10184      The AT_*_pc values for such functions refer to local labels in
10185      these sections.  If the section from that file was discarded, the
10186      labels are not in the output, so the relocs get a value of 0.
10187      If this is a discarded function, mark the pc bounds as invalid,
10188      so that GDB will ignore it.  */
10189   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
10190     return 0;
10191
10192   *lowpc = low;
10193   if (highpc)
10194     *highpc = high;
10195   return ret;
10196 }
10197
10198 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
10199    its low and high PC addresses.  Do nothing if these addresses could not
10200    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
10201    and HIGHPC to the high address if greater than HIGHPC.  */
10202
10203 static void
10204 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
10205                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
10206                                  struct dwarf2_cu *cu)
10207 {
10208   CORE_ADDR low, high;
10209   struct die_info *child = die->child;
10210
10211   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
10212     {
10213       *lowpc = min (*lowpc, low);
10214       *highpc = max (*highpc, high);
10215     }
10216
10217   /* If the language does not allow nested subprograms (either inside
10218      subprograms or lexical blocks), we're done.  */
10219   if (cu->language != language_ada)
10220     return;
10221
10222   /* Check all the children of the given DIE.  If it contains nested
10223      subprograms, then check their pc bounds.  Likewise, we need to
10224      check lexical blocks as well, as they may also contain subprogram
10225      definitions.  */
10226   while (child && child->tag)
10227     {
10228       if (child->tag == DW_TAG_subprogram
10229           || child->tag == DW_TAG_lexical_block)
10230         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
10231       child = sibling_die (child);
10232     }
10233 }
10234
10235 /* Get the low and high pc's represented by the scope DIE, and store
10236    them in *LOWPC and *HIGHPC.  If the correct values can't be
10237    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
10238
10239 static void
10240 get_scope_pc_bounds (struct die_info *die,
10241                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
10242                      struct dwarf2_cu *cu)
10243 {
10244   CORE_ADDR best_low = (CORE_ADDR) -1;
10245   CORE_ADDR best_high = (CORE_ADDR) 0;
10246   CORE_ADDR current_low, current_high;
10247
10248   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
10249     {
10250       best_low = current_low;
10251       best_high = current_high;
10252     }
10253   else
10254     {
10255       struct die_info *child = die->child;
10256
10257       while (child && child->tag)
10258         {
10259           switch (child->tag) {
10260           case DW_TAG_subprogram:
10261             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
10262             break;
10263           case DW_TAG_namespace:
10264           case DW_TAG_module:
10265             /* FIXME: carlton/2004-01-16: Should we do this for
10266                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
10267                that current GCC's always emit the DIEs corresponding
10268                to definitions of methods of classes as children of a
10269                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
10270                the DIEs giving the declarations, which could be
10271                anywhere).  But I don't see any reason why the
10272                standards says that they have to be there.  */
10273             get_scope_pc_bounds (child, &current_low, &current_high, cu);
10274
10275             if (current_low != ((CORE_ADDR) -1))
10276               {
10277                 best_low = min (best_low, current_low);
10278                 best_high = max (best_high, current_high);
10279               }
10280             break;
10281           default:
10282             /* Ignore.  */
10283             break;
10284           }
10285
10286           child = sibling_die (child);
10287         }
10288     }
10289
10290   *lowpc = best_low;
10291   *highpc = best_high;
10292 }
10293
10294 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
10295    in DIE.  */
10296
10297 static void
10298 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
10299                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
10300 {
10301   struct objfile *objfile = cu->objfile;
10302   struct attribute *attr;
10303   struct attribute *attr_high;
10304
10305   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
10306   if (attr_high)
10307     {
10308       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
10309       if (attr)
10310         {
10311           CORE_ADDR low = DW_ADDR (attr);
10312           CORE_ADDR high;
10313           if (attr_high->form == DW_FORM_addr
10314               || attr_high->form == DW_FORM_GNU_addr_index)
10315             high = DW_ADDR (attr_high);
10316           else
10317             high = low + DW_UNSND (attr_high);
10318
10319           record_block_range (block, baseaddr + low, baseaddr + high - 1);
10320         }
10321     }
10322
10323   attr = dwarf2_attr (die, DW_AT_ranges, cu);
10324   if (attr)
10325     {
10326       bfd *obfd = objfile->obfd;
10327       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
10328          We take advantage of the fact that DW_AT_ranges does not appear
10329          in DW_TAG_compile_unit of DWO files.  */
10330       int need_ranges_base = die->tag != DW_TAG_compile_unit;
10331
10332       /* The value of the DW_AT_ranges attribute is the offset of the
10333          address range list in the .debug_ranges section.  */
10334       unsigned long offset = (DW_UNSND (attr)
10335                               + (need_ranges_base ? cu->ranges_base : 0));
10336       gdb_byte *buffer = dwarf2_per_objfile->ranges.buffer + offset;
10337
10338       /* For some target architectures, but not others, the
10339          read_address function sign-extends the addresses it returns.
10340          To recognize base address selection entries, we need a
10341          mask.  */
10342       unsigned int addr_size = cu->header.addr_size;
10343       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
10344
10345       /* The base address, to which the next pair is relative.  Note
10346          that this 'base' is a DWARF concept: most entries in a range
10347          list are relative, to reduce the number of relocs against the
10348          debugging information.  This is separate from this function's
10349          'baseaddr' argument, which GDB uses to relocate debugging
10350          information from a shared library based on the address at
10351          which the library was loaded.  */
10352       CORE_ADDR base = cu->base_address;
10353       int base_known = cu->base_known;
10354
10355       gdb_assert (dwarf2_per_objfile->ranges.readin);
10356       if (offset >= dwarf2_per_objfile->ranges.size)
10357         {
10358           complaint (&symfile_complaints,
10359                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
10360                      offset);
10361           return;
10362         }
10363
10364       for (;;)
10365         {
10366           unsigned int bytes_read;
10367           CORE_ADDR start, end;
10368
10369           start = read_address (obfd, buffer, cu, &bytes_read);
10370           buffer += bytes_read;
10371           end = read_address (obfd, buffer, cu, &bytes_read);
10372           buffer += bytes_read;
10373
10374           /* Did we find the end of the range list?  */
10375           if (start == 0 && end == 0)
10376             break;
10377
10378           /* Did we find a base address selection entry?  */
10379           else if ((start & base_select_mask) == base_select_mask)
10380             {
10381               base = end;
10382               base_known = 1;
10383             }
10384
10385           /* We found an ordinary address range.  */
10386           else
10387             {
10388               if (!base_known)
10389                 {
10390                   complaint (&symfile_complaints,
10391                              _("Invalid .debug_ranges data "
10392                                "(no base address)"));
10393                   return;
10394                 }
10395
10396               if (start > end)
10397                 {
10398                   /* Inverted range entries are invalid.  */
10399                   complaint (&symfile_complaints,
10400                              _("Invalid .debug_ranges data "
10401                                "(inverted range)"));
10402                   return;
10403                 }
10404
10405               /* Empty range entries have no effect.  */
10406               if (start == end)
10407                 continue;
10408
10409               start += base + baseaddr;
10410               end += base + baseaddr;
10411
10412               /* A not-uncommon case of bad debug info.
10413                  Don't pollute the addrmap with bad data.  */
10414               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
10415                 {
10416                   complaint (&symfile_complaints,
10417                              _(".debug_ranges entry has start address of zero"
10418                                " [in module %s]"), objfile->name);
10419                   continue;
10420                 }
10421
10422               record_block_range (block, start, end - 1);
10423             }
10424         }
10425     }
10426 }
10427
10428 /* Check whether the producer field indicates either of GCC < 4.6, or the
10429    Intel C/C++ compiler, and cache the result in CU.  */
10430
10431 static void
10432 check_producer (struct dwarf2_cu *cu)
10433 {
10434   const char *cs;
10435   int major, minor, release;
10436
10437   if (cu->producer == NULL)
10438     {
10439       /* For unknown compilers expect their behavior is DWARF version
10440          compliant.
10441
10442          GCC started to support .debug_types sections by -gdwarf-4 since
10443          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
10444          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
10445          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
10446          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
10447     }
10448   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
10449     {
10450       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
10451
10452       cs = &cu->producer[strlen ("GNU ")];
10453       while (*cs && !isdigit (*cs))
10454         cs++;
10455       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
10456         {
10457           /* Not recognized as GCC.  */
10458         }
10459       else
10460         {
10461           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
10462           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
10463         }
10464     }
10465   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
10466     cu->producer_is_icc = 1;
10467   else
10468     {
10469       /* For other non-GCC compilers, expect their behavior is DWARF version
10470          compliant.  */
10471     }
10472
10473   cu->checked_producer = 1;
10474 }
10475
10476 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
10477    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
10478    during 4.6.0 experimental.  */
10479
10480 static int
10481 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
10482 {
10483   if (!cu->checked_producer)
10484     check_producer (cu);
10485
10486   return cu->producer_is_gxx_lt_4_6;
10487 }
10488
10489 /* Return the default accessibility type if it is not overriden by
10490    DW_AT_accessibility.  */
10491
10492 static enum dwarf_access_attribute
10493 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
10494 {
10495   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
10496     {
10497       /* The default DWARF 2 accessibility for members is public, the default
10498          accessibility for inheritance is private.  */
10499
10500       if (die->tag != DW_TAG_inheritance)
10501         return DW_ACCESS_public;
10502       else
10503         return DW_ACCESS_private;
10504     }
10505   else
10506     {
10507       /* DWARF 3+ defines the default accessibility a different way.  The same
10508          rules apply now for DW_TAG_inheritance as for the members and it only
10509          depends on the container kind.  */
10510
10511       if (die->parent->tag == DW_TAG_class_type)
10512         return DW_ACCESS_private;
10513       else
10514         return DW_ACCESS_public;
10515     }
10516 }
10517
10518 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
10519    offset.  If the attribute was not found return 0, otherwise return
10520    1.  If it was found but could not properly be handled, set *OFFSET
10521    to 0.  */
10522
10523 static int
10524 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
10525                              LONGEST *offset)
10526 {
10527   struct attribute *attr;
10528
10529   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
10530   if (attr != NULL)
10531     {
10532       *offset = 0;
10533
10534       /* Note that we do not check for a section offset first here.
10535          This is because DW_AT_data_member_location is new in DWARF 4,
10536          so if we see it, we can assume that a constant form is really
10537          a constant and not a section offset.  */
10538       if (attr_form_is_constant (attr))
10539         *offset = dwarf2_get_attr_constant_value (attr, 0);
10540       else if (attr_form_is_section_offset (attr))
10541         dwarf2_complex_location_expr_complaint ();
10542       else if (attr_form_is_block (attr))
10543         *offset = decode_locdesc (DW_BLOCK (attr), cu);
10544       else
10545         dwarf2_complex_location_expr_complaint ();
10546
10547       return 1;
10548     }
10549
10550   return 0;
10551 }
10552
10553 /* Add an aggregate field to the field list.  */
10554
10555 static void
10556 dwarf2_add_field (struct field_info *fip, struct die_info *die,
10557                   struct dwarf2_cu *cu)
10558 {
10559   struct objfile *objfile = cu->objfile;
10560   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10561   struct nextfield *new_field;
10562   struct attribute *attr;
10563   struct field *fp;
10564   const char *fieldname = "";
10565
10566   /* Allocate a new field list entry and link it in.  */
10567   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
10568   make_cleanup (xfree, new_field);
10569   memset (new_field, 0, sizeof (struct nextfield));
10570
10571   if (die->tag == DW_TAG_inheritance)
10572     {
10573       new_field->next = fip->baseclasses;
10574       fip->baseclasses = new_field;
10575     }
10576   else
10577     {
10578       new_field->next = fip->fields;
10579       fip->fields = new_field;
10580     }
10581   fip->nfields++;
10582
10583   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
10584   if (attr)
10585     new_field->accessibility = DW_UNSND (attr);
10586   else
10587     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
10588   if (new_field->accessibility != DW_ACCESS_public)
10589     fip->non_public_fields = 1;
10590
10591   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
10592   if (attr)
10593     new_field->virtuality = DW_UNSND (attr);
10594   else
10595     new_field->virtuality = DW_VIRTUALITY_none;
10596
10597   fp = &new_field->field;
10598
10599   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
10600     {
10601       LONGEST offset;
10602
10603       /* Data member other than a C++ static data member.  */
10604
10605       /* Get type of field.  */
10606       fp->type = die_type (die, cu);
10607
10608       SET_FIELD_BITPOS (*fp, 0);
10609
10610       /* Get bit size of field (zero if none).  */
10611       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
10612       if (attr)
10613         {
10614           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
10615         }
10616       else
10617         {
10618           FIELD_BITSIZE (*fp) = 0;
10619         }
10620
10621       /* Get bit offset of field.  */
10622       if (handle_data_member_location (die, cu, &offset))
10623         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10624       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
10625       if (attr)
10626         {
10627           if (gdbarch_bits_big_endian (gdbarch))
10628             {
10629               /* For big endian bits, the DW_AT_bit_offset gives the
10630                  additional bit offset from the MSB of the containing
10631                  anonymous object to the MSB of the field.  We don't
10632                  have to do anything special since we don't need to
10633                  know the size of the anonymous object.  */
10634               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
10635             }
10636           else
10637             {
10638               /* For little endian bits, compute the bit offset to the
10639                  MSB of the anonymous object, subtract off the number of
10640                  bits from the MSB of the field to the MSB of the
10641                  object, and then subtract off the number of bits of
10642                  the field itself.  The result is the bit offset of
10643                  the LSB of the field.  */
10644               int anonymous_size;
10645               int bit_offset = DW_UNSND (attr);
10646
10647               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
10648               if (attr)
10649                 {
10650                   /* The size of the anonymous object containing
10651                      the bit field is explicit, so use the
10652                      indicated size (in bytes).  */
10653                   anonymous_size = DW_UNSND (attr);
10654                 }
10655               else
10656                 {
10657                   /* The size of the anonymous object containing
10658                      the bit field must be inferred from the type
10659                      attribute of the data member containing the
10660                      bit field.  */
10661                   anonymous_size = TYPE_LENGTH (fp->type);
10662                 }
10663               SET_FIELD_BITPOS (*fp,
10664                                 (FIELD_BITPOS (*fp)
10665                                  + anonymous_size * bits_per_byte
10666                                  - bit_offset - FIELD_BITSIZE (*fp)));
10667             }
10668         }
10669
10670       /* Get name of field.  */
10671       fieldname = dwarf2_name (die, cu);
10672       if (fieldname == NULL)
10673         fieldname = "";
10674
10675       /* The name is already allocated along with this objfile, so we don't
10676          need to duplicate it for the type.  */
10677       fp->name = fieldname;
10678
10679       /* Change accessibility for artificial fields (e.g. virtual table
10680          pointer or virtual base class pointer) to private.  */
10681       if (dwarf2_attr (die, DW_AT_artificial, cu))
10682         {
10683           FIELD_ARTIFICIAL (*fp) = 1;
10684           new_field->accessibility = DW_ACCESS_private;
10685           fip->non_public_fields = 1;
10686         }
10687     }
10688   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
10689     {
10690       /* C++ static member.  */
10691
10692       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
10693          is a declaration, but all versions of G++ as of this writing
10694          (so through at least 3.2.1) incorrectly generate
10695          DW_TAG_variable tags.  */
10696
10697       const char *physname;
10698
10699       /* Get name of field.  */
10700       fieldname = dwarf2_name (die, cu);
10701       if (fieldname == NULL)
10702         return;
10703
10704       attr = dwarf2_attr (die, DW_AT_const_value, cu);
10705       if (attr
10706           /* Only create a symbol if this is an external value.
10707              new_symbol checks this and puts the value in the global symbol
10708              table, which we want.  If it is not external, new_symbol
10709              will try to put the value in cu->list_in_scope which is wrong.  */
10710           && dwarf2_flag_true_p (die, DW_AT_external, cu))
10711         {
10712           /* A static const member, not much different than an enum as far as
10713              we're concerned, except that we can support more types.  */
10714           new_symbol (die, NULL, cu);
10715         }
10716
10717       /* Get physical name.  */
10718       physname = dwarf2_physname (fieldname, die, cu);
10719
10720       /* The name is already allocated along with this objfile, so we don't
10721          need to duplicate it for the type.  */
10722       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
10723       FIELD_TYPE (*fp) = die_type (die, cu);
10724       FIELD_NAME (*fp) = fieldname;
10725     }
10726   else if (die->tag == DW_TAG_inheritance)
10727     {
10728       LONGEST offset;
10729
10730       /* C++ base class field.  */
10731       if (handle_data_member_location (die, cu, &offset))
10732         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
10733       FIELD_BITSIZE (*fp) = 0;
10734       FIELD_TYPE (*fp) = die_type (die, cu);
10735       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
10736       fip->nbaseclasses++;
10737     }
10738 }
10739
10740 /* Add a typedef defined in the scope of the FIP's class.  */
10741
10742 static void
10743 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
10744                     struct dwarf2_cu *cu)
10745 {
10746   struct objfile *objfile = cu->objfile;
10747   struct typedef_field_list *new_field;
10748   struct attribute *attr;
10749   struct typedef_field *fp;
10750   char *fieldname = "";
10751
10752   /* Allocate a new field list entry and link it in.  */
10753   new_field = xzalloc (sizeof (*new_field));
10754   make_cleanup (xfree, new_field);
10755
10756   gdb_assert (die->tag == DW_TAG_typedef);
10757
10758   fp = &new_field->field;
10759
10760   /* Get name of field.  */
10761   fp->name = dwarf2_name (die, cu);
10762   if (fp->name == NULL)
10763     return;
10764
10765   fp->type = read_type_die (die, cu);
10766
10767   new_field->next = fip->typedef_field_list;
10768   fip->typedef_field_list = new_field;
10769   fip->typedef_field_list_count++;
10770 }
10771
10772 /* Create the vector of fields, and attach it to the type.  */
10773
10774 static void
10775 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
10776                               struct dwarf2_cu *cu)
10777 {
10778   int nfields = fip->nfields;
10779
10780   /* Record the field count, allocate space for the array of fields,
10781      and create blank accessibility bitfields if necessary.  */
10782   TYPE_NFIELDS (type) = nfields;
10783   TYPE_FIELDS (type) = (struct field *)
10784     TYPE_ALLOC (type, sizeof (struct field) * nfields);
10785   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
10786
10787   if (fip->non_public_fields && cu->language != language_ada)
10788     {
10789       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10790
10791       TYPE_FIELD_PRIVATE_BITS (type) =
10792         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10793       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
10794
10795       TYPE_FIELD_PROTECTED_BITS (type) =
10796         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10797       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
10798
10799       TYPE_FIELD_IGNORE_BITS (type) =
10800         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
10801       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
10802     }
10803
10804   /* If the type has baseclasses, allocate and clear a bit vector for
10805      TYPE_FIELD_VIRTUAL_BITS.  */
10806   if (fip->nbaseclasses && cu->language != language_ada)
10807     {
10808       int num_bytes = B_BYTES (fip->nbaseclasses);
10809       unsigned char *pointer;
10810
10811       ALLOCATE_CPLUS_STRUCT_TYPE (type);
10812       pointer = TYPE_ALLOC (type, num_bytes);
10813       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
10814       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
10815       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
10816     }
10817
10818   /* Copy the saved-up fields into the field vector.  Start from the head of
10819      the list, adding to the tail of the field array, so that they end up in
10820      the same order in the array in which they were added to the list.  */
10821   while (nfields-- > 0)
10822     {
10823       struct nextfield *fieldp;
10824
10825       if (fip->fields)
10826         {
10827           fieldp = fip->fields;
10828           fip->fields = fieldp->next;
10829         }
10830       else
10831         {
10832           fieldp = fip->baseclasses;
10833           fip->baseclasses = fieldp->next;
10834         }
10835
10836       TYPE_FIELD (type, nfields) = fieldp->field;
10837       switch (fieldp->accessibility)
10838         {
10839         case DW_ACCESS_private:
10840           if (cu->language != language_ada)
10841             SET_TYPE_FIELD_PRIVATE (type, nfields);
10842           break;
10843
10844         case DW_ACCESS_protected:
10845           if (cu->language != language_ada)
10846             SET_TYPE_FIELD_PROTECTED (type, nfields);
10847           break;
10848
10849         case DW_ACCESS_public:
10850           break;
10851
10852         default:
10853           /* Unknown accessibility.  Complain and treat it as public.  */
10854           {
10855             complaint (&symfile_complaints, _("unsupported accessibility %d"),
10856                        fieldp->accessibility);
10857           }
10858           break;
10859         }
10860       if (nfields < fip->nbaseclasses)
10861         {
10862           switch (fieldp->virtuality)
10863             {
10864             case DW_VIRTUALITY_virtual:
10865             case DW_VIRTUALITY_pure_virtual:
10866               if (cu->language == language_ada)
10867                 error (_("unexpected virtuality in component of Ada type"));
10868               SET_TYPE_FIELD_VIRTUAL (type, nfields);
10869               break;
10870             }
10871         }
10872     }
10873 }
10874
10875 /* Return true if this member function is a constructor, false
10876    otherwise.  */
10877
10878 static int
10879 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
10880 {
10881   const char *fieldname;
10882   const char *typename;
10883   int len;
10884
10885   if (die->parent == NULL)
10886     return 0;
10887
10888   if (die->parent->tag != DW_TAG_structure_type
10889       && die->parent->tag != DW_TAG_union_type
10890       && die->parent->tag != DW_TAG_class_type)
10891     return 0;
10892
10893   fieldname = dwarf2_name (die, cu);
10894   typename = dwarf2_name (die->parent, cu);
10895   if (fieldname == NULL || typename == NULL)
10896     return 0;
10897
10898   len = strlen (fieldname);
10899   return (strncmp (fieldname, typename, len) == 0
10900           && (typename[len] == '\0' || typename[len] == '<'));
10901 }
10902
10903 /* Add a member function to the proper fieldlist.  */
10904
10905 static void
10906 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
10907                       struct type *type, struct dwarf2_cu *cu)
10908 {
10909   struct objfile *objfile = cu->objfile;
10910   struct attribute *attr;
10911   struct fnfieldlist *flp;
10912   int i;
10913   struct fn_field *fnp;
10914   const char *fieldname;
10915   struct nextfnfield *new_fnfield;
10916   struct type *this_type;
10917   enum dwarf_access_attribute accessibility;
10918
10919   if (cu->language == language_ada)
10920     error (_("unexpected member function in Ada type"));
10921
10922   /* Get name of member function.  */
10923   fieldname = dwarf2_name (die, cu);
10924   if (fieldname == NULL)
10925     return;
10926
10927   /* Look up member function name in fieldlist.  */
10928   for (i = 0; i < fip->nfnfields; i++)
10929     {
10930       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
10931         break;
10932     }
10933
10934   /* Create new list element if necessary.  */
10935   if (i < fip->nfnfields)
10936     flp = &fip->fnfieldlists[i];
10937   else
10938     {
10939       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
10940         {
10941           fip->fnfieldlists = (struct fnfieldlist *)
10942             xrealloc (fip->fnfieldlists,
10943                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
10944                       * sizeof (struct fnfieldlist));
10945           if (fip->nfnfields == 0)
10946             make_cleanup (free_current_contents, &fip->fnfieldlists);
10947         }
10948       flp = &fip->fnfieldlists[fip->nfnfields];
10949       flp->name = fieldname;
10950       flp->length = 0;
10951       flp->head = NULL;
10952       i = fip->nfnfields++;
10953     }
10954
10955   /* Create a new member function field and chain it to the field list
10956      entry.  */
10957   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
10958   make_cleanup (xfree, new_fnfield);
10959   memset (new_fnfield, 0, sizeof (struct nextfnfield));
10960   new_fnfield->next = flp->head;
10961   flp->head = new_fnfield;
10962   flp->length++;
10963
10964   /* Fill in the member function field info.  */
10965   fnp = &new_fnfield->fnfield;
10966
10967   /* Delay processing of the physname until later.  */
10968   if (cu->language == language_cplus || cu->language == language_java)
10969     {
10970       add_to_method_list (type, i, flp->length - 1, fieldname,
10971                           die, cu);
10972     }
10973   else
10974     {
10975       const char *physname = dwarf2_physname (fieldname, die, cu);
10976       fnp->physname = physname ? physname : "";
10977     }
10978
10979   fnp->type = alloc_type (objfile);
10980   this_type = read_type_die (die, cu);
10981   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
10982     {
10983       int nparams = TYPE_NFIELDS (this_type);
10984
10985       /* TYPE is the domain of this method, and THIS_TYPE is the type
10986            of the method itself (TYPE_CODE_METHOD).  */
10987       smash_to_method_type (fnp->type, type,
10988                             TYPE_TARGET_TYPE (this_type),
10989                             TYPE_FIELDS (this_type),
10990                             TYPE_NFIELDS (this_type),
10991                             TYPE_VARARGS (this_type));
10992
10993       /* Handle static member functions.
10994          Dwarf2 has no clean way to discern C++ static and non-static
10995          member functions.  G++ helps GDB by marking the first
10996          parameter for non-static member functions (which is the this
10997          pointer) as artificial.  We obtain this information from
10998          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
10999       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
11000         fnp->voffset = VOFFSET_STATIC;
11001     }
11002   else
11003     complaint (&symfile_complaints, _("member function type missing for '%s'"),
11004                dwarf2_full_name (fieldname, die, cu));
11005
11006   /* Get fcontext from DW_AT_containing_type if present.  */
11007   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11008     fnp->fcontext = die_containing_type (die, cu);
11009
11010   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
11011      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
11012
11013   /* Get accessibility.  */
11014   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11015   if (attr)
11016     accessibility = DW_UNSND (attr);
11017   else
11018     accessibility = dwarf2_default_access_attribute (die, cu);
11019   switch (accessibility)
11020     {
11021     case DW_ACCESS_private:
11022       fnp->is_private = 1;
11023       break;
11024     case DW_ACCESS_protected:
11025       fnp->is_protected = 1;
11026       break;
11027     }
11028
11029   /* Check for artificial methods.  */
11030   attr = dwarf2_attr (die, DW_AT_artificial, cu);
11031   if (attr && DW_UNSND (attr) != 0)
11032     fnp->is_artificial = 1;
11033
11034   fnp->is_constructor = dwarf2_is_constructor (die, cu);
11035
11036   /* Get index in virtual function table if it is a virtual member
11037      function.  For older versions of GCC, this is an offset in the
11038      appropriate virtual table, as specified by DW_AT_containing_type.
11039      For everyone else, it is an expression to be evaluated relative
11040      to the object address.  */
11041
11042   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
11043   if (attr)
11044     {
11045       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
11046         {
11047           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
11048             {
11049               /* Old-style GCC.  */
11050               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
11051             }
11052           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
11053                    || (DW_BLOCK (attr)->size > 1
11054                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
11055                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
11056             {
11057               struct dwarf_block blk;
11058               int offset;
11059
11060               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
11061                         ? 1 : 2);
11062               blk.size = DW_BLOCK (attr)->size - offset;
11063               blk.data = DW_BLOCK (attr)->data + offset;
11064               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
11065               if ((fnp->voffset % cu->header.addr_size) != 0)
11066                 dwarf2_complex_location_expr_complaint ();
11067               else
11068                 fnp->voffset /= cu->header.addr_size;
11069               fnp->voffset += 2;
11070             }
11071           else
11072             dwarf2_complex_location_expr_complaint ();
11073
11074           if (!fnp->fcontext)
11075             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
11076         }
11077       else if (attr_form_is_section_offset (attr))
11078         {
11079           dwarf2_complex_location_expr_complaint ();
11080         }
11081       else
11082         {
11083           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
11084                                                  fieldname);
11085         }
11086     }
11087   else
11088     {
11089       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11090       if (attr && DW_UNSND (attr))
11091         {
11092           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
11093           complaint (&symfile_complaints,
11094                      _("Member function \"%s\" (offset %d) is virtual "
11095                        "but the vtable offset is not specified"),
11096                      fieldname, die->offset.sect_off);
11097           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11098           TYPE_CPLUS_DYNAMIC (type) = 1;
11099         }
11100     }
11101 }
11102
11103 /* Create the vector of member function fields, and attach it to the type.  */
11104
11105 static void
11106 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
11107                                  struct dwarf2_cu *cu)
11108 {
11109   struct fnfieldlist *flp;
11110   int i;
11111
11112   if (cu->language == language_ada)
11113     error (_("unexpected member functions in Ada type"));
11114
11115   ALLOCATE_CPLUS_STRUCT_TYPE (type);
11116   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
11117     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
11118
11119   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
11120     {
11121       struct nextfnfield *nfp = flp->head;
11122       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
11123       int k;
11124
11125       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
11126       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
11127       fn_flp->fn_fields = (struct fn_field *)
11128         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
11129       for (k = flp->length; (k--, nfp); nfp = nfp->next)
11130         fn_flp->fn_fields[k] = nfp->fnfield;
11131     }
11132
11133   TYPE_NFN_FIELDS (type) = fip->nfnfields;
11134 }
11135
11136 /* Returns non-zero if NAME is the name of a vtable member in CU's
11137    language, zero otherwise.  */
11138 static int
11139 is_vtable_name (const char *name, struct dwarf2_cu *cu)
11140 {
11141   static const char vptr[] = "_vptr";
11142   static const char vtable[] = "vtable";
11143
11144   /* Look for the C++ and Java forms of the vtable.  */
11145   if ((cu->language == language_java
11146        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
11147        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
11148        && is_cplus_marker (name[sizeof (vptr) - 1])))
11149     return 1;
11150
11151   return 0;
11152 }
11153
11154 /* GCC outputs unnamed structures that are really pointers to member
11155    functions, with the ABI-specified layout.  If TYPE describes
11156    such a structure, smash it into a member function type.
11157
11158    GCC shouldn't do this; it should just output pointer to member DIEs.
11159    This is GCC PR debug/28767.  */
11160
11161 static void
11162 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
11163 {
11164   struct type *pfn_type, *domain_type, *new_type;
11165
11166   /* Check for a structure with no name and two children.  */
11167   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
11168     return;
11169
11170   /* Check for __pfn and __delta members.  */
11171   if (TYPE_FIELD_NAME (type, 0) == NULL
11172       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
11173       || TYPE_FIELD_NAME (type, 1) == NULL
11174       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
11175     return;
11176
11177   /* Find the type of the method.  */
11178   pfn_type = TYPE_FIELD_TYPE (type, 0);
11179   if (pfn_type == NULL
11180       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
11181       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
11182     return;
11183
11184   /* Look for the "this" argument.  */
11185   pfn_type = TYPE_TARGET_TYPE (pfn_type);
11186   if (TYPE_NFIELDS (pfn_type) == 0
11187       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
11188       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
11189     return;
11190
11191   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
11192   new_type = alloc_type (objfile);
11193   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
11194                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
11195                         TYPE_VARARGS (pfn_type));
11196   smash_to_methodptr_type (type, new_type);
11197 }
11198
11199 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
11200    (icc).  */
11201
11202 static int
11203 producer_is_icc (struct dwarf2_cu *cu)
11204 {
11205   if (!cu->checked_producer)
11206     check_producer (cu);
11207
11208   return cu->producer_is_icc;
11209 }
11210
11211 /* Called when we find the DIE that starts a structure or union scope
11212    (definition) to create a type for the structure or union.  Fill in
11213    the type's name and general properties; the members will not be
11214    processed until process_structure_type.
11215
11216    NOTE: we need to call these functions regardless of whether or not the
11217    DIE has a DW_AT_name attribute, since it might be an anonymous
11218    structure or union.  This gets the type entered into our set of
11219    user defined types.
11220
11221    However, if the structure is incomplete (an opaque struct/union)
11222    then suppress creating a symbol table entry for it since gdb only
11223    wants to find the one with the complete definition.  Note that if
11224    it is complete, we just call new_symbol, which does it's own
11225    checking about whether the struct/union is anonymous or not (and
11226    suppresses creating a symbol table entry itself).  */
11227
11228 static struct type *
11229 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
11230 {
11231   struct objfile *objfile = cu->objfile;
11232   struct type *type;
11233   struct attribute *attr;
11234   const char *name;
11235
11236   /* If the definition of this type lives in .debug_types, read that type.
11237      Don't follow DW_AT_specification though, that will take us back up
11238      the chain and we want to go down.  */
11239   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11240   if (attr)
11241     {
11242       struct dwarf2_cu *type_cu = cu;
11243       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11244
11245       /* We could just recurse on read_structure_type, but we need to call
11246          get_die_type to ensure only one type for this DIE is created.
11247          This is important, for example, because for c++ classes we need
11248          TYPE_NAME set which is only done by new_symbol.  Blech.  */
11249       type = read_type_die (type_die, type_cu);
11250
11251       /* TYPE_CU may not be the same as CU.
11252          Ensure TYPE is recorded in CU's type_hash table.  */
11253       return set_die_type (die, type, cu);
11254     }
11255
11256   type = alloc_type (objfile);
11257   INIT_CPLUS_SPECIFIC (type);
11258
11259   name = dwarf2_name (die, cu);
11260   if (name != NULL)
11261     {
11262       if (cu->language == language_cplus
11263           || cu->language == language_java)
11264         {
11265           const char *full_name = dwarf2_full_name (name, die, cu);
11266
11267           /* dwarf2_full_name might have already finished building the DIE's
11268              type.  If so, there is no need to continue.  */
11269           if (get_die_type (die, cu) != NULL)
11270             return get_die_type (die, cu);
11271
11272           TYPE_TAG_NAME (type) = full_name;
11273           if (die->tag == DW_TAG_structure_type
11274               || die->tag == DW_TAG_class_type)
11275             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11276         }
11277       else
11278         {
11279           /* The name is already allocated along with this objfile, so
11280              we don't need to duplicate it for the type.  */
11281           TYPE_TAG_NAME (type) = name;
11282           if (die->tag == DW_TAG_class_type)
11283             TYPE_NAME (type) = TYPE_TAG_NAME (type);
11284         }
11285     }
11286
11287   if (die->tag == DW_TAG_structure_type)
11288     {
11289       TYPE_CODE (type) = TYPE_CODE_STRUCT;
11290     }
11291   else if (die->tag == DW_TAG_union_type)
11292     {
11293       TYPE_CODE (type) = TYPE_CODE_UNION;
11294     }
11295   else
11296     {
11297       TYPE_CODE (type) = TYPE_CODE_CLASS;
11298     }
11299
11300   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
11301     TYPE_DECLARED_CLASS (type) = 1;
11302
11303   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11304   if (attr)
11305     {
11306       TYPE_LENGTH (type) = DW_UNSND (attr);
11307     }
11308   else
11309     {
11310       TYPE_LENGTH (type) = 0;
11311     }
11312
11313   if (producer_is_icc (cu))
11314     {
11315       /* ICC does not output the required DW_AT_declaration
11316          on incomplete types, but gives them a size of zero.  */
11317     }
11318   else
11319     TYPE_STUB_SUPPORTED (type) = 1;
11320
11321   if (die_is_declaration (die, cu))
11322     TYPE_STUB (type) = 1;
11323   else if (attr == NULL && die->child == NULL
11324            && producer_is_realview (cu->producer))
11325     /* RealView does not output the required DW_AT_declaration
11326        on incomplete types.  */
11327     TYPE_STUB (type) = 1;
11328
11329   /* We need to add the type field to the die immediately so we don't
11330      infinitely recurse when dealing with pointers to the structure
11331      type within the structure itself.  */
11332   set_die_type (die, type, cu);
11333
11334   /* set_die_type should be already done.  */
11335   set_descriptive_type (type, die, cu);
11336
11337   return type;
11338 }
11339
11340 /* Finish creating a structure or union type, including filling in
11341    its members and creating a symbol for it.  */
11342
11343 static void
11344 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
11345 {
11346   struct objfile *objfile = cu->objfile;
11347   struct die_info *child_die = die->child;
11348   struct type *type;
11349
11350   type = get_die_type (die, cu);
11351   if (type == NULL)
11352     type = read_structure_type (die, cu);
11353
11354   if (die->child != NULL && ! die_is_declaration (die, cu))
11355     {
11356       struct field_info fi;
11357       struct die_info *child_die;
11358       VEC (symbolp) *template_args = NULL;
11359       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
11360
11361       memset (&fi, 0, sizeof (struct field_info));
11362
11363       child_die = die->child;
11364
11365       while (child_die && child_die->tag)
11366         {
11367           if (child_die->tag == DW_TAG_member
11368               || child_die->tag == DW_TAG_variable)
11369             {
11370               /* NOTE: carlton/2002-11-05: A C++ static data member
11371                  should be a DW_TAG_member that is a declaration, but
11372                  all versions of G++ as of this writing (so through at
11373                  least 3.2.1) incorrectly generate DW_TAG_variable
11374                  tags for them instead.  */
11375               dwarf2_add_field (&fi, child_die, cu);
11376             }
11377           else if (child_die->tag == DW_TAG_subprogram)
11378             {
11379               /* C++ member function.  */
11380               dwarf2_add_member_fn (&fi, child_die, type, cu);
11381             }
11382           else if (child_die->tag == DW_TAG_inheritance)
11383             {
11384               /* C++ base class field.  */
11385               dwarf2_add_field (&fi, child_die, cu);
11386             }
11387           else if (child_die->tag == DW_TAG_typedef)
11388             dwarf2_add_typedef (&fi, child_die, cu);
11389           else if (child_die->tag == DW_TAG_template_type_param
11390                    || child_die->tag == DW_TAG_template_value_param)
11391             {
11392               struct symbol *arg = new_symbol (child_die, NULL, cu);
11393
11394               if (arg != NULL)
11395                 VEC_safe_push (symbolp, template_args, arg);
11396             }
11397
11398           child_die = sibling_die (child_die);
11399         }
11400
11401       /* Attach template arguments to type.  */
11402       if (! VEC_empty (symbolp, template_args))
11403         {
11404           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11405           TYPE_N_TEMPLATE_ARGUMENTS (type)
11406             = VEC_length (symbolp, template_args);
11407           TYPE_TEMPLATE_ARGUMENTS (type)
11408             = obstack_alloc (&objfile->objfile_obstack,
11409                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
11410                               * sizeof (struct symbol *)));
11411           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
11412                   VEC_address (symbolp, template_args),
11413                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
11414                    * sizeof (struct symbol *)));
11415           VEC_free (symbolp, template_args);
11416         }
11417
11418       /* Attach fields and member functions to the type.  */
11419       if (fi.nfields)
11420         dwarf2_attach_fields_to_type (&fi, type, cu);
11421       if (fi.nfnfields)
11422         {
11423           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
11424
11425           /* Get the type which refers to the base class (possibly this
11426              class itself) which contains the vtable pointer for the current
11427              class from the DW_AT_containing_type attribute.  This use of
11428              DW_AT_containing_type is a GNU extension.  */
11429
11430           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
11431             {
11432               struct type *t = die_containing_type (die, cu);
11433
11434               TYPE_VPTR_BASETYPE (type) = t;
11435               if (type == t)
11436                 {
11437                   int i;
11438
11439                   /* Our own class provides vtbl ptr.  */
11440                   for (i = TYPE_NFIELDS (t) - 1;
11441                        i >= TYPE_N_BASECLASSES (t);
11442                        --i)
11443                     {
11444                       const char *fieldname = TYPE_FIELD_NAME (t, i);
11445
11446                       if (is_vtable_name (fieldname, cu))
11447                         {
11448                           TYPE_VPTR_FIELDNO (type) = i;
11449                           break;
11450                         }
11451                     }
11452
11453                   /* Complain if virtual function table field not found.  */
11454                   if (i < TYPE_N_BASECLASSES (t))
11455                     complaint (&symfile_complaints,
11456                                _("virtual function table pointer "
11457                                  "not found when defining class '%s'"),
11458                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
11459                                "");
11460                 }
11461               else
11462                 {
11463                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
11464                 }
11465             }
11466           else if (cu->producer
11467                    && strncmp (cu->producer,
11468                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
11469             {
11470               /* The IBM XLC compiler does not provide direct indication
11471                  of the containing type, but the vtable pointer is
11472                  always named __vfp.  */
11473
11474               int i;
11475
11476               for (i = TYPE_NFIELDS (type) - 1;
11477                    i >= TYPE_N_BASECLASSES (type);
11478                    --i)
11479                 {
11480                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
11481                     {
11482                       TYPE_VPTR_FIELDNO (type) = i;
11483                       TYPE_VPTR_BASETYPE (type) = type;
11484                       break;
11485                     }
11486                 }
11487             }
11488         }
11489
11490       /* Copy fi.typedef_field_list linked list elements content into the
11491          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
11492       if (fi.typedef_field_list)
11493         {
11494           int i = fi.typedef_field_list_count;
11495
11496           ALLOCATE_CPLUS_STRUCT_TYPE (type);
11497           TYPE_TYPEDEF_FIELD_ARRAY (type)
11498             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
11499           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
11500
11501           /* Reverse the list order to keep the debug info elements order.  */
11502           while (--i >= 0)
11503             {
11504               struct typedef_field *dest, *src;
11505
11506               dest = &TYPE_TYPEDEF_FIELD (type, i);
11507               src = &fi.typedef_field_list->field;
11508               fi.typedef_field_list = fi.typedef_field_list->next;
11509               *dest = *src;
11510             }
11511         }
11512
11513       do_cleanups (back_to);
11514
11515       if (HAVE_CPLUS_STRUCT (type))
11516         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
11517     }
11518
11519   quirk_gcc_member_function_pointer (type, objfile);
11520
11521   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
11522      snapshots) has been known to create a die giving a declaration
11523      for a class that has, as a child, a die giving a definition for a
11524      nested class.  So we have to process our children even if the
11525      current die is a declaration.  Normally, of course, a declaration
11526      won't have any children at all.  */
11527
11528   while (child_die != NULL && child_die->tag)
11529     {
11530       if (child_die->tag == DW_TAG_member
11531           || child_die->tag == DW_TAG_variable
11532           || child_die->tag == DW_TAG_inheritance
11533           || child_die->tag == DW_TAG_template_value_param
11534           || child_die->tag == DW_TAG_template_type_param)
11535         {
11536           /* Do nothing.  */
11537         }
11538       else
11539         process_die (child_die, cu);
11540
11541       child_die = sibling_die (child_die);
11542     }
11543
11544   /* Do not consider external references.  According to the DWARF standard,
11545      these DIEs are identified by the fact that they have no byte_size
11546      attribute, and a declaration attribute.  */
11547   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
11548       || !die_is_declaration (die, cu))
11549     new_symbol (die, type, cu);
11550 }
11551
11552 /* Given a DW_AT_enumeration_type die, set its type.  We do not
11553    complete the type's fields yet, or create any symbols.  */
11554
11555 static struct type *
11556 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
11557 {
11558   struct objfile *objfile = cu->objfile;
11559   struct type *type;
11560   struct attribute *attr;
11561   const char *name;
11562
11563   /* If the definition of this type lives in .debug_types, read that type.
11564      Don't follow DW_AT_specification though, that will take us back up
11565      the chain and we want to go down.  */
11566   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
11567   if (attr)
11568     {
11569       struct dwarf2_cu *type_cu = cu;
11570       struct die_info *type_die = follow_die_ref_or_sig (die, attr, &type_cu);
11571
11572       type = read_type_die (type_die, type_cu);
11573
11574       /* TYPE_CU may not be the same as CU.
11575          Ensure TYPE is recorded in CU's type_hash table.  */
11576       return set_die_type (die, type, cu);
11577     }
11578
11579   type = alloc_type (objfile);
11580
11581   TYPE_CODE (type) = TYPE_CODE_ENUM;
11582   name = dwarf2_full_name (NULL, die, cu);
11583   if (name != NULL)
11584     TYPE_TAG_NAME (type) = name;
11585
11586   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11587   if (attr)
11588     {
11589       TYPE_LENGTH (type) = DW_UNSND (attr);
11590     }
11591   else
11592     {
11593       TYPE_LENGTH (type) = 0;
11594     }
11595
11596   /* The enumeration DIE can be incomplete.  In Ada, any type can be
11597      declared as private in the package spec, and then defined only
11598      inside the package body.  Such types are known as Taft Amendment
11599      Types.  When another package uses such a type, an incomplete DIE
11600      may be generated by the compiler.  */
11601   if (die_is_declaration (die, cu))
11602     TYPE_STUB (type) = 1;
11603
11604   return set_die_type (die, type, cu);
11605 }
11606
11607 /* Given a pointer to a die which begins an enumeration, process all
11608    the dies that define the members of the enumeration, and create the
11609    symbol for the enumeration type.
11610
11611    NOTE: We reverse the order of the element list.  */
11612
11613 static void
11614 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
11615 {
11616   struct type *this_type;
11617
11618   this_type = get_die_type (die, cu);
11619   if (this_type == NULL)
11620     this_type = read_enumeration_type (die, cu);
11621
11622   if (die->child != NULL)
11623     {
11624       struct die_info *child_die;
11625       struct symbol *sym;
11626       struct field *fields = NULL;
11627       int num_fields = 0;
11628       int unsigned_enum = 1;
11629       const char *name;
11630       int flag_enum = 1;
11631       ULONGEST mask = 0;
11632
11633       child_die = die->child;
11634       while (child_die && child_die->tag)
11635         {
11636           if (child_die->tag != DW_TAG_enumerator)
11637             {
11638               process_die (child_die, cu);
11639             }
11640           else
11641             {
11642               name = dwarf2_name (child_die, cu);
11643               if (name)
11644                 {
11645                   sym = new_symbol (child_die, this_type, cu);
11646                   if (SYMBOL_VALUE (sym) < 0)
11647                     {
11648                       unsigned_enum = 0;
11649                       flag_enum = 0;
11650                     }
11651                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
11652                     flag_enum = 0;
11653                   else
11654                     mask |= SYMBOL_VALUE (sym);
11655
11656                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
11657                     {
11658                       fields = (struct field *)
11659                         xrealloc (fields,
11660                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
11661                                   * sizeof (struct field));
11662                     }
11663
11664                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
11665                   FIELD_TYPE (fields[num_fields]) = NULL;
11666                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
11667                   FIELD_BITSIZE (fields[num_fields]) = 0;
11668
11669                   num_fields++;
11670                 }
11671             }
11672
11673           child_die = sibling_die (child_die);
11674         }
11675
11676       if (num_fields)
11677         {
11678           TYPE_NFIELDS (this_type) = num_fields;
11679           TYPE_FIELDS (this_type) = (struct field *)
11680             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
11681           memcpy (TYPE_FIELDS (this_type), fields,
11682                   sizeof (struct field) * num_fields);
11683           xfree (fields);
11684         }
11685       if (unsigned_enum)
11686         TYPE_UNSIGNED (this_type) = 1;
11687       if (flag_enum)
11688         TYPE_FLAG_ENUM (this_type) = 1;
11689     }
11690
11691   /* If we are reading an enum from a .debug_types unit, and the enum
11692      is a declaration, and the enum is not the signatured type in the
11693      unit, then we do not want to add a symbol for it.  Adding a
11694      symbol would in some cases obscure the true definition of the
11695      enum, giving users an incomplete type when the definition is
11696      actually available.  Note that we do not want to do this for all
11697      enums which are just declarations, because C++0x allows forward
11698      enum declarations.  */
11699   if (cu->per_cu->is_debug_types
11700       && die_is_declaration (die, cu))
11701     {
11702       struct signatured_type *sig_type;
11703
11704       sig_type
11705         = lookup_signatured_type_at_offset (dwarf2_per_objfile->objfile,
11706                                             cu->per_cu->info_or_types_section,
11707                                             cu->per_cu->offset);
11708       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
11709       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
11710         return;
11711     }
11712
11713   new_symbol (die, this_type, cu);
11714 }
11715
11716 /* Extract all information from a DW_TAG_array_type DIE and put it in
11717    the DIE's type field.  For now, this only handles one dimensional
11718    arrays.  */
11719
11720 static struct type *
11721 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
11722 {
11723   struct objfile *objfile = cu->objfile;
11724   struct die_info *child_die;
11725   struct type *type;
11726   struct type *element_type, *range_type, *index_type;
11727   struct type **range_types = NULL;
11728   struct attribute *attr;
11729   int ndim = 0;
11730   struct cleanup *back_to;
11731   const char *name;
11732
11733   element_type = die_type (die, cu);
11734
11735   /* The die_type call above may have already set the type for this DIE.  */
11736   type = get_die_type (die, cu);
11737   if (type)
11738     return type;
11739
11740   /* Irix 6.2 native cc creates array types without children for
11741      arrays with unspecified length.  */
11742   if (die->child == NULL)
11743     {
11744       index_type = objfile_type (objfile)->builtin_int;
11745       range_type = create_range_type (NULL, index_type, 0, -1);
11746       type = create_array_type (NULL, element_type, range_type);
11747       return set_die_type (die, type, cu);
11748     }
11749
11750   back_to = make_cleanup (null_cleanup, NULL);
11751   child_die = die->child;
11752   while (child_die && child_die->tag)
11753     {
11754       if (child_die->tag == DW_TAG_subrange_type)
11755         {
11756           struct type *child_type = read_type_die (child_die, cu);
11757
11758           if (child_type != NULL)
11759             {
11760               /* The range type was succesfully read.  Save it for the
11761                  array type creation.  */
11762               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
11763                 {
11764                   range_types = (struct type **)
11765                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
11766                               * sizeof (struct type *));
11767                   if (ndim == 0)
11768                     make_cleanup (free_current_contents, &range_types);
11769                 }
11770               range_types[ndim++] = child_type;
11771             }
11772         }
11773       child_die = sibling_die (child_die);
11774     }
11775
11776   /* Dwarf2 dimensions are output from left to right, create the
11777      necessary array types in backwards order.  */
11778
11779   type = element_type;
11780
11781   if (read_array_order (die, cu) == DW_ORD_col_major)
11782     {
11783       int i = 0;
11784
11785       while (i < ndim)
11786         type = create_array_type (NULL, type, range_types[i++]);
11787     }
11788   else
11789     {
11790       while (ndim-- > 0)
11791         type = create_array_type (NULL, type, range_types[ndim]);
11792     }
11793
11794   /* Understand Dwarf2 support for vector types (like they occur on
11795      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
11796      array type.  This is not part of the Dwarf2/3 standard yet, but a
11797      custom vendor extension.  The main difference between a regular
11798      array and the vector variant is that vectors are passed by value
11799      to functions.  */
11800   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
11801   if (attr)
11802     make_vector_type (type);
11803
11804   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
11805      implementation may choose to implement triple vectors using this
11806      attribute.  */
11807   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11808   if (attr)
11809     {
11810       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
11811         TYPE_LENGTH (type) = DW_UNSND (attr);
11812       else
11813         complaint (&symfile_complaints,
11814                    _("DW_AT_byte_size for array type smaller "
11815                      "than the total size of elements"));
11816     }
11817
11818   name = dwarf2_name (die, cu);
11819   if (name)
11820     TYPE_NAME (type) = name;
11821
11822   /* Install the type in the die.  */
11823   set_die_type (die, type, cu);
11824
11825   /* set_die_type should be already done.  */
11826   set_descriptive_type (type, die, cu);
11827
11828   do_cleanups (back_to);
11829
11830   return type;
11831 }
11832
11833 static enum dwarf_array_dim_ordering
11834 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
11835 {
11836   struct attribute *attr;
11837
11838   attr = dwarf2_attr (die, DW_AT_ordering, cu);
11839
11840   if (attr) return DW_SND (attr);
11841
11842   /* GNU F77 is a special case, as at 08/2004 array type info is the
11843      opposite order to the dwarf2 specification, but data is still
11844      laid out as per normal fortran.
11845
11846      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
11847      version checking.  */
11848
11849   if (cu->language == language_fortran
11850       && cu->producer && strstr (cu->producer, "GNU F77"))
11851     {
11852       return DW_ORD_row_major;
11853     }
11854
11855   switch (cu->language_defn->la_array_ordering)
11856     {
11857     case array_column_major:
11858       return DW_ORD_col_major;
11859     case array_row_major:
11860     default:
11861       return DW_ORD_row_major;
11862     };
11863 }
11864
11865 /* Extract all information from a DW_TAG_set_type DIE and put it in
11866    the DIE's type field.  */
11867
11868 static struct type *
11869 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
11870 {
11871   struct type *domain_type, *set_type;
11872   struct attribute *attr;
11873
11874   domain_type = die_type (die, cu);
11875
11876   /* The die_type call above may have already set the type for this DIE.  */
11877   set_type = get_die_type (die, cu);
11878   if (set_type)
11879     return set_type;
11880
11881   set_type = create_set_type (NULL, domain_type);
11882
11883   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
11884   if (attr)
11885     TYPE_LENGTH (set_type) = DW_UNSND (attr);
11886
11887   return set_die_type (die, set_type, cu);
11888 }
11889
11890 /* A helper for read_common_block that creates a locexpr baton.
11891    SYM is the symbol which we are marking as computed.
11892    COMMON_DIE is the DIE for the common block.
11893    COMMON_LOC is the location expression attribute for the common
11894    block itself.
11895    MEMBER_LOC is the location expression attribute for the particular
11896    member of the common block that we are processing.
11897    CU is the CU from which the above come.  */
11898
11899 static void
11900 mark_common_block_symbol_computed (struct symbol *sym,
11901                                    struct die_info *common_die,
11902                                    struct attribute *common_loc,
11903                                    struct attribute *member_loc,
11904                                    struct dwarf2_cu *cu)
11905 {
11906   struct objfile *objfile = dwarf2_per_objfile->objfile;
11907   struct dwarf2_locexpr_baton *baton;
11908   gdb_byte *ptr;
11909   unsigned int cu_off;
11910   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
11911   LONGEST offset = 0;
11912
11913   gdb_assert (common_loc && member_loc);
11914   gdb_assert (attr_form_is_block (common_loc));
11915   gdb_assert (attr_form_is_block (member_loc)
11916               || attr_form_is_constant (member_loc));
11917
11918   baton = obstack_alloc (&objfile->objfile_obstack,
11919                          sizeof (struct dwarf2_locexpr_baton));
11920   baton->per_cu = cu->per_cu;
11921   gdb_assert (baton->per_cu);
11922
11923   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
11924
11925   if (attr_form_is_constant (member_loc))
11926     {
11927       offset = dwarf2_get_attr_constant_value (member_loc, 0);
11928       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
11929     }
11930   else
11931     baton->size += DW_BLOCK (member_loc)->size;
11932
11933   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
11934   baton->data = ptr;
11935
11936   *ptr++ = DW_OP_call4;
11937   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
11938   store_unsigned_integer (ptr, 4, byte_order, cu_off);
11939   ptr += 4;
11940
11941   if (attr_form_is_constant (member_loc))
11942     {
11943       *ptr++ = DW_OP_addr;
11944       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
11945       ptr += cu->header.addr_size;
11946     }
11947   else
11948     {
11949       /* We have to copy the data here, because DW_OP_call4 will only
11950          use a DW_AT_location attribute.  */
11951       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
11952       ptr += DW_BLOCK (member_loc)->size;
11953     }
11954
11955   *ptr++ = DW_OP_plus;
11956   gdb_assert (ptr - baton->data == baton->size);
11957
11958   SYMBOL_LOCATION_BATON (sym) = baton;
11959   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
11960 }
11961
11962 /* Create appropriate locally-scoped variables for all the
11963    DW_TAG_common_block entries.  Also create a struct common_block
11964    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
11965    is used to sepate the common blocks name namespace from regular
11966    variable names.  */
11967
11968 static void
11969 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
11970 {
11971   struct attribute *attr;
11972
11973   attr = dwarf2_attr (die, DW_AT_location, cu);
11974   if (attr)
11975     {
11976       /* Support the .debug_loc offsets.  */
11977       if (attr_form_is_block (attr))
11978         {
11979           /* Ok.  */
11980         }
11981       else if (attr_form_is_section_offset (attr))
11982         {
11983           dwarf2_complex_location_expr_complaint ();
11984           attr = NULL;
11985         }
11986       else
11987         {
11988           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
11989                                                  "common block member");
11990           attr = NULL;
11991         }
11992     }
11993
11994   if (die->child != NULL)
11995     {
11996       struct objfile *objfile = cu->objfile;
11997       struct die_info *child_die;
11998       size_t n_entries = 0, size;
11999       struct common_block *common_block;
12000       struct symbol *sym;
12001
12002       for (child_die = die->child;
12003            child_die && child_die->tag;
12004            child_die = sibling_die (child_die))
12005         ++n_entries;
12006
12007       size = (sizeof (struct common_block)
12008               + (n_entries - 1) * sizeof (struct symbol *));
12009       common_block = obstack_alloc (&objfile->objfile_obstack, size);
12010       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
12011       common_block->n_entries = 0;
12012
12013       for (child_die = die->child;
12014            child_die && child_die->tag;
12015            child_die = sibling_die (child_die))
12016         {
12017           /* Create the symbol in the DW_TAG_common_block block in the current
12018              symbol scope.  */
12019           sym = new_symbol (child_die, NULL, cu);
12020           if (sym != NULL)
12021             {
12022               struct attribute *member_loc;
12023
12024               common_block->contents[common_block->n_entries++] = sym;
12025
12026               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
12027                                         cu);
12028               if (member_loc)
12029                 {
12030                   /* GDB has handled this for a long time, but it is
12031                      not specified by DWARF.  It seems to have been
12032                      emitted by gfortran at least as recently as:
12033                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
12034                   complaint (&symfile_complaints,
12035                              _("Variable in common block has "
12036                                "DW_AT_data_member_location "
12037                                "- DIE at 0x%x [in module %s]"),
12038                              child_die->offset.sect_off, cu->objfile->name);
12039
12040                   if (attr_form_is_section_offset (member_loc))
12041                     dwarf2_complex_location_expr_complaint ();
12042                   else if (attr_form_is_constant (member_loc)
12043                            || attr_form_is_block (member_loc))
12044                     {
12045                       if (attr)
12046                         mark_common_block_symbol_computed (sym, die, attr,
12047                                                            member_loc, cu);
12048                     }
12049                   else
12050                     dwarf2_complex_location_expr_complaint ();
12051                 }
12052             }
12053         }
12054
12055       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
12056       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
12057     }
12058 }
12059
12060 /* Create a type for a C++ namespace.  */
12061
12062 static struct type *
12063 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
12064 {
12065   struct objfile *objfile = cu->objfile;
12066   const char *previous_prefix, *name;
12067   int is_anonymous;
12068   struct type *type;
12069
12070   /* For extensions, reuse the type of the original namespace.  */
12071   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
12072     {
12073       struct die_info *ext_die;
12074       struct dwarf2_cu *ext_cu = cu;
12075
12076       ext_die = dwarf2_extension (die, &ext_cu);
12077       type = read_type_die (ext_die, ext_cu);
12078
12079       /* EXT_CU may not be the same as CU.
12080          Ensure TYPE is recorded in CU's type_hash table.  */
12081       return set_die_type (die, type, cu);
12082     }
12083
12084   name = namespace_name (die, &is_anonymous, cu);
12085
12086   /* Now build the name of the current namespace.  */
12087
12088   previous_prefix = determine_prefix (die, cu);
12089   if (previous_prefix[0] != '\0')
12090     name = typename_concat (&objfile->objfile_obstack,
12091                             previous_prefix, name, 0, cu);
12092
12093   /* Create the type.  */
12094   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
12095                     objfile);
12096   TYPE_NAME (type) = name;
12097   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12098
12099   return set_die_type (die, type, cu);
12100 }
12101
12102 /* Read a C++ namespace.  */
12103
12104 static void
12105 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
12106 {
12107   struct objfile *objfile = cu->objfile;
12108   int is_anonymous;
12109
12110   /* Add a symbol associated to this if we haven't seen the namespace
12111      before.  Also, add a using directive if it's an anonymous
12112      namespace.  */
12113
12114   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
12115     {
12116       struct type *type;
12117
12118       type = read_type_die (die, cu);
12119       new_symbol (die, type, cu);
12120
12121       namespace_name (die, &is_anonymous, cu);
12122       if (is_anonymous)
12123         {
12124           const char *previous_prefix = determine_prefix (die, cu);
12125
12126           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
12127                                   NULL, NULL, 0, &objfile->objfile_obstack);
12128         }
12129     }
12130
12131   if (die->child != NULL)
12132     {
12133       struct die_info *child_die = die->child;
12134
12135       while (child_die && child_die->tag)
12136         {
12137           process_die (child_die, cu);
12138           child_die = sibling_die (child_die);
12139         }
12140     }
12141 }
12142
12143 /* Read a Fortran module as type.  This DIE can be only a declaration used for
12144    imported module.  Still we need that type as local Fortran "use ... only"
12145    declaration imports depend on the created type in determine_prefix.  */
12146
12147 static struct type *
12148 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
12149 {
12150   struct objfile *objfile = cu->objfile;
12151   const char *module_name;
12152   struct type *type;
12153
12154   module_name = dwarf2_name (die, cu);
12155   if (!module_name)
12156     complaint (&symfile_complaints,
12157                _("DW_TAG_module has no name, offset 0x%x"),
12158                die->offset.sect_off);
12159   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
12160
12161   /* determine_prefix uses TYPE_TAG_NAME.  */
12162   TYPE_TAG_NAME (type) = TYPE_NAME (type);
12163
12164   return set_die_type (die, type, cu);
12165 }
12166
12167 /* Read a Fortran module.  */
12168
12169 static void
12170 read_module (struct die_info *die, struct dwarf2_cu *cu)
12171 {
12172   struct die_info *child_die = die->child;
12173
12174   while (child_die && child_die->tag)
12175     {
12176       process_die (child_die, cu);
12177       child_die = sibling_die (child_die);
12178     }
12179 }
12180
12181 /* Return the name of the namespace represented by DIE.  Set
12182    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
12183    namespace.  */
12184
12185 static const char *
12186 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
12187 {
12188   struct die_info *current_die;
12189   const char *name = NULL;
12190
12191   /* Loop through the extensions until we find a name.  */
12192
12193   for (current_die = die;
12194        current_die != NULL;
12195        current_die = dwarf2_extension (die, &cu))
12196     {
12197       name = dwarf2_name (current_die, cu);
12198       if (name != NULL)
12199         break;
12200     }
12201
12202   /* Is it an anonymous namespace?  */
12203
12204   *is_anonymous = (name == NULL);
12205   if (*is_anonymous)
12206     name = CP_ANONYMOUS_NAMESPACE_STR;
12207
12208   return name;
12209 }
12210
12211 /* Extract all information from a DW_TAG_pointer_type DIE and add to
12212    the user defined type vector.  */
12213
12214 static struct type *
12215 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
12216 {
12217   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
12218   struct comp_unit_head *cu_header = &cu->header;
12219   struct type *type;
12220   struct attribute *attr_byte_size;
12221   struct attribute *attr_address_class;
12222   int byte_size, addr_class;
12223   struct type *target_type;
12224
12225   target_type = die_type (die, cu);
12226
12227   /* The die_type call above may have already set the type for this DIE.  */
12228   type = get_die_type (die, cu);
12229   if (type)
12230     return type;
12231
12232   type = lookup_pointer_type (target_type);
12233
12234   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
12235   if (attr_byte_size)
12236     byte_size = DW_UNSND (attr_byte_size);
12237   else
12238     byte_size = cu_header->addr_size;
12239
12240   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
12241   if (attr_address_class)
12242     addr_class = DW_UNSND (attr_address_class);
12243   else
12244     addr_class = DW_ADDR_none;
12245
12246   /* If the pointer size or address class is different than the
12247      default, create a type variant marked as such and set the
12248      length accordingly.  */
12249   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
12250     {
12251       if (gdbarch_address_class_type_flags_p (gdbarch))
12252         {
12253           int type_flags;
12254
12255           type_flags = gdbarch_address_class_type_flags
12256                          (gdbarch, byte_size, addr_class);
12257           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
12258                       == 0);
12259           type = make_type_with_address_space (type, type_flags);
12260         }
12261       else if (TYPE_LENGTH (type) != byte_size)
12262         {
12263           complaint (&symfile_complaints,
12264                      _("invalid pointer size %d"), byte_size);
12265         }
12266       else
12267         {
12268           /* Should we also complain about unhandled address classes?  */
12269         }
12270     }
12271
12272   TYPE_LENGTH (type) = byte_size;
12273   return set_die_type (die, type, cu);
12274 }
12275
12276 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
12277    the user defined type vector.  */
12278
12279 static struct type *
12280 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
12281 {
12282   struct type *type;
12283   struct type *to_type;
12284   struct type *domain;
12285
12286   to_type = die_type (die, cu);
12287   domain = die_containing_type (die, cu);
12288
12289   /* The calls above may have already set the type for this DIE.  */
12290   type = get_die_type (die, cu);
12291   if (type)
12292     return type;
12293
12294   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
12295     type = lookup_methodptr_type (to_type);
12296   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
12297     {
12298       struct type *new_type = alloc_type (cu->objfile);
12299
12300       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
12301                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
12302                             TYPE_VARARGS (to_type));
12303       type = lookup_methodptr_type (new_type);
12304     }
12305   else
12306     type = lookup_memberptr_type (to_type, domain);
12307
12308   return set_die_type (die, type, cu);
12309 }
12310
12311 /* Extract all information from a DW_TAG_reference_type DIE and add to
12312    the user defined type vector.  */
12313
12314 static struct type *
12315 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
12316 {
12317   struct comp_unit_head *cu_header = &cu->header;
12318   struct type *type, *target_type;
12319   struct attribute *attr;
12320
12321   target_type = die_type (die, cu);
12322
12323   /* The die_type call above may have already set the type for this DIE.  */
12324   type = get_die_type (die, cu);
12325   if (type)
12326     return type;
12327
12328   type = lookup_reference_type (target_type);
12329   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12330   if (attr)
12331     {
12332       TYPE_LENGTH (type) = DW_UNSND (attr);
12333     }
12334   else
12335     {
12336       TYPE_LENGTH (type) = cu_header->addr_size;
12337     }
12338   return set_die_type (die, type, cu);
12339 }
12340
12341 static struct type *
12342 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
12343 {
12344   struct type *base_type, *cv_type;
12345
12346   base_type = die_type (die, cu);
12347
12348   /* The die_type call above may have already set the type for this DIE.  */
12349   cv_type = get_die_type (die, cu);
12350   if (cv_type)
12351     return cv_type;
12352
12353   /* In case the const qualifier is applied to an array type, the element type
12354      is so qualified, not the array type (section 6.7.3 of C99).  */
12355   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
12356     {
12357       struct type *el_type, *inner_array;
12358
12359       base_type = copy_type (base_type);
12360       inner_array = base_type;
12361
12362       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
12363         {
12364           TYPE_TARGET_TYPE (inner_array) =
12365             copy_type (TYPE_TARGET_TYPE (inner_array));
12366           inner_array = TYPE_TARGET_TYPE (inner_array);
12367         }
12368
12369       el_type = TYPE_TARGET_TYPE (inner_array);
12370       TYPE_TARGET_TYPE (inner_array) =
12371         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
12372
12373       return set_die_type (die, base_type, cu);
12374     }
12375
12376   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
12377   return set_die_type (die, cv_type, cu);
12378 }
12379
12380 static struct type *
12381 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
12382 {
12383   struct type *base_type, *cv_type;
12384
12385   base_type = die_type (die, cu);
12386
12387   /* The die_type call above may have already set the type for this DIE.  */
12388   cv_type = get_die_type (die, cu);
12389   if (cv_type)
12390     return cv_type;
12391
12392   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
12393   return set_die_type (die, cv_type, cu);
12394 }
12395
12396 /* Handle DW_TAG_restrict_type.  */
12397
12398 static struct type *
12399 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
12400 {
12401   struct type *base_type, *cv_type;
12402
12403   base_type = die_type (die, cu);
12404
12405   /* The die_type call above may have already set the type for this DIE.  */
12406   cv_type = get_die_type (die, cu);
12407   if (cv_type)
12408     return cv_type;
12409
12410   cv_type = make_restrict_type (base_type);
12411   return set_die_type (die, cv_type, cu);
12412 }
12413
12414 /* Extract all information from a DW_TAG_string_type DIE and add to
12415    the user defined type vector.  It isn't really a user defined type,
12416    but it behaves like one, with other DIE's using an AT_user_def_type
12417    attribute to reference it.  */
12418
12419 static struct type *
12420 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
12421 {
12422   struct objfile *objfile = cu->objfile;
12423   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12424   struct type *type, *range_type, *index_type, *char_type;
12425   struct attribute *attr;
12426   unsigned int length;
12427
12428   attr = dwarf2_attr (die, DW_AT_string_length, cu);
12429   if (attr)
12430     {
12431       length = DW_UNSND (attr);
12432     }
12433   else
12434     {
12435       /* Check for the DW_AT_byte_size attribute.  */
12436       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12437       if (attr)
12438         {
12439           length = DW_UNSND (attr);
12440         }
12441       else
12442         {
12443           length = 1;
12444         }
12445     }
12446
12447   index_type = objfile_type (objfile)->builtin_int;
12448   range_type = create_range_type (NULL, index_type, 1, length);
12449   char_type = language_string_char_type (cu->language_defn, gdbarch);
12450   type = create_string_type (NULL, char_type, range_type);
12451
12452   return set_die_type (die, type, cu);
12453 }
12454
12455 /* Handle DIES due to C code like:
12456
12457    struct foo
12458    {
12459    int (*funcp)(int a, long l);
12460    int b;
12461    };
12462
12463    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
12464
12465 static struct type *
12466 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
12467 {
12468   struct objfile *objfile = cu->objfile;
12469   struct type *type;            /* Type that this function returns.  */
12470   struct type *ftype;           /* Function that returns above type.  */
12471   struct attribute *attr;
12472
12473   type = die_type (die, cu);
12474
12475   /* The die_type call above may have already set the type for this DIE.  */
12476   ftype = get_die_type (die, cu);
12477   if (ftype)
12478     return ftype;
12479
12480   ftype = lookup_function_type (type);
12481
12482   /* All functions in C++, Pascal and Java have prototypes.  */
12483   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
12484   if ((attr && (DW_UNSND (attr) != 0))
12485       || cu->language == language_cplus
12486       || cu->language == language_java
12487       || cu->language == language_pascal)
12488     TYPE_PROTOTYPED (ftype) = 1;
12489   else if (producer_is_realview (cu->producer))
12490     /* RealView does not emit DW_AT_prototyped.  We can not
12491        distinguish prototyped and unprototyped functions; default to
12492        prototyped, since that is more common in modern code (and
12493        RealView warns about unprototyped functions).  */
12494     TYPE_PROTOTYPED (ftype) = 1;
12495
12496   /* Store the calling convention in the type if it's available in
12497      the subroutine die.  Otherwise set the calling convention to
12498      the default value DW_CC_normal.  */
12499   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
12500   if (attr)
12501     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
12502   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
12503     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
12504   else
12505     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
12506
12507   /* We need to add the subroutine type to the die immediately so
12508      we don't infinitely recurse when dealing with parameters
12509      declared as the same subroutine type.  */
12510   set_die_type (die, ftype, cu);
12511
12512   if (die->child != NULL)
12513     {
12514       struct type *void_type = objfile_type (objfile)->builtin_void;
12515       struct die_info *child_die;
12516       int nparams, iparams;
12517
12518       /* Count the number of parameters.
12519          FIXME: GDB currently ignores vararg functions, but knows about
12520          vararg member functions.  */
12521       nparams = 0;
12522       child_die = die->child;
12523       while (child_die && child_die->tag)
12524         {
12525           if (child_die->tag == DW_TAG_formal_parameter)
12526             nparams++;
12527           else if (child_die->tag == DW_TAG_unspecified_parameters)
12528             TYPE_VARARGS (ftype) = 1;
12529           child_die = sibling_die (child_die);
12530         }
12531
12532       /* Allocate storage for parameters and fill them in.  */
12533       TYPE_NFIELDS (ftype) = nparams;
12534       TYPE_FIELDS (ftype) = (struct field *)
12535         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
12536
12537       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
12538          even if we error out during the parameters reading below.  */
12539       for (iparams = 0; iparams < nparams; iparams++)
12540         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
12541
12542       iparams = 0;
12543       child_die = die->child;
12544       while (child_die && child_die->tag)
12545         {
12546           if (child_die->tag == DW_TAG_formal_parameter)
12547             {
12548               struct type *arg_type;
12549
12550               /* DWARF version 2 has no clean way to discern C++
12551                  static and non-static member functions.  G++ helps
12552                  GDB by marking the first parameter for non-static
12553                  member functions (which is the this pointer) as
12554                  artificial.  We pass this information to
12555                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
12556
12557                  DWARF version 3 added DW_AT_object_pointer, which GCC
12558                  4.5 does not yet generate.  */
12559               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
12560               if (attr)
12561                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
12562               else
12563                 {
12564                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
12565
12566                   /* GCC/43521: In java, the formal parameter
12567                      "this" is sometimes not marked with DW_AT_artificial.  */
12568                   if (cu->language == language_java)
12569                     {
12570                       const char *name = dwarf2_name (child_die, cu);
12571
12572                       if (name && !strcmp (name, "this"))
12573                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
12574                     }
12575                 }
12576               arg_type = die_type (child_die, cu);
12577
12578               /* RealView does not mark THIS as const, which the testsuite
12579                  expects.  GCC marks THIS as const in method definitions,
12580                  but not in the class specifications (GCC PR 43053).  */
12581               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
12582                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
12583                 {
12584                   int is_this = 0;
12585                   struct dwarf2_cu *arg_cu = cu;
12586                   const char *name = dwarf2_name (child_die, cu);
12587
12588                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
12589                   if (attr)
12590                     {
12591                       /* If the compiler emits this, use it.  */
12592                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
12593                         is_this = 1;
12594                     }
12595                   else if (name && strcmp (name, "this") == 0)
12596                     /* Function definitions will have the argument names.  */
12597                     is_this = 1;
12598                   else if (name == NULL && iparams == 0)
12599                     /* Declarations may not have the names, so like
12600                        elsewhere in GDB, assume an artificial first
12601                        argument is "this".  */
12602                     is_this = 1;
12603
12604                   if (is_this)
12605                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
12606                                              arg_type, 0);
12607                 }
12608
12609               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
12610               iparams++;
12611             }
12612           child_die = sibling_die (child_die);
12613         }
12614     }
12615
12616   return ftype;
12617 }
12618
12619 static struct type *
12620 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
12621 {
12622   struct objfile *objfile = cu->objfile;
12623   const char *name = NULL;
12624   struct type *this_type, *target_type;
12625
12626   name = dwarf2_full_name (NULL, die, cu);
12627   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
12628                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
12629   TYPE_NAME (this_type) = name;
12630   set_die_type (die, this_type, cu);
12631   target_type = die_type (die, cu);
12632   if (target_type != this_type)
12633     TYPE_TARGET_TYPE (this_type) = target_type;
12634   else
12635     {
12636       /* Self-referential typedefs are, it seems, not allowed by the DWARF
12637          spec and cause infinite loops in GDB.  */
12638       complaint (&symfile_complaints,
12639                  _("Self-referential DW_TAG_typedef "
12640                    "- DIE at 0x%x [in module %s]"),
12641                  die->offset.sect_off, objfile->name);
12642       TYPE_TARGET_TYPE (this_type) = NULL;
12643     }
12644   return this_type;
12645 }
12646
12647 /* Find a representation of a given base type and install
12648    it in the TYPE field of the die.  */
12649
12650 static struct type *
12651 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
12652 {
12653   struct objfile *objfile = cu->objfile;
12654   struct type *type;
12655   struct attribute *attr;
12656   int encoding = 0, size = 0;
12657   const char *name;
12658   enum type_code code = TYPE_CODE_INT;
12659   int type_flags = 0;
12660   struct type *target_type = NULL;
12661
12662   attr = dwarf2_attr (die, DW_AT_encoding, cu);
12663   if (attr)
12664     {
12665       encoding = DW_UNSND (attr);
12666     }
12667   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12668   if (attr)
12669     {
12670       size = DW_UNSND (attr);
12671     }
12672   name = dwarf2_name (die, cu);
12673   if (!name)
12674     {
12675       complaint (&symfile_complaints,
12676                  _("DW_AT_name missing from DW_TAG_base_type"));
12677     }
12678
12679   switch (encoding)
12680     {
12681       case DW_ATE_address:
12682         /* Turn DW_ATE_address into a void * pointer.  */
12683         code = TYPE_CODE_PTR;
12684         type_flags |= TYPE_FLAG_UNSIGNED;
12685         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
12686         break;
12687       case DW_ATE_boolean:
12688         code = TYPE_CODE_BOOL;
12689         type_flags |= TYPE_FLAG_UNSIGNED;
12690         break;
12691       case DW_ATE_complex_float:
12692         code = TYPE_CODE_COMPLEX;
12693         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
12694         break;
12695       case DW_ATE_decimal_float:
12696         code = TYPE_CODE_DECFLOAT;
12697         break;
12698       case DW_ATE_float:
12699         code = TYPE_CODE_FLT;
12700         break;
12701       case DW_ATE_signed:
12702         break;
12703       case DW_ATE_unsigned:
12704         type_flags |= TYPE_FLAG_UNSIGNED;
12705         if (cu->language == language_fortran
12706             && name
12707             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
12708           code = TYPE_CODE_CHAR;
12709         break;
12710       case DW_ATE_signed_char:
12711         if (cu->language == language_ada || cu->language == language_m2
12712             || cu->language == language_pascal
12713             || cu->language == language_fortran)
12714           code = TYPE_CODE_CHAR;
12715         break;
12716       case DW_ATE_unsigned_char:
12717         if (cu->language == language_ada || cu->language == language_m2
12718             || cu->language == language_pascal
12719             || cu->language == language_fortran)
12720           code = TYPE_CODE_CHAR;
12721         type_flags |= TYPE_FLAG_UNSIGNED;
12722         break;
12723       case DW_ATE_UTF:
12724         /* We just treat this as an integer and then recognize the
12725            type by name elsewhere.  */
12726         break;
12727
12728       default:
12729         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
12730                    dwarf_type_encoding_name (encoding));
12731         break;
12732     }
12733
12734   type = init_type (code, size, type_flags, NULL, objfile);
12735   TYPE_NAME (type) = name;
12736   TYPE_TARGET_TYPE (type) = target_type;
12737
12738   if (name && strcmp (name, "char") == 0)
12739     TYPE_NOSIGN (type) = 1;
12740
12741   return set_die_type (die, type, cu);
12742 }
12743
12744 /* Read the given DW_AT_subrange DIE.  */
12745
12746 static struct type *
12747 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
12748 {
12749   struct type *base_type, *orig_base_type;
12750   struct type *range_type;
12751   struct attribute *attr;
12752   LONGEST low, high;
12753   int low_default_is_valid;
12754   const char *name;
12755   LONGEST negative_mask;
12756
12757   orig_base_type = die_type (die, cu);
12758   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
12759      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
12760      creating the range type, but we use the result of check_typedef
12761      when examining properties of the type.  */
12762   base_type = check_typedef (orig_base_type);
12763
12764   /* The die_type call above may have already set the type for this DIE.  */
12765   range_type = get_die_type (die, cu);
12766   if (range_type)
12767     return range_type;
12768
12769   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
12770      omitting DW_AT_lower_bound.  */
12771   switch (cu->language)
12772     {
12773     case language_c:
12774     case language_cplus:
12775       low = 0;
12776       low_default_is_valid = 1;
12777       break;
12778     case language_fortran:
12779       low = 1;
12780       low_default_is_valid = 1;
12781       break;
12782     case language_d:
12783     case language_java:
12784     case language_objc:
12785       low = 0;
12786       low_default_is_valid = (cu->header.version >= 4);
12787       break;
12788     case language_ada:
12789     case language_m2:
12790     case language_pascal:
12791       low = 1;
12792       low_default_is_valid = (cu->header.version >= 4);
12793       break;
12794     default:
12795       low = 0;
12796       low_default_is_valid = 0;
12797       break;
12798     }
12799
12800   /* FIXME: For variable sized arrays either of these could be
12801      a variable rather than a constant value.  We'll allow it,
12802      but we don't know how to handle it.  */
12803   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
12804   if (attr)
12805     low = dwarf2_get_attr_constant_value (attr, low);
12806   else if (!low_default_is_valid)
12807     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
12808                                       "- DIE at 0x%x [in module %s]"),
12809                die->offset.sect_off, cu->objfile->name);
12810
12811   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
12812   if (attr)
12813     {
12814       if (attr_form_is_block (attr) || is_ref_attr (attr))
12815         {
12816           /* GCC encodes arrays with unspecified or dynamic length
12817              with a DW_FORM_block1 attribute or a reference attribute.
12818              FIXME: GDB does not yet know how to handle dynamic
12819              arrays properly, treat them as arrays with unspecified
12820              length for now.
12821
12822              FIXME: jimb/2003-09-22: GDB does not really know
12823              how to handle arrays of unspecified length
12824              either; we just represent them as zero-length
12825              arrays.  Choose an appropriate upper bound given
12826              the lower bound we've computed above.  */
12827           high = low - 1;
12828         }
12829       else
12830         high = dwarf2_get_attr_constant_value (attr, 1);
12831     }
12832   else
12833     {
12834       attr = dwarf2_attr (die, DW_AT_count, cu);
12835       if (attr)
12836         {
12837           int count = dwarf2_get_attr_constant_value (attr, 1);
12838           high = low + count - 1;
12839         }
12840       else
12841         {
12842           /* Unspecified array length.  */
12843           high = low - 1;
12844         }
12845     }
12846
12847   /* Dwarf-2 specifications explicitly allows to create subrange types
12848      without specifying a base type.
12849      In that case, the base type must be set to the type of
12850      the lower bound, upper bound or count, in that order, if any of these
12851      three attributes references an object that has a type.
12852      If no base type is found, the Dwarf-2 specifications say that
12853      a signed integer type of size equal to the size of an address should
12854      be used.
12855      For the following C code: `extern char gdb_int [];'
12856      GCC produces an empty range DIE.
12857      FIXME: muller/2010-05-28: Possible references to object for low bound,
12858      high bound or count are not yet handled by this code.  */
12859   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
12860     {
12861       struct objfile *objfile = cu->objfile;
12862       struct gdbarch *gdbarch = get_objfile_arch (objfile);
12863       int addr_size = gdbarch_addr_bit (gdbarch) /8;
12864       struct type *int_type = objfile_type (objfile)->builtin_int;
12865
12866       /* Test "int", "long int", and "long long int" objfile types,
12867          and select the first one having a size above or equal to the
12868          architecture address size.  */
12869       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12870         base_type = int_type;
12871       else
12872         {
12873           int_type = objfile_type (objfile)->builtin_long;
12874           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12875             base_type = int_type;
12876           else
12877             {
12878               int_type = objfile_type (objfile)->builtin_long_long;
12879               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
12880                 base_type = int_type;
12881             }
12882         }
12883     }
12884
12885   negative_mask =
12886     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
12887   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
12888     low |= negative_mask;
12889   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
12890     high |= negative_mask;
12891
12892   range_type = create_range_type (NULL, orig_base_type, low, high);
12893
12894   /* Mark arrays with dynamic length at least as an array of unspecified
12895      length.  GDB could check the boundary but before it gets implemented at
12896      least allow accessing the array elements.  */
12897   if (attr && attr_form_is_block (attr))
12898     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12899
12900   /* Ada expects an empty array on no boundary attributes.  */
12901   if (attr == NULL && cu->language != language_ada)
12902     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
12903
12904   name = dwarf2_name (die, cu);
12905   if (name)
12906     TYPE_NAME (range_type) = name;
12907
12908   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12909   if (attr)
12910     TYPE_LENGTH (range_type) = DW_UNSND (attr);
12911
12912   set_die_type (die, range_type, cu);
12913
12914   /* set_die_type should be already done.  */
12915   set_descriptive_type (range_type, die, cu);
12916
12917   return range_type;
12918 }
12919
12920 static struct type *
12921 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
12922 {
12923   struct type *type;
12924
12925   /* For now, we only support the C meaning of an unspecified type: void.  */
12926
12927   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
12928   TYPE_NAME (type) = dwarf2_name (die, cu);
12929
12930   return set_die_type (die, type, cu);
12931 }
12932
12933 /* Read a single die and all its descendents.  Set the die's sibling
12934    field to NULL; set other fields in the die correctly, and set all
12935    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
12936    location of the info_ptr after reading all of those dies.  PARENT
12937    is the parent of the die in question.  */
12938
12939 static struct die_info *
12940 read_die_and_children (const struct die_reader_specs *reader,
12941                        gdb_byte *info_ptr,
12942                        gdb_byte **new_info_ptr,
12943                        struct die_info *parent)
12944 {
12945   struct die_info *die;
12946   gdb_byte *cur_ptr;
12947   int has_children;
12948
12949   cur_ptr = read_full_die (reader, &die, info_ptr, &has_children);
12950   if (die == NULL)
12951     {
12952       *new_info_ptr = cur_ptr;
12953       return NULL;
12954     }
12955   store_in_ref_table (die, reader->cu);
12956
12957   if (has_children)
12958     die->child = read_die_and_siblings (reader, cur_ptr, new_info_ptr, die);
12959   else
12960     {
12961       die->child = NULL;
12962       *new_info_ptr = cur_ptr;
12963     }
12964
12965   die->sibling = NULL;
12966   die->parent = parent;
12967   return die;
12968 }
12969
12970 /* Read a die, all of its descendents, and all of its siblings; set
12971    all of the fields of all of the dies correctly.  Arguments are as
12972    in read_die_and_children.  */
12973
12974 static struct die_info *
12975 read_die_and_siblings (const struct die_reader_specs *reader,
12976                        gdb_byte *info_ptr,
12977                        gdb_byte **new_info_ptr,
12978                        struct die_info *parent)
12979 {
12980   struct die_info *first_die, *last_sibling;
12981   gdb_byte *cur_ptr;
12982
12983   cur_ptr = info_ptr;
12984   first_die = last_sibling = NULL;
12985
12986   while (1)
12987     {
12988       struct die_info *die
12989         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
12990
12991       if (die == NULL)
12992         {
12993           *new_info_ptr = cur_ptr;
12994           return first_die;
12995         }
12996
12997       if (!first_die)
12998         first_die = die;
12999       else
13000         last_sibling->sibling = die;
13001
13002       last_sibling = die;
13003     }
13004 }
13005
13006 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
13007    attributes.
13008    The caller is responsible for filling in the extra attributes
13009    and updating (*DIEP)->num_attrs.
13010    Set DIEP to point to a newly allocated die with its information,
13011    except for its child, sibling, and parent fields.
13012    Set HAS_CHILDREN to tell whether the die has children or not.  */
13013
13014 static gdb_byte *
13015 read_full_die_1 (const struct die_reader_specs *reader,
13016                  struct die_info **diep, gdb_byte *info_ptr,
13017                  int *has_children, int num_extra_attrs)
13018 {
13019   unsigned int abbrev_number, bytes_read, i;
13020   sect_offset offset;
13021   struct abbrev_info *abbrev;
13022   struct die_info *die;
13023   struct dwarf2_cu *cu = reader->cu;
13024   bfd *abfd = reader->abfd;
13025
13026   offset.sect_off = info_ptr - reader->buffer;
13027   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
13028   info_ptr += bytes_read;
13029   if (!abbrev_number)
13030     {
13031       *diep = NULL;
13032       *has_children = 0;
13033       return info_ptr;
13034     }
13035
13036   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
13037   if (!abbrev)
13038     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
13039            abbrev_number,
13040            bfd_get_filename (abfd));
13041
13042   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
13043   die->offset = offset;
13044   die->tag = abbrev->tag;
13045   die->abbrev = abbrev_number;
13046
13047   /* Make the result usable.
13048      The caller needs to update num_attrs after adding the extra
13049      attributes.  */
13050   die->num_attrs = abbrev->num_attrs;
13051
13052   for (i = 0; i < abbrev->num_attrs; ++i)
13053     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
13054                                info_ptr);
13055
13056   *diep = die;
13057   *has_children = abbrev->has_children;
13058   return info_ptr;
13059 }
13060
13061 /* Read a die and all its attributes.
13062    Set DIEP to point to a newly allocated die with its information,
13063    except for its child, sibling, and parent fields.
13064    Set HAS_CHILDREN to tell whether the die has children or not.  */
13065
13066 static gdb_byte *
13067 read_full_die (const struct die_reader_specs *reader,
13068                struct die_info **diep, gdb_byte *info_ptr,
13069                int *has_children)
13070 {
13071   return read_full_die_1 (reader, diep, info_ptr, has_children, 0);
13072 }
13073 \f
13074 /* Abbreviation tables.
13075
13076    In DWARF version 2, the description of the debugging information is
13077    stored in a separate .debug_abbrev section.  Before we read any
13078    dies from a section we read in all abbreviations and install them
13079    in a hash table.  */
13080
13081 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
13082
13083 static struct abbrev_info *
13084 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
13085 {
13086   struct abbrev_info *abbrev;
13087
13088   abbrev = (struct abbrev_info *)
13089     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
13090   memset (abbrev, 0, sizeof (struct abbrev_info));
13091   return abbrev;
13092 }
13093
13094 /* Add an abbreviation to the table.  */
13095
13096 static void
13097 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
13098                          unsigned int abbrev_number,
13099                          struct abbrev_info *abbrev)
13100 {
13101   unsigned int hash_number;
13102
13103   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13104   abbrev->next = abbrev_table->abbrevs[hash_number];
13105   abbrev_table->abbrevs[hash_number] = abbrev;
13106 }
13107
13108 /* Look up an abbrev in the table.
13109    Returns NULL if the abbrev is not found.  */
13110
13111 static struct abbrev_info *
13112 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
13113                             unsigned int abbrev_number)
13114 {
13115   unsigned int hash_number;
13116   struct abbrev_info *abbrev;
13117
13118   hash_number = abbrev_number % ABBREV_HASH_SIZE;
13119   abbrev = abbrev_table->abbrevs[hash_number];
13120
13121   while (abbrev)
13122     {
13123       if (abbrev->number == abbrev_number)
13124         return abbrev;
13125       abbrev = abbrev->next;
13126     }
13127   return NULL;
13128 }
13129
13130 /* Read in an abbrev table.  */
13131
13132 static struct abbrev_table *
13133 abbrev_table_read_table (struct dwarf2_section_info *section,
13134                          sect_offset offset)
13135 {
13136   struct objfile *objfile = dwarf2_per_objfile->objfile;
13137   bfd *abfd = section->asection->owner;
13138   struct abbrev_table *abbrev_table;
13139   gdb_byte *abbrev_ptr;
13140   struct abbrev_info *cur_abbrev;
13141   unsigned int abbrev_number, bytes_read, abbrev_name;
13142   unsigned int abbrev_form;
13143   struct attr_abbrev *cur_attrs;
13144   unsigned int allocated_attrs;
13145
13146   abbrev_table = XMALLOC (struct abbrev_table);
13147   abbrev_table->offset = offset;
13148   obstack_init (&abbrev_table->abbrev_obstack);
13149   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
13150                                          (ABBREV_HASH_SIZE
13151                                           * sizeof (struct abbrev_info *)));
13152   memset (abbrev_table->abbrevs, 0,
13153           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
13154
13155   dwarf2_read_section (objfile, section);
13156   abbrev_ptr = section->buffer + offset.sect_off;
13157   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13158   abbrev_ptr += bytes_read;
13159
13160   allocated_attrs = ATTR_ALLOC_CHUNK;
13161   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
13162
13163   /* Loop until we reach an abbrev number of 0.  */
13164   while (abbrev_number)
13165     {
13166       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
13167
13168       /* read in abbrev header */
13169       cur_abbrev->number = abbrev_number;
13170       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13171       abbrev_ptr += bytes_read;
13172       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
13173       abbrev_ptr += 1;
13174
13175       /* now read in declarations */
13176       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13177       abbrev_ptr += bytes_read;
13178       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13179       abbrev_ptr += bytes_read;
13180       while (abbrev_name)
13181         {
13182           if (cur_abbrev->num_attrs == allocated_attrs)
13183             {
13184               allocated_attrs += ATTR_ALLOC_CHUNK;
13185               cur_attrs
13186                 = xrealloc (cur_attrs, (allocated_attrs
13187                                         * sizeof (struct attr_abbrev)));
13188             }
13189
13190           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
13191           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
13192           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13193           abbrev_ptr += bytes_read;
13194           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13195           abbrev_ptr += bytes_read;
13196         }
13197
13198       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
13199                                          (cur_abbrev->num_attrs
13200                                           * sizeof (struct attr_abbrev)));
13201       memcpy (cur_abbrev->attrs, cur_attrs,
13202               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
13203
13204       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
13205
13206       /* Get next abbreviation.
13207          Under Irix6 the abbreviations for a compilation unit are not
13208          always properly terminated with an abbrev number of 0.
13209          Exit loop if we encounter an abbreviation which we have
13210          already read (which means we are about to read the abbreviations
13211          for the next compile unit) or if the end of the abbreviation
13212          table is reached.  */
13213       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
13214         break;
13215       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
13216       abbrev_ptr += bytes_read;
13217       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
13218         break;
13219     }
13220
13221   xfree (cur_attrs);
13222   return abbrev_table;
13223 }
13224
13225 /* Free the resources held by ABBREV_TABLE.  */
13226
13227 static void
13228 abbrev_table_free (struct abbrev_table *abbrev_table)
13229 {
13230   obstack_free (&abbrev_table->abbrev_obstack, NULL);
13231   xfree (abbrev_table);
13232 }
13233
13234 /* Same as abbrev_table_free but as a cleanup.
13235    We pass in a pointer to the pointer to the table so that we can
13236    set the pointer to NULL when we're done.  It also simplifies
13237    build_type_unit_groups.  */
13238
13239 static void
13240 abbrev_table_free_cleanup (void *table_ptr)
13241 {
13242   struct abbrev_table **abbrev_table_ptr = table_ptr;
13243
13244   if (*abbrev_table_ptr != NULL)
13245     abbrev_table_free (*abbrev_table_ptr);
13246   *abbrev_table_ptr = NULL;
13247 }
13248
13249 /* Read the abbrev table for CU from ABBREV_SECTION.  */
13250
13251 static void
13252 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
13253                      struct dwarf2_section_info *abbrev_section)
13254 {
13255   cu->abbrev_table =
13256     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
13257 }
13258
13259 /* Release the memory used by the abbrev table for a compilation unit.  */
13260
13261 static void
13262 dwarf2_free_abbrev_table (void *ptr_to_cu)
13263 {
13264   struct dwarf2_cu *cu = ptr_to_cu;
13265
13266   abbrev_table_free (cu->abbrev_table);
13267   /* Set this to NULL so that we SEGV if we try to read it later,
13268      and also because free_comp_unit verifies this is NULL.  */
13269   cu->abbrev_table = NULL;
13270 }
13271 \f
13272 /* Returns nonzero if TAG represents a type that we might generate a partial
13273    symbol for.  */
13274
13275 static int
13276 is_type_tag_for_partial (int tag)
13277 {
13278   switch (tag)
13279     {
13280 #if 0
13281     /* Some types that would be reasonable to generate partial symbols for,
13282        that we don't at present.  */
13283     case DW_TAG_array_type:
13284     case DW_TAG_file_type:
13285     case DW_TAG_ptr_to_member_type:
13286     case DW_TAG_set_type:
13287     case DW_TAG_string_type:
13288     case DW_TAG_subroutine_type:
13289 #endif
13290     case DW_TAG_base_type:
13291     case DW_TAG_class_type:
13292     case DW_TAG_interface_type:
13293     case DW_TAG_enumeration_type:
13294     case DW_TAG_structure_type:
13295     case DW_TAG_subrange_type:
13296     case DW_TAG_typedef:
13297     case DW_TAG_union_type:
13298       return 1;
13299     default:
13300       return 0;
13301     }
13302 }
13303
13304 /* Load all DIEs that are interesting for partial symbols into memory.  */
13305
13306 static struct partial_die_info *
13307 load_partial_dies (const struct die_reader_specs *reader,
13308                    gdb_byte *info_ptr, int building_psymtab)
13309 {
13310   struct dwarf2_cu *cu = reader->cu;
13311   struct objfile *objfile = cu->objfile;
13312   struct partial_die_info *part_die;
13313   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
13314   struct abbrev_info *abbrev;
13315   unsigned int bytes_read;
13316   unsigned int load_all = 0;
13317   int nesting_level = 1;
13318
13319   parent_die = NULL;
13320   last_die = NULL;
13321
13322   gdb_assert (cu->per_cu != NULL);
13323   if (cu->per_cu->load_all_dies)
13324     load_all = 1;
13325
13326   cu->partial_dies
13327     = htab_create_alloc_ex (cu->header.length / 12,
13328                             partial_die_hash,
13329                             partial_die_eq,
13330                             NULL,
13331                             &cu->comp_unit_obstack,
13332                             hashtab_obstack_allocate,
13333                             dummy_obstack_deallocate);
13334
13335   part_die = obstack_alloc (&cu->comp_unit_obstack,
13336                             sizeof (struct partial_die_info));
13337
13338   while (1)
13339     {
13340       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
13341
13342       /* A NULL abbrev means the end of a series of children.  */
13343       if (abbrev == NULL)
13344         {
13345           if (--nesting_level == 0)
13346             {
13347               /* PART_DIE was probably the last thing allocated on the
13348                  comp_unit_obstack, so we could call obstack_free
13349                  here.  We don't do that because the waste is small,
13350                  and will be cleaned up when we're done with this
13351                  compilation unit.  This way, we're also more robust
13352                  against other users of the comp_unit_obstack.  */
13353               return first_die;
13354             }
13355           info_ptr += bytes_read;
13356           last_die = parent_die;
13357           parent_die = parent_die->die_parent;
13358           continue;
13359         }
13360
13361       /* Check for template arguments.  We never save these; if
13362          they're seen, we just mark the parent, and go on our way.  */
13363       if (parent_die != NULL
13364           && cu->language == language_cplus
13365           && (abbrev->tag == DW_TAG_template_type_param
13366               || abbrev->tag == DW_TAG_template_value_param))
13367         {
13368           parent_die->has_template_arguments = 1;
13369
13370           if (!load_all)
13371             {
13372               /* We don't need a partial DIE for the template argument.  */
13373               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13374               continue;
13375             }
13376         }
13377
13378       /* We only recurse into c++ subprograms looking for template arguments.
13379          Skip their other children.  */
13380       if (!load_all
13381           && cu->language == language_cplus
13382           && parent_die != NULL
13383           && parent_die->tag == DW_TAG_subprogram)
13384         {
13385           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13386           continue;
13387         }
13388
13389       /* Check whether this DIE is interesting enough to save.  Normally
13390          we would not be interested in members here, but there may be
13391          later variables referencing them via DW_AT_specification (for
13392          static members).  */
13393       if (!load_all
13394           && !is_type_tag_for_partial (abbrev->tag)
13395           && abbrev->tag != DW_TAG_constant
13396           && abbrev->tag != DW_TAG_enumerator
13397           && abbrev->tag != DW_TAG_subprogram
13398           && abbrev->tag != DW_TAG_lexical_block
13399           && abbrev->tag != DW_TAG_variable
13400           && abbrev->tag != DW_TAG_namespace
13401           && abbrev->tag != DW_TAG_module
13402           && abbrev->tag != DW_TAG_member
13403           && abbrev->tag != DW_TAG_imported_unit)
13404         {
13405           /* Otherwise we skip to the next sibling, if any.  */
13406           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
13407           continue;
13408         }
13409
13410       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
13411                                    info_ptr);
13412
13413       /* This two-pass algorithm for processing partial symbols has a
13414          high cost in cache pressure.  Thus, handle some simple cases
13415          here which cover the majority of C partial symbols.  DIEs
13416          which neither have specification tags in them, nor could have
13417          specification tags elsewhere pointing at them, can simply be
13418          processed and discarded.
13419
13420          This segment is also optional; scan_partial_symbols and
13421          add_partial_symbol will handle these DIEs if we chain
13422          them in normally.  When compilers which do not emit large
13423          quantities of duplicate debug information are more common,
13424          this code can probably be removed.  */
13425
13426       /* Any complete simple types at the top level (pretty much all
13427          of them, for a language without namespaces), can be processed
13428          directly.  */
13429       if (parent_die == NULL
13430           && part_die->has_specification == 0
13431           && part_die->is_declaration == 0
13432           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
13433               || part_die->tag == DW_TAG_base_type
13434               || part_die->tag == DW_TAG_subrange_type))
13435         {
13436           if (building_psymtab && part_die->name != NULL)
13437             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13438                                  VAR_DOMAIN, LOC_TYPEDEF,
13439                                  &objfile->static_psymbols,
13440                                  0, (CORE_ADDR) 0, cu->language, objfile);
13441           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13442           continue;
13443         }
13444
13445       /* The exception for DW_TAG_typedef with has_children above is
13446          a workaround of GCC PR debug/47510.  In the case of this complaint
13447          type_name_no_tag_or_error will error on such types later.
13448
13449          GDB skipped children of DW_TAG_typedef by the shortcut above and then
13450          it could not find the child DIEs referenced later, this is checked
13451          above.  In correct DWARF DW_TAG_typedef should have no children.  */
13452
13453       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
13454         complaint (&symfile_complaints,
13455                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
13456                      "- DIE at 0x%x [in module %s]"),
13457                    part_die->offset.sect_off, objfile->name);
13458
13459       /* If we're at the second level, and we're an enumerator, and
13460          our parent has no specification (meaning possibly lives in a
13461          namespace elsewhere), then we can add the partial symbol now
13462          instead of queueing it.  */
13463       if (part_die->tag == DW_TAG_enumerator
13464           && parent_die != NULL
13465           && parent_die->die_parent == NULL
13466           && parent_die->tag == DW_TAG_enumeration_type
13467           && parent_die->has_specification == 0)
13468         {
13469           if (part_die->name == NULL)
13470             complaint (&symfile_complaints,
13471                        _("malformed enumerator DIE ignored"));
13472           else if (building_psymtab)
13473             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
13474                                  VAR_DOMAIN, LOC_CONST,
13475                                  (cu->language == language_cplus
13476                                   || cu->language == language_java)
13477                                  ? &objfile->global_psymbols
13478                                  : &objfile->static_psymbols,
13479                                  0, (CORE_ADDR) 0, cu->language, objfile);
13480
13481           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
13482           continue;
13483         }
13484
13485       /* We'll save this DIE so link it in.  */
13486       part_die->die_parent = parent_die;
13487       part_die->die_sibling = NULL;
13488       part_die->die_child = NULL;
13489
13490       if (last_die && last_die == parent_die)
13491         last_die->die_child = part_die;
13492       else if (last_die)
13493         last_die->die_sibling = part_die;
13494
13495       last_die = part_die;
13496
13497       if (first_die == NULL)
13498         first_die = part_die;
13499
13500       /* Maybe add the DIE to the hash table.  Not all DIEs that we
13501          find interesting need to be in the hash table, because we
13502          also have the parent/sibling/child chains; only those that we
13503          might refer to by offset later during partial symbol reading.
13504
13505          For now this means things that might have be the target of a
13506          DW_AT_specification, DW_AT_abstract_origin, or
13507          DW_AT_extension.  DW_AT_extension will refer only to
13508          namespaces; DW_AT_abstract_origin refers to functions (and
13509          many things under the function DIE, but we do not recurse
13510          into function DIEs during partial symbol reading) and
13511          possibly variables as well; DW_AT_specification refers to
13512          declarations.  Declarations ought to have the DW_AT_declaration
13513          flag.  It happens that GCC forgets to put it in sometimes, but
13514          only for functions, not for types.
13515
13516          Adding more things than necessary to the hash table is harmless
13517          except for the performance cost.  Adding too few will result in
13518          wasted time in find_partial_die, when we reread the compilation
13519          unit with load_all_dies set.  */
13520
13521       if (load_all
13522           || abbrev->tag == DW_TAG_constant
13523           || abbrev->tag == DW_TAG_subprogram
13524           || abbrev->tag == DW_TAG_variable
13525           || abbrev->tag == DW_TAG_namespace
13526           || part_die->is_declaration)
13527         {
13528           void **slot;
13529
13530           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
13531                                            part_die->offset.sect_off, INSERT);
13532           *slot = part_die;
13533         }
13534
13535       part_die = obstack_alloc (&cu->comp_unit_obstack,
13536                                 sizeof (struct partial_die_info));
13537
13538       /* For some DIEs we want to follow their children (if any).  For C
13539          we have no reason to follow the children of structures; for other
13540          languages we have to, so that we can get at method physnames
13541          to infer fully qualified class names, for DW_AT_specification,
13542          and for C++ template arguments.  For C++, we also look one level
13543          inside functions to find template arguments (if the name of the
13544          function does not already contain the template arguments).
13545
13546          For Ada, we need to scan the children of subprograms and lexical
13547          blocks as well because Ada allows the definition of nested
13548          entities that could be interesting for the debugger, such as
13549          nested subprograms for instance.  */
13550       if (last_die->has_children
13551           && (load_all
13552               || last_die->tag == DW_TAG_namespace
13553               || last_die->tag == DW_TAG_module
13554               || last_die->tag == DW_TAG_enumeration_type
13555               || (cu->language == language_cplus
13556                   && last_die->tag == DW_TAG_subprogram
13557                   && (last_die->name == NULL
13558                       || strchr (last_die->name, '<') == NULL))
13559               || (cu->language != language_c
13560                   && (last_die->tag == DW_TAG_class_type
13561                       || last_die->tag == DW_TAG_interface_type
13562                       || last_die->tag == DW_TAG_structure_type
13563                       || last_die->tag == DW_TAG_union_type))
13564               || (cu->language == language_ada
13565                   && (last_die->tag == DW_TAG_subprogram
13566                       || last_die->tag == DW_TAG_lexical_block))))
13567         {
13568           nesting_level++;
13569           parent_die = last_die;
13570           continue;
13571         }
13572
13573       /* Otherwise we skip to the next sibling, if any.  */
13574       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
13575
13576       /* Back to the top, do it again.  */
13577     }
13578 }
13579
13580 /* Read a minimal amount of information into the minimal die structure.  */
13581
13582 static gdb_byte *
13583 read_partial_die (const struct die_reader_specs *reader,
13584                   struct partial_die_info *part_die,
13585                   struct abbrev_info *abbrev, unsigned int abbrev_len,
13586                   gdb_byte *info_ptr)
13587 {
13588   struct dwarf2_cu *cu = reader->cu;
13589   struct objfile *objfile = cu->objfile;
13590   gdb_byte *buffer = reader->buffer;
13591   unsigned int i;
13592   struct attribute attr;
13593   int has_low_pc_attr = 0;
13594   int has_high_pc_attr = 0;
13595   int high_pc_relative = 0;
13596
13597   memset (part_die, 0, sizeof (struct partial_die_info));
13598
13599   part_die->offset.sect_off = info_ptr - buffer;
13600
13601   info_ptr += abbrev_len;
13602
13603   if (abbrev == NULL)
13604     return info_ptr;
13605
13606   part_die->tag = abbrev->tag;
13607   part_die->has_children = abbrev->has_children;
13608
13609   for (i = 0; i < abbrev->num_attrs; ++i)
13610     {
13611       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
13612
13613       /* Store the data if it is of an attribute we want to keep in a
13614          partial symbol table.  */
13615       switch (attr.name)
13616         {
13617         case DW_AT_name:
13618           switch (part_die->tag)
13619             {
13620             case DW_TAG_compile_unit:
13621             case DW_TAG_partial_unit:
13622             case DW_TAG_type_unit:
13623               /* Compilation units have a DW_AT_name that is a filename, not
13624                  a source language identifier.  */
13625             case DW_TAG_enumeration_type:
13626             case DW_TAG_enumerator:
13627               /* These tags always have simple identifiers already; no need
13628                  to canonicalize them.  */
13629               part_die->name = DW_STRING (&attr);
13630               break;
13631             default:
13632               part_die->name
13633                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
13634                                             &objfile->objfile_obstack);
13635               break;
13636             }
13637           break;
13638         case DW_AT_linkage_name:
13639         case DW_AT_MIPS_linkage_name:
13640           /* Note that both forms of linkage name might appear.  We
13641              assume they will be the same, and we only store the last
13642              one we see.  */
13643           if (cu->language == language_ada)
13644             part_die->name = DW_STRING (&attr);
13645           part_die->linkage_name = DW_STRING (&attr);
13646           break;
13647         case DW_AT_low_pc:
13648           has_low_pc_attr = 1;
13649           part_die->lowpc = DW_ADDR (&attr);
13650           break;
13651         case DW_AT_high_pc:
13652           has_high_pc_attr = 1;
13653           if (attr.form == DW_FORM_addr
13654               || attr.form == DW_FORM_GNU_addr_index)
13655             part_die->highpc = DW_ADDR (&attr);
13656           else
13657             {
13658               high_pc_relative = 1;
13659               part_die->highpc = DW_UNSND (&attr);
13660             }
13661           break;
13662         case DW_AT_location:
13663           /* Support the .debug_loc offsets.  */
13664           if (attr_form_is_block (&attr))
13665             {
13666                part_die->d.locdesc = DW_BLOCK (&attr);
13667             }
13668           else if (attr_form_is_section_offset (&attr))
13669             {
13670               dwarf2_complex_location_expr_complaint ();
13671             }
13672           else
13673             {
13674               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13675                                                      "partial symbol information");
13676             }
13677           break;
13678         case DW_AT_external:
13679           part_die->is_external = DW_UNSND (&attr);
13680           break;
13681         case DW_AT_declaration:
13682           part_die->is_declaration = DW_UNSND (&attr);
13683           break;
13684         case DW_AT_type:
13685           part_die->has_type = 1;
13686           break;
13687         case DW_AT_abstract_origin:
13688         case DW_AT_specification:
13689         case DW_AT_extension:
13690           part_die->has_specification = 1;
13691           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
13692           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13693                                    || cu->per_cu->is_dwz);
13694           break;
13695         case DW_AT_sibling:
13696           /* Ignore absolute siblings, they might point outside of
13697              the current compile unit.  */
13698           if (attr.form == DW_FORM_ref_addr)
13699             complaint (&symfile_complaints,
13700                        _("ignoring absolute DW_AT_sibling"));
13701           else
13702             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
13703           break;
13704         case DW_AT_byte_size:
13705           part_die->has_byte_size = 1;
13706           break;
13707         case DW_AT_calling_convention:
13708           /* DWARF doesn't provide a way to identify a program's source-level
13709              entry point.  DW_AT_calling_convention attributes are only meant
13710              to describe functions' calling conventions.
13711
13712              However, because it's a necessary piece of information in
13713              Fortran, and because DW_CC_program is the only piece of debugging
13714              information whose definition refers to a 'main program' at all,
13715              several compilers have begun marking Fortran main programs with
13716              DW_CC_program --- even when those functions use the standard
13717              calling conventions.
13718
13719              So until DWARF specifies a way to provide this information and
13720              compilers pick up the new representation, we'll support this
13721              practice.  */
13722           if (DW_UNSND (&attr) == DW_CC_program
13723               && cu->language == language_fortran)
13724             {
13725               set_main_name (part_die->name);
13726
13727               /* As this DIE has a static linkage the name would be difficult
13728                  to look up later.  */
13729               language_of_main = language_fortran;
13730             }
13731           break;
13732         case DW_AT_inline:
13733           if (DW_UNSND (&attr) == DW_INL_inlined
13734               || DW_UNSND (&attr) == DW_INL_declared_inlined)
13735             part_die->may_be_inlined = 1;
13736           break;
13737
13738         case DW_AT_import:
13739           if (part_die->tag == DW_TAG_imported_unit)
13740             {
13741               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
13742               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
13743                                   || cu->per_cu->is_dwz);
13744             }
13745           break;
13746
13747         default:
13748           break;
13749         }
13750     }
13751
13752   if (high_pc_relative)
13753     part_die->highpc += part_die->lowpc;
13754
13755   if (has_low_pc_attr && has_high_pc_attr)
13756     {
13757       /* When using the GNU linker, .gnu.linkonce. sections are used to
13758          eliminate duplicate copies of functions and vtables and such.
13759          The linker will arbitrarily choose one and discard the others.
13760          The AT_*_pc values for such functions refer to local labels in
13761          these sections.  If the section from that file was discarded, the
13762          labels are not in the output, so the relocs get a value of 0.
13763          If this is a discarded function, mark the pc bounds as invalid,
13764          so that GDB will ignore it.  */
13765       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
13766         {
13767           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13768
13769           complaint (&symfile_complaints,
13770                      _("DW_AT_low_pc %s is zero "
13771                        "for DIE at 0x%x [in module %s]"),
13772                      paddress (gdbarch, part_die->lowpc),
13773                      part_die->offset.sect_off, objfile->name);
13774         }
13775       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
13776       else if (part_die->lowpc >= part_die->highpc)
13777         {
13778           struct gdbarch *gdbarch = get_objfile_arch (objfile);
13779
13780           complaint (&symfile_complaints,
13781                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
13782                        "for DIE at 0x%x [in module %s]"),
13783                      paddress (gdbarch, part_die->lowpc),
13784                      paddress (gdbarch, part_die->highpc),
13785                      part_die->offset.sect_off, objfile->name);
13786         }
13787       else
13788         part_die->has_pc_info = 1;
13789     }
13790
13791   return info_ptr;
13792 }
13793
13794 /* Find a cached partial DIE at OFFSET in CU.  */
13795
13796 static struct partial_die_info *
13797 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
13798 {
13799   struct partial_die_info *lookup_die = NULL;
13800   struct partial_die_info part_die;
13801
13802   part_die.offset = offset;
13803   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
13804                                     offset.sect_off);
13805
13806   return lookup_die;
13807 }
13808
13809 /* Find a partial DIE at OFFSET, which may or may not be in CU,
13810    except in the case of .debug_types DIEs which do not reference
13811    outside their CU (they do however referencing other types via
13812    DW_FORM_ref_sig8).  */
13813
13814 static struct partial_die_info *
13815 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
13816 {
13817   struct objfile *objfile = cu->objfile;
13818   struct dwarf2_per_cu_data *per_cu = NULL;
13819   struct partial_die_info *pd = NULL;
13820
13821   if (offset_in_dwz == cu->per_cu->is_dwz
13822       && offset_in_cu_p (&cu->header, offset))
13823     {
13824       pd = find_partial_die_in_comp_unit (offset, cu);
13825       if (pd != NULL)
13826         return pd;
13827       /* We missed recording what we needed.
13828          Load all dies and try again.  */
13829       per_cu = cu->per_cu;
13830     }
13831   else
13832     {
13833       /* TUs don't reference other CUs/TUs (except via type signatures).  */
13834       if (cu->per_cu->is_debug_types)
13835         {
13836           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
13837                    " external reference to offset 0x%lx [in module %s].\n"),
13838                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
13839                  bfd_get_filename (objfile->obfd));
13840         }
13841       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
13842                                                  objfile);
13843
13844       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
13845         load_partial_comp_unit (per_cu);
13846
13847       per_cu->cu->last_used = 0;
13848       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13849     }
13850
13851   /* If we didn't find it, and not all dies have been loaded,
13852      load them all and try again.  */
13853
13854   if (pd == NULL && per_cu->load_all_dies == 0)
13855     {
13856       per_cu->load_all_dies = 1;
13857
13858       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
13859          THIS_CU->cu may already be in use.  So we can't just free it and
13860          replace its DIEs with the ones we read in.  Instead, we leave those
13861          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
13862          and clobber THIS_CU->cu->partial_dies with the hash table for the new
13863          set.  */
13864       load_partial_comp_unit (per_cu);
13865
13866       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
13867     }
13868
13869   if (pd == NULL)
13870     internal_error (__FILE__, __LINE__,
13871                     _("could not find partial DIE 0x%x "
13872                       "in cache [from module %s]\n"),
13873                     offset.sect_off, bfd_get_filename (objfile->obfd));
13874   return pd;
13875 }
13876
13877 /* See if we can figure out if the class lives in a namespace.  We do
13878    this by looking for a member function; its demangled name will
13879    contain namespace info, if there is any.  */
13880
13881 static void
13882 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
13883                                   struct dwarf2_cu *cu)
13884 {
13885   /* NOTE: carlton/2003-10-07: Getting the info this way changes
13886      what template types look like, because the demangler
13887      frequently doesn't give the same name as the debug info.  We
13888      could fix this by only using the demangled name to get the
13889      prefix (but see comment in read_structure_type).  */
13890
13891   struct partial_die_info *real_pdi;
13892   struct partial_die_info *child_pdi;
13893
13894   /* If this DIE (this DIE's specification, if any) has a parent, then
13895      we should not do this.  We'll prepend the parent's fully qualified
13896      name when we create the partial symbol.  */
13897
13898   real_pdi = struct_pdi;
13899   while (real_pdi->has_specification)
13900     real_pdi = find_partial_die (real_pdi->spec_offset,
13901                                  real_pdi->spec_is_dwz, cu);
13902
13903   if (real_pdi->die_parent != NULL)
13904     return;
13905
13906   for (child_pdi = struct_pdi->die_child;
13907        child_pdi != NULL;
13908        child_pdi = child_pdi->die_sibling)
13909     {
13910       if (child_pdi->tag == DW_TAG_subprogram
13911           && child_pdi->linkage_name != NULL)
13912         {
13913           char *actual_class_name
13914             = language_class_name_from_physname (cu->language_defn,
13915                                                  child_pdi->linkage_name);
13916           if (actual_class_name != NULL)
13917             {
13918               struct_pdi->name
13919                 = obstack_copy0 (&cu->objfile->objfile_obstack,
13920                                  actual_class_name,
13921                                  strlen (actual_class_name));
13922               xfree (actual_class_name);
13923             }
13924           break;
13925         }
13926     }
13927 }
13928
13929 /* Adjust PART_DIE before generating a symbol for it.  This function
13930    may set the is_external flag or change the DIE's name.  */
13931
13932 static void
13933 fixup_partial_die (struct partial_die_info *part_die,
13934                    struct dwarf2_cu *cu)
13935 {
13936   /* Once we've fixed up a die, there's no point in doing so again.
13937      This also avoids a memory leak if we were to call
13938      guess_partial_die_structure_name multiple times.  */
13939   if (part_die->fixup_called)
13940     return;
13941
13942   /* If we found a reference attribute and the DIE has no name, try
13943      to find a name in the referred to DIE.  */
13944
13945   if (part_die->name == NULL && part_die->has_specification)
13946     {
13947       struct partial_die_info *spec_die;
13948
13949       spec_die = find_partial_die (part_die->spec_offset,
13950                                    part_die->spec_is_dwz, cu);
13951
13952       fixup_partial_die (spec_die, cu);
13953
13954       if (spec_die->name)
13955         {
13956           part_die->name = spec_die->name;
13957
13958           /* Copy DW_AT_external attribute if it is set.  */
13959           if (spec_die->is_external)
13960             part_die->is_external = spec_die->is_external;
13961         }
13962     }
13963
13964   /* Set default names for some unnamed DIEs.  */
13965
13966   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
13967     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
13968
13969   /* If there is no parent die to provide a namespace, and there are
13970      children, see if we can determine the namespace from their linkage
13971      name.  */
13972   if (cu->language == language_cplus
13973       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
13974       && part_die->die_parent == NULL
13975       && part_die->has_children
13976       && (part_die->tag == DW_TAG_class_type
13977           || part_die->tag == DW_TAG_structure_type
13978           || part_die->tag == DW_TAG_union_type))
13979     guess_partial_die_structure_name (part_die, cu);
13980
13981   /* GCC might emit a nameless struct or union that has a linkage
13982      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
13983   if (part_die->name == NULL
13984       && (part_die->tag == DW_TAG_class_type
13985           || part_die->tag == DW_TAG_interface_type
13986           || part_die->tag == DW_TAG_structure_type
13987           || part_die->tag == DW_TAG_union_type)
13988       && part_die->linkage_name != NULL)
13989     {
13990       char *demangled;
13991
13992       demangled = cplus_demangle (part_die->linkage_name, DMGL_TYPES);
13993       if (demangled)
13994         {
13995           const char *base;
13996
13997           /* Strip any leading namespaces/classes, keep only the base name.
13998              DW_AT_name for named DIEs does not contain the prefixes.  */
13999           base = strrchr (demangled, ':');
14000           if (base && base > demangled && base[-1] == ':')
14001             base++;
14002           else
14003             base = demangled;
14004
14005           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
14006                                           base, strlen (base));
14007           xfree (demangled);
14008         }
14009     }
14010
14011   part_die->fixup_called = 1;
14012 }
14013
14014 /* Read an attribute value described by an attribute form.  */
14015
14016 static gdb_byte *
14017 read_attribute_value (const struct die_reader_specs *reader,
14018                       struct attribute *attr, unsigned form,
14019                       gdb_byte *info_ptr)
14020 {
14021   struct dwarf2_cu *cu = reader->cu;
14022   bfd *abfd = reader->abfd;
14023   struct comp_unit_head *cu_header = &cu->header;
14024   unsigned int bytes_read;
14025   struct dwarf_block *blk;
14026
14027   attr->form = form;
14028   switch (form)
14029     {
14030     case DW_FORM_ref_addr:
14031       if (cu->header.version == 2)
14032         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14033       else
14034         DW_UNSND (attr) = read_offset (abfd, info_ptr,
14035                                        &cu->header, &bytes_read);
14036       info_ptr += bytes_read;
14037       break;
14038     case DW_FORM_GNU_ref_alt:
14039       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14040       info_ptr += bytes_read;
14041       break;
14042     case DW_FORM_addr:
14043       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
14044       info_ptr += bytes_read;
14045       break;
14046     case DW_FORM_block2:
14047       blk = dwarf_alloc_block (cu);
14048       blk->size = read_2_bytes (abfd, info_ptr);
14049       info_ptr += 2;
14050       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14051       info_ptr += blk->size;
14052       DW_BLOCK (attr) = blk;
14053       break;
14054     case DW_FORM_block4:
14055       blk = dwarf_alloc_block (cu);
14056       blk->size = read_4_bytes (abfd, info_ptr);
14057       info_ptr += 4;
14058       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14059       info_ptr += blk->size;
14060       DW_BLOCK (attr) = blk;
14061       break;
14062     case DW_FORM_data2:
14063       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
14064       info_ptr += 2;
14065       break;
14066     case DW_FORM_data4:
14067       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
14068       info_ptr += 4;
14069       break;
14070     case DW_FORM_data8:
14071       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
14072       info_ptr += 8;
14073       break;
14074     case DW_FORM_sec_offset:
14075       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
14076       info_ptr += bytes_read;
14077       break;
14078     case DW_FORM_string:
14079       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
14080       DW_STRING_IS_CANONICAL (attr) = 0;
14081       info_ptr += bytes_read;
14082       break;
14083     case DW_FORM_strp:
14084       if (!cu->per_cu->is_dwz)
14085         {
14086           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
14087                                                    &bytes_read);
14088           DW_STRING_IS_CANONICAL (attr) = 0;
14089           info_ptr += bytes_read;
14090           break;
14091         }
14092       /* FALLTHROUGH */
14093     case DW_FORM_GNU_strp_alt:
14094       {
14095         struct dwz_file *dwz = dwarf2_get_dwz_file ();
14096         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
14097                                           &bytes_read);
14098
14099         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
14100         DW_STRING_IS_CANONICAL (attr) = 0;
14101         info_ptr += bytes_read;
14102       }
14103       break;
14104     case DW_FORM_exprloc:
14105     case DW_FORM_block:
14106       blk = dwarf_alloc_block (cu);
14107       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14108       info_ptr += bytes_read;
14109       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14110       info_ptr += blk->size;
14111       DW_BLOCK (attr) = blk;
14112       break;
14113     case DW_FORM_block1:
14114       blk = dwarf_alloc_block (cu);
14115       blk->size = read_1_byte (abfd, info_ptr);
14116       info_ptr += 1;
14117       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
14118       info_ptr += blk->size;
14119       DW_BLOCK (attr) = blk;
14120       break;
14121     case DW_FORM_data1:
14122       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14123       info_ptr += 1;
14124       break;
14125     case DW_FORM_flag:
14126       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
14127       info_ptr += 1;
14128       break;
14129     case DW_FORM_flag_present:
14130       DW_UNSND (attr) = 1;
14131       break;
14132     case DW_FORM_sdata:
14133       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
14134       info_ptr += bytes_read;
14135       break;
14136     case DW_FORM_udata:
14137       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14138       info_ptr += bytes_read;
14139       break;
14140     case DW_FORM_ref1:
14141       DW_UNSND (attr) = (cu->header.offset.sect_off
14142                          + read_1_byte (abfd, info_ptr));
14143       info_ptr += 1;
14144       break;
14145     case DW_FORM_ref2:
14146       DW_UNSND (attr) = (cu->header.offset.sect_off
14147                          + read_2_bytes (abfd, info_ptr));
14148       info_ptr += 2;
14149       break;
14150     case DW_FORM_ref4:
14151       DW_UNSND (attr) = (cu->header.offset.sect_off
14152                          + read_4_bytes (abfd, info_ptr));
14153       info_ptr += 4;
14154       break;
14155     case DW_FORM_ref8:
14156       DW_UNSND (attr) = (cu->header.offset.sect_off
14157                          + read_8_bytes (abfd, info_ptr));
14158       info_ptr += 8;
14159       break;
14160     case DW_FORM_ref_sig8:
14161       /* Convert the signature to something we can record in DW_UNSND
14162          for later lookup.
14163          NOTE: This is NULL if the type wasn't found.  */
14164       DW_SIGNATURED_TYPE (attr) =
14165         lookup_signatured_type (read_8_bytes (abfd, info_ptr));
14166       info_ptr += 8;
14167       break;
14168     case DW_FORM_ref_udata:
14169       DW_UNSND (attr) = (cu->header.offset.sect_off
14170                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
14171       info_ptr += bytes_read;
14172       break;
14173     case DW_FORM_indirect:
14174       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14175       info_ptr += bytes_read;
14176       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
14177       break;
14178     case DW_FORM_GNU_addr_index:
14179       if (reader->dwo_file == NULL)
14180         {
14181           /* For now flag a hard error.
14182              Later we can turn this into a complaint.  */
14183           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14184                  dwarf_form_name (form),
14185                  bfd_get_filename (abfd));
14186         }
14187       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
14188       info_ptr += bytes_read;
14189       break;
14190     case DW_FORM_GNU_str_index:
14191       if (reader->dwo_file == NULL)
14192         {
14193           /* For now flag a hard error.
14194              Later we can turn this into a complaint if warranted.  */
14195           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
14196                  dwarf_form_name (form),
14197                  bfd_get_filename (abfd));
14198         }
14199       {
14200         ULONGEST str_index =
14201           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14202
14203         DW_STRING (attr) = read_str_index (reader, cu, str_index);
14204         DW_STRING_IS_CANONICAL (attr) = 0;
14205         info_ptr += bytes_read;
14206       }
14207       break;
14208     default:
14209       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
14210              dwarf_form_name (form),
14211              bfd_get_filename (abfd));
14212     }
14213
14214   /* Super hack.  */
14215   if (cu->per_cu->is_dwz && is_ref_attr (attr))
14216     attr->form = DW_FORM_GNU_ref_alt;
14217
14218   /* We have seen instances where the compiler tried to emit a byte
14219      size attribute of -1 which ended up being encoded as an unsigned
14220      0xffffffff.  Although 0xffffffff is technically a valid size value,
14221      an object of this size seems pretty unlikely so we can relatively
14222      safely treat these cases as if the size attribute was invalid and
14223      treat them as zero by default.  */
14224   if (attr->name == DW_AT_byte_size
14225       && form == DW_FORM_data4
14226       && DW_UNSND (attr) >= 0xffffffff)
14227     {
14228       complaint
14229         (&symfile_complaints,
14230          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
14231          hex_string (DW_UNSND (attr)));
14232       DW_UNSND (attr) = 0;
14233     }
14234
14235   return info_ptr;
14236 }
14237
14238 /* Read an attribute described by an abbreviated attribute.  */
14239
14240 static gdb_byte *
14241 read_attribute (const struct die_reader_specs *reader,
14242                 struct attribute *attr, struct attr_abbrev *abbrev,
14243                 gdb_byte *info_ptr)
14244 {
14245   attr->name = abbrev->name;
14246   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
14247 }
14248
14249 /* Read dwarf information from a buffer.  */
14250
14251 static unsigned int
14252 read_1_byte (bfd *abfd, const gdb_byte *buf)
14253 {
14254   return bfd_get_8 (abfd, buf);
14255 }
14256
14257 static int
14258 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
14259 {
14260   return bfd_get_signed_8 (abfd, buf);
14261 }
14262
14263 static unsigned int
14264 read_2_bytes (bfd *abfd, const gdb_byte *buf)
14265 {
14266   return bfd_get_16 (abfd, buf);
14267 }
14268
14269 static int
14270 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
14271 {
14272   return bfd_get_signed_16 (abfd, buf);
14273 }
14274
14275 static unsigned int
14276 read_4_bytes (bfd *abfd, const gdb_byte *buf)
14277 {
14278   return bfd_get_32 (abfd, buf);
14279 }
14280
14281 static int
14282 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
14283 {
14284   return bfd_get_signed_32 (abfd, buf);
14285 }
14286
14287 static ULONGEST
14288 read_8_bytes (bfd *abfd, const gdb_byte *buf)
14289 {
14290   return bfd_get_64 (abfd, buf);
14291 }
14292
14293 static CORE_ADDR
14294 read_address (bfd *abfd, gdb_byte *buf, struct dwarf2_cu *cu,
14295               unsigned int *bytes_read)
14296 {
14297   struct comp_unit_head *cu_header = &cu->header;
14298   CORE_ADDR retval = 0;
14299
14300   if (cu_header->signed_addr_p)
14301     {
14302       switch (cu_header->addr_size)
14303         {
14304         case 2:
14305           retval = bfd_get_signed_16 (abfd, buf);
14306           break;
14307         case 4:
14308           retval = bfd_get_signed_32 (abfd, buf);
14309           break;
14310         case 8:
14311           retval = bfd_get_signed_64 (abfd, buf);
14312           break;
14313         default:
14314           internal_error (__FILE__, __LINE__,
14315                           _("read_address: bad switch, signed [in module %s]"),
14316                           bfd_get_filename (abfd));
14317         }
14318     }
14319   else
14320     {
14321       switch (cu_header->addr_size)
14322         {
14323         case 2:
14324           retval = bfd_get_16 (abfd, buf);
14325           break;
14326         case 4:
14327           retval = bfd_get_32 (abfd, buf);
14328           break;
14329         case 8:
14330           retval = bfd_get_64 (abfd, buf);
14331           break;
14332         default:
14333           internal_error (__FILE__, __LINE__,
14334                           _("read_address: bad switch, "
14335                             "unsigned [in module %s]"),
14336                           bfd_get_filename (abfd));
14337         }
14338     }
14339
14340   *bytes_read = cu_header->addr_size;
14341   return retval;
14342 }
14343
14344 /* Read the initial length from a section.  The (draft) DWARF 3
14345    specification allows the initial length to take up either 4 bytes
14346    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
14347    bytes describe the length and all offsets will be 8 bytes in length
14348    instead of 4.
14349
14350    An older, non-standard 64-bit format is also handled by this
14351    function.  The older format in question stores the initial length
14352    as an 8-byte quantity without an escape value.  Lengths greater
14353    than 2^32 aren't very common which means that the initial 4 bytes
14354    is almost always zero.  Since a length value of zero doesn't make
14355    sense for the 32-bit format, this initial zero can be considered to
14356    be an escape value which indicates the presence of the older 64-bit
14357    format.  As written, the code can't detect (old format) lengths
14358    greater than 4GB.  If it becomes necessary to handle lengths
14359    somewhat larger than 4GB, we could allow other small values (such
14360    as the non-sensical values of 1, 2, and 3) to also be used as
14361    escape values indicating the presence of the old format.
14362
14363    The value returned via bytes_read should be used to increment the
14364    relevant pointer after calling read_initial_length().
14365
14366    [ Note:  read_initial_length() and read_offset() are based on the
14367      document entitled "DWARF Debugging Information Format", revision
14368      3, draft 8, dated November 19, 2001.  This document was obtained
14369      from:
14370
14371         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
14372
14373      This document is only a draft and is subject to change.  (So beware.)
14374
14375      Details regarding the older, non-standard 64-bit format were
14376      determined empirically by examining 64-bit ELF files produced by
14377      the SGI toolchain on an IRIX 6.5 machine.
14378
14379      - Kevin, July 16, 2002
14380    ] */
14381
14382 static LONGEST
14383 read_initial_length (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read)
14384 {
14385   LONGEST length = bfd_get_32 (abfd, buf);
14386
14387   if (length == 0xffffffff)
14388     {
14389       length = bfd_get_64 (abfd, buf + 4);
14390       *bytes_read = 12;
14391     }
14392   else if (length == 0)
14393     {
14394       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
14395       length = bfd_get_64 (abfd, buf);
14396       *bytes_read = 8;
14397     }
14398   else
14399     {
14400       *bytes_read = 4;
14401     }
14402
14403   return length;
14404 }
14405
14406 /* Cover function for read_initial_length.
14407    Returns the length of the object at BUF, and stores the size of the
14408    initial length in *BYTES_READ and stores the size that offsets will be in
14409    *OFFSET_SIZE.
14410    If the initial length size is not equivalent to that specified in
14411    CU_HEADER then issue a complaint.
14412    This is useful when reading non-comp-unit headers.  */
14413
14414 static LONGEST
14415 read_checked_initial_length_and_offset (bfd *abfd, gdb_byte *buf,
14416                                         const struct comp_unit_head *cu_header,
14417                                         unsigned int *bytes_read,
14418                                         unsigned int *offset_size)
14419 {
14420   LONGEST length = read_initial_length (abfd, buf, bytes_read);
14421
14422   gdb_assert (cu_header->initial_length_size == 4
14423               || cu_header->initial_length_size == 8
14424               || cu_header->initial_length_size == 12);
14425
14426   if (cu_header->initial_length_size != *bytes_read)
14427     complaint (&symfile_complaints,
14428                _("intermixed 32-bit and 64-bit DWARF sections"));
14429
14430   *offset_size = (*bytes_read == 4) ? 4 : 8;
14431   return length;
14432 }
14433
14434 /* Read an offset from the data stream.  The size of the offset is
14435    given by cu_header->offset_size.  */
14436
14437 static LONGEST
14438 read_offset (bfd *abfd, gdb_byte *buf, const struct comp_unit_head *cu_header,
14439              unsigned int *bytes_read)
14440 {
14441   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
14442
14443   *bytes_read = cu_header->offset_size;
14444   return offset;
14445 }
14446
14447 /* Read an offset from the data stream.  */
14448
14449 static LONGEST
14450 read_offset_1 (bfd *abfd, gdb_byte *buf, unsigned int offset_size)
14451 {
14452   LONGEST retval = 0;
14453
14454   switch (offset_size)
14455     {
14456     case 4:
14457       retval = bfd_get_32 (abfd, buf);
14458       break;
14459     case 8:
14460       retval = bfd_get_64 (abfd, buf);
14461       break;
14462     default:
14463       internal_error (__FILE__, __LINE__,
14464                       _("read_offset_1: bad switch [in module %s]"),
14465                       bfd_get_filename (abfd));
14466     }
14467
14468   return retval;
14469 }
14470
14471 static gdb_byte *
14472 read_n_bytes (bfd *abfd, gdb_byte *buf, unsigned int size)
14473 {
14474   /* If the size of a host char is 8 bits, we can return a pointer
14475      to the buffer, otherwise we have to copy the data to a buffer
14476      allocated on the temporary obstack.  */
14477   gdb_assert (HOST_CHAR_BIT == 8);
14478   return buf;
14479 }
14480
14481 static char *
14482 read_direct_string (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14483 {
14484   /* If the size of a host char is 8 bits, we can return a pointer
14485      to the string, otherwise we have to copy the string to a buffer
14486      allocated on the temporary obstack.  */
14487   gdb_assert (HOST_CHAR_BIT == 8);
14488   if (*buf == '\0')
14489     {
14490       *bytes_read_ptr = 1;
14491       return NULL;
14492     }
14493   *bytes_read_ptr = strlen ((char *) buf) + 1;
14494   return (char *) buf;
14495 }
14496
14497 static char *
14498 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
14499 {
14500   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
14501   if (dwarf2_per_objfile->str.buffer == NULL)
14502     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
14503            bfd_get_filename (abfd));
14504   if (str_offset >= dwarf2_per_objfile->str.size)
14505     error (_("DW_FORM_strp pointing outside of "
14506              ".debug_str section [in module %s]"),
14507            bfd_get_filename (abfd));
14508   gdb_assert (HOST_CHAR_BIT == 8);
14509   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
14510     return NULL;
14511   return (char *) (dwarf2_per_objfile->str.buffer + str_offset);
14512 }
14513
14514 /* Read a string at offset STR_OFFSET in the .debug_str section from
14515    the .dwz file DWZ.  Throw an error if the offset is too large.  If
14516    the string consists of a single NUL byte, return NULL; otherwise
14517    return a pointer to the string.  */
14518
14519 static char *
14520 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
14521 {
14522   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
14523
14524   if (dwz->str.buffer == NULL)
14525     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
14526              "section [in module %s]"),
14527            bfd_get_filename (dwz->dwz_bfd));
14528   if (str_offset >= dwz->str.size)
14529     error (_("DW_FORM_GNU_strp_alt pointing outside of "
14530              ".debug_str section [in module %s]"),
14531            bfd_get_filename (dwz->dwz_bfd));
14532   gdb_assert (HOST_CHAR_BIT == 8);
14533   if (dwz->str.buffer[str_offset] == '\0')
14534     return NULL;
14535   return (char *) (dwz->str.buffer + str_offset);
14536 }
14537
14538 static char *
14539 read_indirect_string (bfd *abfd, gdb_byte *buf,
14540                       const struct comp_unit_head *cu_header,
14541                       unsigned int *bytes_read_ptr)
14542 {
14543   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
14544
14545   return read_indirect_string_at_offset (abfd, str_offset);
14546 }
14547
14548 static ULONGEST
14549 read_unsigned_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14550 {
14551   ULONGEST result;
14552   unsigned int num_read;
14553   int i, shift;
14554   unsigned char byte;
14555
14556   result = 0;
14557   shift = 0;
14558   num_read = 0;
14559   i = 0;
14560   while (1)
14561     {
14562       byte = bfd_get_8 (abfd, buf);
14563       buf++;
14564       num_read++;
14565       result |= ((ULONGEST) (byte & 127) << shift);
14566       if ((byte & 128) == 0)
14567         {
14568           break;
14569         }
14570       shift += 7;
14571     }
14572   *bytes_read_ptr = num_read;
14573   return result;
14574 }
14575
14576 static LONGEST
14577 read_signed_leb128 (bfd *abfd, gdb_byte *buf, unsigned int *bytes_read_ptr)
14578 {
14579   LONGEST result;
14580   int i, shift, num_read;
14581   unsigned char byte;
14582
14583   result = 0;
14584   shift = 0;
14585   num_read = 0;
14586   i = 0;
14587   while (1)
14588     {
14589       byte = bfd_get_8 (abfd, buf);
14590       buf++;
14591       num_read++;
14592       result |= ((LONGEST) (byte & 127) << shift);
14593       shift += 7;
14594       if ((byte & 128) == 0)
14595         {
14596           break;
14597         }
14598     }
14599   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
14600     result |= -(((LONGEST) 1) << shift);
14601   *bytes_read_ptr = num_read;
14602   return result;
14603 }
14604
14605 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
14606    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
14607    ADDR_SIZE is the size of addresses from the CU header.  */
14608
14609 static CORE_ADDR
14610 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
14611 {
14612   struct objfile *objfile = dwarf2_per_objfile->objfile;
14613   bfd *abfd = objfile->obfd;
14614   const gdb_byte *info_ptr;
14615
14616   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
14617   if (dwarf2_per_objfile->addr.buffer == NULL)
14618     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
14619            objfile->name);
14620   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
14621     error (_("DW_FORM_addr_index pointing outside of "
14622              ".debug_addr section [in module %s]"),
14623            objfile->name);
14624   info_ptr = (dwarf2_per_objfile->addr.buffer
14625               + addr_base + addr_index * addr_size);
14626   if (addr_size == 4)
14627     return bfd_get_32 (abfd, info_ptr);
14628   else
14629     return bfd_get_64 (abfd, info_ptr);
14630 }
14631
14632 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
14633
14634 static CORE_ADDR
14635 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
14636 {
14637   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
14638 }
14639
14640 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
14641
14642 static CORE_ADDR
14643 read_addr_index_from_leb128 (struct dwarf2_cu *cu, gdb_byte *info_ptr,
14644                              unsigned int *bytes_read)
14645 {
14646   bfd *abfd = cu->objfile->obfd;
14647   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
14648
14649   return read_addr_index (cu, addr_index);
14650 }
14651
14652 /* Data structure to pass results from dwarf2_read_addr_index_reader
14653    back to dwarf2_read_addr_index.  */
14654
14655 struct dwarf2_read_addr_index_data
14656 {
14657   ULONGEST addr_base;
14658   int addr_size;
14659 };
14660
14661 /* die_reader_func for dwarf2_read_addr_index.  */
14662
14663 static void
14664 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
14665                                gdb_byte *info_ptr,
14666                                struct die_info *comp_unit_die,
14667                                int has_children,
14668                                void *data)
14669 {
14670   struct dwarf2_cu *cu = reader->cu;
14671   struct dwarf2_read_addr_index_data *aidata =
14672     (struct dwarf2_read_addr_index_data *) data;
14673
14674   aidata->addr_base = cu->addr_base;
14675   aidata->addr_size = cu->header.addr_size;
14676 }
14677
14678 /* Given an index in .debug_addr, fetch the value.
14679    NOTE: This can be called during dwarf expression evaluation,
14680    long after the debug information has been read, and thus per_cu->cu
14681    may no longer exist.  */
14682
14683 CORE_ADDR
14684 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
14685                         unsigned int addr_index)
14686 {
14687   struct objfile *objfile = per_cu->objfile;
14688   struct dwarf2_cu *cu = per_cu->cu;
14689   ULONGEST addr_base;
14690   int addr_size;
14691
14692   /* This is intended to be called from outside this file.  */
14693   dw2_setup (objfile);
14694
14695   /* We need addr_base and addr_size.
14696      If we don't have PER_CU->cu, we have to get it.
14697      Nasty, but the alternative is storing the needed info in PER_CU,
14698      which at this point doesn't seem justified: it's not clear how frequently
14699      it would get used and it would increase the size of every PER_CU.
14700      Entry points like dwarf2_per_cu_addr_size do a similar thing
14701      so we're not in uncharted territory here.
14702      Alas we need to be a bit more complicated as addr_base is contained
14703      in the DIE.
14704
14705      We don't need to read the entire CU(/TU).
14706      We just need the header and top level die.
14707
14708      IWBN to use the aging mechanism to let us lazily later discard the CU.
14709      For now we skip this optimization.  */
14710
14711   if (cu != NULL)
14712     {
14713       addr_base = cu->addr_base;
14714       addr_size = cu->header.addr_size;
14715     }
14716   else
14717     {
14718       struct dwarf2_read_addr_index_data aidata;
14719
14720       /* Note: We can't use init_cutu_and_read_dies_simple here,
14721          we need addr_base.  */
14722       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
14723                                dwarf2_read_addr_index_reader, &aidata);
14724       addr_base = aidata.addr_base;
14725       addr_size = aidata.addr_size;
14726     }
14727
14728   return read_addr_index_1 (addr_index, addr_base, addr_size);
14729 }
14730
14731 /* Given a DW_AT_str_index, fetch the string.  */
14732
14733 static char *
14734 read_str_index (const struct die_reader_specs *reader,
14735                 struct dwarf2_cu *cu, ULONGEST str_index)
14736 {
14737   struct objfile *objfile = dwarf2_per_objfile->objfile;
14738   const char *dwo_name = objfile->name;
14739   bfd *abfd = objfile->obfd;
14740   struct dwo_sections *sections = &reader->dwo_file->sections;
14741   gdb_byte *info_ptr;
14742   ULONGEST str_offset;
14743
14744   dwarf2_read_section (objfile, &sections->str);
14745   dwarf2_read_section (objfile, &sections->str_offsets);
14746   if (sections->str.buffer == NULL)
14747     error (_("DW_FORM_str_index used without .debug_str.dwo section"
14748              " in CU at offset 0x%lx [in module %s]"),
14749            (long) cu->header.offset.sect_off, dwo_name);
14750   if (sections->str_offsets.buffer == NULL)
14751     error (_("DW_FORM_str_index used without .debug_str_offsets.dwo section"
14752              " in CU at offset 0x%lx [in module %s]"),
14753            (long) cu->header.offset.sect_off, dwo_name);
14754   if (str_index * cu->header.offset_size >= sections->str_offsets.size)
14755     error (_("DW_FORM_str_index pointing outside of .debug_str_offsets.dwo"
14756              " section in CU at offset 0x%lx [in module %s]"),
14757            (long) cu->header.offset.sect_off, dwo_name);
14758   info_ptr = (sections->str_offsets.buffer
14759               + str_index * cu->header.offset_size);
14760   if (cu->header.offset_size == 4)
14761     str_offset = bfd_get_32 (abfd, info_ptr);
14762   else
14763     str_offset = bfd_get_64 (abfd, info_ptr);
14764   if (str_offset >= sections->str.size)
14765     error (_("Offset from DW_FORM_str_index pointing outside of"
14766              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
14767            (long) cu->header.offset.sect_off, dwo_name);
14768   return (char *) (sections->str.buffer + str_offset);
14769 }
14770
14771 /* Return the length of an LEB128 number in BUF.  */
14772
14773 static int
14774 leb128_size (const gdb_byte *buf)
14775 {
14776   const gdb_byte *begin = buf;
14777   gdb_byte byte;
14778
14779   while (1)
14780     {
14781       byte = *buf++;
14782       if ((byte & 128) == 0)
14783         return buf - begin;
14784     }
14785 }
14786
14787 static void
14788 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
14789 {
14790   switch (lang)
14791     {
14792     case DW_LANG_C89:
14793     case DW_LANG_C99:
14794     case DW_LANG_C:
14795       cu->language = language_c;
14796       break;
14797     case DW_LANG_C_plus_plus:
14798       cu->language = language_cplus;
14799       break;
14800     case DW_LANG_D:
14801       cu->language = language_d;
14802       break;
14803     case DW_LANG_Fortran77:
14804     case DW_LANG_Fortran90:
14805     case DW_LANG_Fortran95:
14806       cu->language = language_fortran;
14807       break;
14808     case DW_LANG_Go:
14809       cu->language = language_go;
14810       break;
14811     case DW_LANG_Mips_Assembler:
14812       cu->language = language_asm;
14813       break;
14814     case DW_LANG_Java:
14815       cu->language = language_java;
14816       break;
14817     case DW_LANG_Ada83:
14818     case DW_LANG_Ada95:
14819       cu->language = language_ada;
14820       break;
14821     case DW_LANG_Modula2:
14822       cu->language = language_m2;
14823       break;
14824     case DW_LANG_Pascal83:
14825       cu->language = language_pascal;
14826       break;
14827     case DW_LANG_ObjC:
14828       cu->language = language_objc;
14829       break;
14830     case DW_LANG_Cobol74:
14831     case DW_LANG_Cobol85:
14832     default:
14833       cu->language = language_minimal;
14834       break;
14835     }
14836   cu->language_defn = language_def (cu->language);
14837 }
14838
14839 /* Return the named attribute or NULL if not there.  */
14840
14841 static struct attribute *
14842 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
14843 {
14844   for (;;)
14845     {
14846       unsigned int i;
14847       struct attribute *spec = NULL;
14848
14849       for (i = 0; i < die->num_attrs; ++i)
14850         {
14851           if (die->attrs[i].name == name)
14852             return &die->attrs[i];
14853           if (die->attrs[i].name == DW_AT_specification
14854               || die->attrs[i].name == DW_AT_abstract_origin)
14855             spec = &die->attrs[i];
14856         }
14857
14858       if (!spec)
14859         break;
14860
14861       die = follow_die_ref (die, spec, &cu);
14862     }
14863
14864   return NULL;
14865 }
14866
14867 /* Return the named attribute or NULL if not there,
14868    but do not follow DW_AT_specification, etc.
14869    This is for use in contexts where we're reading .debug_types dies.
14870    Following DW_AT_specification, DW_AT_abstract_origin will take us
14871    back up the chain, and we want to go down.  */
14872
14873 static struct attribute *
14874 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
14875 {
14876   unsigned int i;
14877
14878   for (i = 0; i < die->num_attrs; ++i)
14879     if (die->attrs[i].name == name)
14880       return &die->attrs[i];
14881
14882   return NULL;
14883 }
14884
14885 /* Return non-zero iff the attribute NAME is defined for the given DIE,
14886    and holds a non-zero value.  This function should only be used for
14887    DW_FORM_flag or DW_FORM_flag_present attributes.  */
14888
14889 static int
14890 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
14891 {
14892   struct attribute *attr = dwarf2_attr (die, name, cu);
14893
14894   return (attr && DW_UNSND (attr));
14895 }
14896
14897 static int
14898 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
14899 {
14900   /* A DIE is a declaration if it has a DW_AT_declaration attribute
14901      which value is non-zero.  However, we have to be careful with
14902      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
14903      (via dwarf2_flag_true_p) follows this attribute.  So we may
14904      end up accidently finding a declaration attribute that belongs
14905      to a different DIE referenced by the specification attribute,
14906      even though the given DIE does not have a declaration attribute.  */
14907   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
14908           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
14909 }
14910
14911 /* Return the die giving the specification for DIE, if there is
14912    one.  *SPEC_CU is the CU containing DIE on input, and the CU
14913    containing the return value on output.  If there is no
14914    specification, but there is an abstract origin, that is
14915    returned.  */
14916
14917 static struct die_info *
14918 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
14919 {
14920   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
14921                                              *spec_cu);
14922
14923   if (spec_attr == NULL)
14924     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
14925
14926   if (spec_attr == NULL)
14927     return NULL;
14928   else
14929     return follow_die_ref (die, spec_attr, spec_cu);
14930 }
14931
14932 /* Free the line_header structure *LH, and any arrays and strings it
14933    refers to.
14934    NOTE: This is also used as a "cleanup" function.  */
14935
14936 static void
14937 free_line_header (struct line_header *lh)
14938 {
14939   if (lh->standard_opcode_lengths)
14940     xfree (lh->standard_opcode_lengths);
14941
14942   /* Remember that all the lh->file_names[i].name pointers are
14943      pointers into debug_line_buffer, and don't need to be freed.  */
14944   if (lh->file_names)
14945     xfree (lh->file_names);
14946
14947   /* Similarly for the include directory names.  */
14948   if (lh->include_dirs)
14949     xfree (lh->include_dirs);
14950
14951   xfree (lh);
14952 }
14953
14954 /* Add an entry to LH's include directory table.  */
14955
14956 static void
14957 add_include_dir (struct line_header *lh, char *include_dir)
14958 {
14959   /* Grow the array if necessary.  */
14960   if (lh->include_dirs_size == 0)
14961     {
14962       lh->include_dirs_size = 1; /* for testing */
14963       lh->include_dirs = xmalloc (lh->include_dirs_size
14964                                   * sizeof (*lh->include_dirs));
14965     }
14966   else if (lh->num_include_dirs >= lh->include_dirs_size)
14967     {
14968       lh->include_dirs_size *= 2;
14969       lh->include_dirs = xrealloc (lh->include_dirs,
14970                                    (lh->include_dirs_size
14971                                     * sizeof (*lh->include_dirs)));
14972     }
14973
14974   lh->include_dirs[lh->num_include_dirs++] = include_dir;
14975 }
14976
14977 /* Add an entry to LH's file name table.  */
14978
14979 static void
14980 add_file_name (struct line_header *lh,
14981                char *name,
14982                unsigned int dir_index,
14983                unsigned int mod_time,
14984                unsigned int length)
14985 {
14986   struct file_entry *fe;
14987
14988   /* Grow the array if necessary.  */
14989   if (lh->file_names_size == 0)
14990     {
14991       lh->file_names_size = 1; /* for testing */
14992       lh->file_names = xmalloc (lh->file_names_size
14993                                 * sizeof (*lh->file_names));
14994     }
14995   else if (lh->num_file_names >= lh->file_names_size)
14996     {
14997       lh->file_names_size *= 2;
14998       lh->file_names = xrealloc (lh->file_names,
14999                                  (lh->file_names_size
15000                                   * sizeof (*lh->file_names)));
15001     }
15002
15003   fe = &lh->file_names[lh->num_file_names++];
15004   fe->name = name;
15005   fe->dir_index = dir_index;
15006   fe->mod_time = mod_time;
15007   fe->length = length;
15008   fe->included_p = 0;
15009   fe->symtab = NULL;
15010 }
15011
15012 /* A convenience function to find the proper .debug_line section for a
15013    CU.  */
15014
15015 static struct dwarf2_section_info *
15016 get_debug_line_section (struct dwarf2_cu *cu)
15017 {
15018   struct dwarf2_section_info *section;
15019
15020   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
15021      DWO file.  */
15022   if (cu->dwo_unit && cu->per_cu->is_debug_types)
15023     section = &cu->dwo_unit->dwo_file->sections.line;
15024   else if (cu->per_cu->is_dwz)
15025     {
15026       struct dwz_file *dwz = dwarf2_get_dwz_file ();
15027
15028       section = &dwz->line;
15029     }
15030   else
15031     section = &dwarf2_per_objfile->line;
15032
15033   return section;
15034 }
15035
15036 /* Read the statement program header starting at OFFSET in
15037    .debug_line, or .debug_line.dwo.  Return a pointer
15038    to a struct line_header, allocated using xmalloc.
15039
15040    NOTE: the strings in the include directory and file name tables of
15041    the returned object point into the dwarf line section buffer,
15042    and must not be freed.  */
15043
15044 static struct line_header *
15045 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
15046 {
15047   struct cleanup *back_to;
15048   struct line_header *lh;
15049   gdb_byte *line_ptr;
15050   unsigned int bytes_read, offset_size;
15051   int i;
15052   char *cur_dir, *cur_file;
15053   struct dwarf2_section_info *section;
15054   bfd *abfd;
15055
15056   section = get_debug_line_section (cu);
15057   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
15058   if (section->buffer == NULL)
15059     {
15060       if (cu->dwo_unit && cu->per_cu->is_debug_types)
15061         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
15062       else
15063         complaint (&symfile_complaints, _("missing .debug_line section"));
15064       return 0;
15065     }
15066
15067   /* We can't do this until we know the section is non-empty.
15068      Only then do we know we have such a section.  */
15069   abfd = section->asection->owner;
15070
15071   /* Make sure that at least there's room for the total_length field.
15072      That could be 12 bytes long, but we're just going to fudge that.  */
15073   if (offset + 4 >= section->size)
15074     {
15075       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15076       return 0;
15077     }
15078
15079   lh = xmalloc (sizeof (*lh));
15080   memset (lh, 0, sizeof (*lh));
15081   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
15082                           (void *) lh);
15083
15084   line_ptr = section->buffer + offset;
15085
15086   /* Read in the header.  */
15087   lh->total_length =
15088     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
15089                                             &bytes_read, &offset_size);
15090   line_ptr += bytes_read;
15091   if (line_ptr + lh->total_length > (section->buffer + section->size))
15092     {
15093       dwarf2_statement_list_fits_in_line_number_section_complaint ();
15094       return 0;
15095     }
15096   lh->statement_program_end = line_ptr + lh->total_length;
15097   lh->version = read_2_bytes (abfd, line_ptr);
15098   line_ptr += 2;
15099   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
15100   line_ptr += offset_size;
15101   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
15102   line_ptr += 1;
15103   if (lh->version >= 4)
15104     {
15105       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
15106       line_ptr += 1;
15107     }
15108   else
15109     lh->maximum_ops_per_instruction = 1;
15110
15111   if (lh->maximum_ops_per_instruction == 0)
15112     {
15113       lh->maximum_ops_per_instruction = 1;
15114       complaint (&symfile_complaints,
15115                  _("invalid maximum_ops_per_instruction "
15116                    "in `.debug_line' section"));
15117     }
15118
15119   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
15120   line_ptr += 1;
15121   lh->line_base = read_1_signed_byte (abfd, line_ptr);
15122   line_ptr += 1;
15123   lh->line_range = read_1_byte (abfd, line_ptr);
15124   line_ptr += 1;
15125   lh->opcode_base = read_1_byte (abfd, line_ptr);
15126   line_ptr += 1;
15127   lh->standard_opcode_lengths
15128     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
15129
15130   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
15131   for (i = 1; i < lh->opcode_base; ++i)
15132     {
15133       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
15134       line_ptr += 1;
15135     }
15136
15137   /* Read directory table.  */
15138   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15139     {
15140       line_ptr += bytes_read;
15141       add_include_dir (lh, cur_dir);
15142     }
15143   line_ptr += bytes_read;
15144
15145   /* Read file name table.  */
15146   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
15147     {
15148       unsigned int dir_index, mod_time, length;
15149
15150       line_ptr += bytes_read;
15151       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15152       line_ptr += bytes_read;
15153       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15154       line_ptr += bytes_read;
15155       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15156       line_ptr += bytes_read;
15157
15158       add_file_name (lh, cur_file, dir_index, mod_time, length);
15159     }
15160   line_ptr += bytes_read;
15161   lh->statement_program_start = line_ptr;
15162
15163   if (line_ptr > (section->buffer + section->size))
15164     complaint (&symfile_complaints,
15165                _("line number info header doesn't "
15166                  "fit in `.debug_line' section"));
15167
15168   discard_cleanups (back_to);
15169   return lh;
15170 }
15171
15172 /* Subroutine of dwarf_decode_lines to simplify it.
15173    Return the file name of the psymtab for included file FILE_INDEX
15174    in line header LH of PST.
15175    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15176    If space for the result is malloc'd, it will be freed by a cleanup.
15177    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
15178
15179    The function creates dangling cleanup registration.  */
15180
15181 static char *
15182 psymtab_include_file_name (const struct line_header *lh, int file_index,
15183                            const struct partial_symtab *pst,
15184                            const char *comp_dir)
15185 {
15186   const struct file_entry fe = lh->file_names [file_index];
15187   char *include_name = fe.name;
15188   char *include_name_to_compare = include_name;
15189   char *dir_name = NULL;
15190   const char *pst_filename;
15191   char *copied_name = NULL;
15192   int file_is_pst;
15193
15194   if (fe.dir_index)
15195     dir_name = lh->include_dirs[fe.dir_index - 1];
15196
15197   if (!IS_ABSOLUTE_PATH (include_name)
15198       && (dir_name != NULL || comp_dir != NULL))
15199     {
15200       /* Avoid creating a duplicate psymtab for PST.
15201          We do this by comparing INCLUDE_NAME and PST_FILENAME.
15202          Before we do the comparison, however, we need to account
15203          for DIR_NAME and COMP_DIR.
15204          First prepend dir_name (if non-NULL).  If we still don't
15205          have an absolute path prepend comp_dir (if non-NULL).
15206          However, the directory we record in the include-file's
15207          psymtab does not contain COMP_DIR (to match the
15208          corresponding symtab(s)).
15209
15210          Example:
15211
15212          bash$ cd /tmp
15213          bash$ gcc -g ./hello.c
15214          include_name = "hello.c"
15215          dir_name = "."
15216          DW_AT_comp_dir = comp_dir = "/tmp"
15217          DW_AT_name = "./hello.c"  */
15218
15219       if (dir_name != NULL)
15220         {
15221           include_name = concat (dir_name, SLASH_STRING,
15222                                  include_name, (char *)NULL);
15223           include_name_to_compare = include_name;
15224           make_cleanup (xfree, include_name);
15225         }
15226       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
15227         {
15228           include_name_to_compare = concat (comp_dir, SLASH_STRING,
15229                                             include_name, (char *)NULL);
15230         }
15231     }
15232
15233   pst_filename = pst->filename;
15234   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
15235     {
15236       copied_name = concat (pst->dirname, SLASH_STRING,
15237                             pst_filename, (char *)NULL);
15238       pst_filename = copied_name;
15239     }
15240
15241   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
15242
15243   if (include_name_to_compare != include_name)
15244     xfree (include_name_to_compare);
15245   if (copied_name != NULL)
15246     xfree (copied_name);
15247
15248   if (file_is_pst)
15249     return NULL;
15250   return include_name;
15251 }
15252
15253 /* Ignore this record_line request.  */
15254
15255 static void
15256 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
15257 {
15258   return;
15259 }
15260
15261 /* Subroutine of dwarf_decode_lines to simplify it.
15262    Process the line number information in LH.  */
15263
15264 static void
15265 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
15266                       struct dwarf2_cu *cu, struct partial_symtab *pst)
15267 {
15268   gdb_byte *line_ptr, *extended_end;
15269   gdb_byte *line_end;
15270   unsigned int bytes_read, extended_len;
15271   unsigned char op_code, extended_op, adj_opcode;
15272   CORE_ADDR baseaddr;
15273   struct objfile *objfile = cu->objfile;
15274   bfd *abfd = objfile->obfd;
15275   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15276   const int decode_for_pst_p = (pst != NULL);
15277   struct subfile *last_subfile = NULL;
15278   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
15279     = record_line;
15280
15281   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15282
15283   line_ptr = lh->statement_program_start;
15284   line_end = lh->statement_program_end;
15285
15286   /* Read the statement sequences until there's nothing left.  */
15287   while (line_ptr < line_end)
15288     {
15289       /* state machine registers  */
15290       CORE_ADDR address = 0;
15291       unsigned int file = 1;
15292       unsigned int line = 1;
15293       unsigned int column = 0;
15294       int is_stmt = lh->default_is_stmt;
15295       int basic_block = 0;
15296       int end_sequence = 0;
15297       CORE_ADDR addr;
15298       unsigned char op_index = 0;
15299
15300       if (!decode_for_pst_p && lh->num_file_names >= file)
15301         {
15302           /* Start a subfile for the current file of the state machine.  */
15303           /* lh->include_dirs and lh->file_names are 0-based, but the
15304              directory and file name numbers in the statement program
15305              are 1-based.  */
15306           struct file_entry *fe = &lh->file_names[file - 1];
15307           char *dir = NULL;
15308
15309           if (fe->dir_index)
15310             dir = lh->include_dirs[fe->dir_index - 1];
15311
15312           dwarf2_start_subfile (fe->name, dir, comp_dir);
15313         }
15314
15315       /* Decode the table.  */
15316       while (!end_sequence)
15317         {
15318           op_code = read_1_byte (abfd, line_ptr);
15319           line_ptr += 1;
15320           if (line_ptr > line_end)
15321             {
15322               dwarf2_debug_line_missing_end_sequence_complaint ();
15323               break;
15324             }
15325
15326           if (op_code >= lh->opcode_base)
15327             {
15328               /* Special operand.  */
15329               adj_opcode = op_code - lh->opcode_base;
15330               address += (((op_index + (adj_opcode / lh->line_range))
15331                            / lh->maximum_ops_per_instruction)
15332                           * lh->minimum_instruction_length);
15333               op_index = ((op_index + (adj_opcode / lh->line_range))
15334                           % lh->maximum_ops_per_instruction);
15335               line += lh->line_base + (adj_opcode % lh->line_range);
15336               if (lh->num_file_names < file || file == 0)
15337                 dwarf2_debug_line_missing_file_complaint ();
15338               /* For now we ignore lines not starting on an
15339                  instruction boundary.  */
15340               else if (op_index == 0)
15341                 {
15342                   lh->file_names[file - 1].included_p = 1;
15343                   if (!decode_for_pst_p && is_stmt)
15344                     {
15345                       if (last_subfile != current_subfile)
15346                         {
15347                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15348                           if (last_subfile)
15349                             (*p_record_line) (last_subfile, 0, addr);
15350                           last_subfile = current_subfile;
15351                         }
15352                       /* Append row to matrix using current values.  */
15353                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15354                       (*p_record_line) (current_subfile, line, addr);
15355                     }
15356                 }
15357               basic_block = 0;
15358             }
15359           else switch (op_code)
15360             {
15361             case DW_LNS_extended_op:
15362               extended_len = read_unsigned_leb128 (abfd, line_ptr,
15363                                                    &bytes_read);
15364               line_ptr += bytes_read;
15365               extended_end = line_ptr + extended_len;
15366               extended_op = read_1_byte (abfd, line_ptr);
15367               line_ptr += 1;
15368               switch (extended_op)
15369                 {
15370                 case DW_LNE_end_sequence:
15371                   p_record_line = record_line;
15372                   end_sequence = 1;
15373                   break;
15374                 case DW_LNE_set_address:
15375                   address = read_address (abfd, line_ptr, cu, &bytes_read);
15376
15377                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
15378                     {
15379                       /* This line table is for a function which has been
15380                          GCd by the linker.  Ignore it.  PR gdb/12528 */
15381
15382                       long line_offset
15383                         = line_ptr - get_debug_line_section (cu)->buffer;
15384
15385                       complaint (&symfile_complaints,
15386                                  _(".debug_line address at offset 0x%lx is 0 "
15387                                    "[in module %s]"),
15388                                  line_offset, objfile->name);
15389                       p_record_line = noop_record_line;
15390                     }
15391
15392                   op_index = 0;
15393                   line_ptr += bytes_read;
15394                   address += baseaddr;
15395                   break;
15396                 case DW_LNE_define_file:
15397                   {
15398                     char *cur_file;
15399                     unsigned int dir_index, mod_time, length;
15400
15401                     cur_file = read_direct_string (abfd, line_ptr,
15402                                                    &bytes_read);
15403                     line_ptr += bytes_read;
15404                     dir_index =
15405                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15406                     line_ptr += bytes_read;
15407                     mod_time =
15408                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15409                     line_ptr += bytes_read;
15410                     length =
15411                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15412                     line_ptr += bytes_read;
15413                     add_file_name (lh, cur_file, dir_index, mod_time, length);
15414                   }
15415                   break;
15416                 case DW_LNE_set_discriminator:
15417                   /* The discriminator is not interesting to the debugger;
15418                      just ignore it.  */
15419                   line_ptr = extended_end;
15420                   break;
15421                 default:
15422                   complaint (&symfile_complaints,
15423                              _("mangled .debug_line section"));
15424                   return;
15425                 }
15426               /* Make sure that we parsed the extended op correctly.  If e.g.
15427                  we expected a different address size than the producer used,
15428                  we may have read the wrong number of bytes.  */
15429               if (line_ptr != extended_end)
15430                 {
15431                   complaint (&symfile_complaints,
15432                              _("mangled .debug_line section"));
15433                   return;
15434                 }
15435               break;
15436             case DW_LNS_copy:
15437               if (lh->num_file_names < file || file == 0)
15438                 dwarf2_debug_line_missing_file_complaint ();
15439               else
15440                 {
15441                   lh->file_names[file - 1].included_p = 1;
15442                   if (!decode_for_pst_p && is_stmt)
15443                     {
15444                       if (last_subfile != current_subfile)
15445                         {
15446                           addr = gdbarch_addr_bits_remove (gdbarch, address);
15447                           if (last_subfile)
15448                             (*p_record_line) (last_subfile, 0, addr);
15449                           last_subfile = current_subfile;
15450                         }
15451                       addr = gdbarch_addr_bits_remove (gdbarch, address);
15452                       (*p_record_line) (current_subfile, line, addr);
15453                     }
15454                 }
15455               basic_block = 0;
15456               break;
15457             case DW_LNS_advance_pc:
15458               {
15459                 CORE_ADDR adjust
15460                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15461
15462                 address += (((op_index + adjust)
15463                              / lh->maximum_ops_per_instruction)
15464                             * lh->minimum_instruction_length);
15465                 op_index = ((op_index + adjust)
15466                             % lh->maximum_ops_per_instruction);
15467                 line_ptr += bytes_read;
15468               }
15469               break;
15470             case DW_LNS_advance_line:
15471               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
15472               line_ptr += bytes_read;
15473               break;
15474             case DW_LNS_set_file:
15475               {
15476                 /* The arrays lh->include_dirs and lh->file_names are
15477                    0-based, but the directory and file name numbers in
15478                    the statement program are 1-based.  */
15479                 struct file_entry *fe;
15480                 char *dir = NULL;
15481
15482                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15483                 line_ptr += bytes_read;
15484                 if (lh->num_file_names < file || file == 0)
15485                   dwarf2_debug_line_missing_file_complaint ();
15486                 else
15487                   {
15488                     fe = &lh->file_names[file - 1];
15489                     if (fe->dir_index)
15490                       dir = lh->include_dirs[fe->dir_index - 1];
15491                     if (!decode_for_pst_p)
15492                       {
15493                         last_subfile = current_subfile;
15494                         dwarf2_start_subfile (fe->name, dir, comp_dir);
15495                       }
15496                   }
15497               }
15498               break;
15499             case DW_LNS_set_column:
15500               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15501               line_ptr += bytes_read;
15502               break;
15503             case DW_LNS_negate_stmt:
15504               is_stmt = (!is_stmt);
15505               break;
15506             case DW_LNS_set_basic_block:
15507               basic_block = 1;
15508               break;
15509             /* Add to the address register of the state machine the
15510                address increment value corresponding to special opcode
15511                255.  I.e., this value is scaled by the minimum
15512                instruction length since special opcode 255 would have
15513                scaled the increment.  */
15514             case DW_LNS_const_add_pc:
15515               {
15516                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
15517
15518                 address += (((op_index + adjust)
15519                              / lh->maximum_ops_per_instruction)
15520                             * lh->minimum_instruction_length);
15521                 op_index = ((op_index + adjust)
15522                             % lh->maximum_ops_per_instruction);
15523               }
15524               break;
15525             case DW_LNS_fixed_advance_pc:
15526               address += read_2_bytes (abfd, line_ptr);
15527               op_index = 0;
15528               line_ptr += 2;
15529               break;
15530             default:
15531               {
15532                 /* Unknown standard opcode, ignore it.  */
15533                 int i;
15534
15535                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
15536                   {
15537                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
15538                     line_ptr += bytes_read;
15539                   }
15540               }
15541             }
15542         }
15543       if (lh->num_file_names < file || file == 0)
15544         dwarf2_debug_line_missing_file_complaint ();
15545       else
15546         {
15547           lh->file_names[file - 1].included_p = 1;
15548           if (!decode_for_pst_p)
15549             {
15550               addr = gdbarch_addr_bits_remove (gdbarch, address);
15551               (*p_record_line) (current_subfile, 0, addr);
15552             }
15553         }
15554     }
15555 }
15556
15557 /* Decode the Line Number Program (LNP) for the given line_header
15558    structure and CU.  The actual information extracted and the type
15559    of structures created from the LNP depends on the value of PST.
15560
15561    1. If PST is NULL, then this procedure uses the data from the program
15562       to create all necessary symbol tables, and their linetables.
15563
15564    2. If PST is not NULL, this procedure reads the program to determine
15565       the list of files included by the unit represented by PST, and
15566       builds all the associated partial symbol tables.
15567
15568    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
15569    It is used for relative paths in the line table.
15570    NOTE: When processing partial symtabs (pst != NULL),
15571    comp_dir == pst->dirname.
15572
15573    NOTE: It is important that psymtabs have the same file name (via strcmp)
15574    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
15575    symtab we don't use it in the name of the psymtabs we create.
15576    E.g. expand_line_sal requires this when finding psymtabs to expand.
15577    A good testcase for this is mb-inline.exp.  */
15578
15579 static void
15580 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
15581                     struct dwarf2_cu *cu, struct partial_symtab *pst,
15582                     int want_line_info)
15583 {
15584   struct objfile *objfile = cu->objfile;
15585   const int decode_for_pst_p = (pst != NULL);
15586   struct subfile *first_subfile = current_subfile;
15587
15588   if (want_line_info)
15589     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
15590
15591   if (decode_for_pst_p)
15592     {
15593       int file_index;
15594
15595       /* Now that we're done scanning the Line Header Program, we can
15596          create the psymtab of each included file.  */
15597       for (file_index = 0; file_index < lh->num_file_names; file_index++)
15598         if (lh->file_names[file_index].included_p == 1)
15599           {
15600             char *include_name =
15601               psymtab_include_file_name (lh, file_index, pst, comp_dir);
15602             if (include_name != NULL)
15603               dwarf2_create_include_psymtab (include_name, pst, objfile);
15604           }
15605     }
15606   else
15607     {
15608       /* Make sure a symtab is created for every file, even files
15609          which contain only variables (i.e. no code with associated
15610          line numbers).  */
15611       int i;
15612
15613       for (i = 0; i < lh->num_file_names; i++)
15614         {
15615           char *dir = NULL;
15616           struct file_entry *fe;
15617
15618           fe = &lh->file_names[i];
15619           if (fe->dir_index)
15620             dir = lh->include_dirs[fe->dir_index - 1];
15621           dwarf2_start_subfile (fe->name, dir, comp_dir);
15622
15623           /* Skip the main file; we don't need it, and it must be
15624              allocated last, so that it will show up before the
15625              non-primary symtabs in the objfile's symtab list.  */
15626           if (current_subfile == first_subfile)
15627             continue;
15628
15629           if (current_subfile->symtab == NULL)
15630             current_subfile->symtab = allocate_symtab (current_subfile->name,
15631                                                        objfile);
15632           fe->symtab = current_subfile->symtab;
15633         }
15634     }
15635 }
15636
15637 /* Start a subfile for DWARF.  FILENAME is the name of the file and
15638    DIRNAME the name of the source directory which contains FILENAME
15639    or NULL if not known.  COMP_DIR is the compilation directory for the
15640    linetable's compilation unit or NULL if not known.
15641    This routine tries to keep line numbers from identical absolute and
15642    relative file names in a common subfile.
15643
15644    Using the `list' example from the GDB testsuite, which resides in
15645    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
15646    of /srcdir/list0.c yields the following debugging information for list0.c:
15647
15648    DW_AT_name:          /srcdir/list0.c
15649    DW_AT_comp_dir:              /compdir
15650    files.files[0].name: list0.h
15651    files.files[0].dir:  /srcdir
15652    files.files[1].name: list0.c
15653    files.files[1].dir:  /srcdir
15654
15655    The line number information for list0.c has to end up in a single
15656    subfile, so that `break /srcdir/list0.c:1' works as expected.
15657    start_subfile will ensure that this happens provided that we pass the
15658    concatenation of files.files[1].dir and files.files[1].name as the
15659    subfile's name.  */
15660
15661 static void
15662 dwarf2_start_subfile (char *filename, const char *dirname,
15663                       const char *comp_dir)
15664 {
15665   char *fullname;
15666
15667   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
15668      `start_symtab' will always pass the contents of DW_AT_comp_dir as
15669      second argument to start_subfile.  To be consistent, we do the
15670      same here.  In order not to lose the line information directory,
15671      we concatenate it to the filename when it makes sense.
15672      Note that the Dwarf3 standard says (speaking of filenames in line
15673      information): ``The directory index is ignored for file names
15674      that represent full path names''.  Thus ignoring dirname in the
15675      `else' branch below isn't an issue.  */
15676
15677   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
15678     fullname = concat (dirname, SLASH_STRING, filename, (char *)NULL);
15679   else
15680     fullname = filename;
15681
15682   start_subfile (fullname, comp_dir);
15683
15684   if (fullname != filename)
15685     xfree (fullname);
15686 }
15687
15688 /* Start a symtab for DWARF.
15689    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
15690
15691 static void
15692 dwarf2_start_symtab (struct dwarf2_cu *cu,
15693                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
15694 {
15695   start_symtab (name, comp_dir, low_pc);
15696   record_debugformat ("DWARF 2");
15697   record_producer (cu->producer);
15698
15699   /* We assume that we're processing GCC output.  */
15700   processing_gcc_compilation = 2;
15701
15702   cu->processing_has_namespace_info = 0;
15703 }
15704
15705 static void
15706 var_decode_location (struct attribute *attr, struct symbol *sym,
15707                      struct dwarf2_cu *cu)
15708 {
15709   struct objfile *objfile = cu->objfile;
15710   struct comp_unit_head *cu_header = &cu->header;
15711
15712   /* NOTE drow/2003-01-30: There used to be a comment and some special
15713      code here to turn a symbol with DW_AT_external and a
15714      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
15715      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
15716      with some versions of binutils) where shared libraries could have
15717      relocations against symbols in their debug information - the
15718      minimal symbol would have the right address, but the debug info
15719      would not.  It's no longer necessary, because we will explicitly
15720      apply relocations when we read in the debug information now.  */
15721
15722   /* A DW_AT_location attribute with no contents indicates that a
15723      variable has been optimized away.  */
15724   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
15725     {
15726       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15727       return;
15728     }
15729
15730   /* Handle one degenerate form of location expression specially, to
15731      preserve GDB's previous behavior when section offsets are
15732      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
15733      then mark this symbol as LOC_STATIC.  */
15734
15735   if (attr_form_is_block (attr)
15736       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
15737            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
15738           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
15739               && (DW_BLOCK (attr)->size
15740                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
15741     {
15742       unsigned int dummy;
15743
15744       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
15745         SYMBOL_VALUE_ADDRESS (sym) =
15746           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
15747       else
15748         SYMBOL_VALUE_ADDRESS (sym) =
15749           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
15750       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
15751       fixup_symbol_section (sym, objfile);
15752       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
15753                                               SYMBOL_SECTION (sym));
15754       return;
15755     }
15756
15757   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
15758      expression evaluator, and use LOC_COMPUTED only when necessary
15759      (i.e. when the value of a register or memory location is
15760      referenced, or a thread-local block, etc.).  Then again, it might
15761      not be worthwhile.  I'm assuming that it isn't unless performance
15762      or memory numbers show me otherwise.  */
15763
15764   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
15765
15766   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
15767     cu->has_loclist = 1;
15768 }
15769
15770 /* Given a pointer to a DWARF information entry, figure out if we need
15771    to make a symbol table entry for it, and if so, create a new entry
15772    and return a pointer to it.
15773    If TYPE is NULL, determine symbol type from the die, otherwise
15774    used the passed type.
15775    If SPACE is not NULL, use it to hold the new symbol.  If it is
15776    NULL, allocate a new symbol on the objfile's obstack.  */
15777
15778 static struct symbol *
15779 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
15780                  struct symbol *space)
15781 {
15782   struct objfile *objfile = cu->objfile;
15783   struct symbol *sym = NULL;
15784   const char *name;
15785   struct attribute *attr = NULL;
15786   struct attribute *attr2 = NULL;
15787   CORE_ADDR baseaddr;
15788   struct pending **list_to_add = NULL;
15789
15790   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
15791
15792   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
15793
15794   name = dwarf2_name (die, cu);
15795   if (name)
15796     {
15797       const char *linkagename;
15798       int suppress_add = 0;
15799
15800       if (space)
15801         sym = space;
15802       else
15803         sym = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symbol);
15804       OBJSTAT (objfile, n_syms++);
15805
15806       /* Cache this symbol's name and the name's demangled form (if any).  */
15807       SYMBOL_SET_LANGUAGE (sym, cu->language);
15808       linkagename = dwarf2_physname (name, die, cu);
15809       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
15810
15811       /* Fortran does not have mangling standard and the mangling does differ
15812          between gfortran, iFort etc.  */
15813       if (cu->language == language_fortran
15814           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
15815         symbol_set_demangled_name (&(sym->ginfo),
15816                                    dwarf2_full_name (name, die, cu),
15817                                    NULL);
15818
15819       /* Default assumptions.
15820          Use the passed type or decode it from the die.  */
15821       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
15822       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
15823       if (type != NULL)
15824         SYMBOL_TYPE (sym) = type;
15825       else
15826         SYMBOL_TYPE (sym) = die_type (die, cu);
15827       attr = dwarf2_attr (die,
15828                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
15829                           cu);
15830       if (attr)
15831         {
15832           SYMBOL_LINE (sym) = DW_UNSND (attr);
15833         }
15834
15835       attr = dwarf2_attr (die,
15836                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
15837                           cu);
15838       if (attr)
15839         {
15840           int file_index = DW_UNSND (attr);
15841
15842           if (cu->line_header == NULL
15843               || file_index > cu->line_header->num_file_names)
15844             complaint (&symfile_complaints,
15845                        _("file index out of range"));
15846           else if (file_index > 0)
15847             {
15848               struct file_entry *fe;
15849
15850               fe = &cu->line_header->file_names[file_index - 1];
15851               SYMBOL_SYMTAB (sym) = fe->symtab;
15852             }
15853         }
15854
15855       switch (die->tag)
15856         {
15857         case DW_TAG_label:
15858           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
15859           if (attr)
15860             {
15861               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
15862             }
15863           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
15864           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
15865           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
15866           add_symbol_to_list (sym, cu->list_in_scope);
15867           break;
15868         case DW_TAG_subprogram:
15869           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15870              finish_block.  */
15871           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
15872           attr2 = dwarf2_attr (die, DW_AT_external, cu);
15873           if ((attr2 && (DW_UNSND (attr2) != 0))
15874               || cu->language == language_ada)
15875             {
15876               /* Subprograms marked external are stored as a global symbol.
15877                  Ada subprograms, whether marked external or not, are always
15878                  stored as a global symbol, because we want to be able to
15879                  access them globally.  For instance, we want to be able
15880                  to break on a nested subprogram without having to
15881                  specify the context.  */
15882               list_to_add = &global_symbols;
15883             }
15884           else
15885             {
15886               list_to_add = cu->list_in_scope;
15887             }
15888           break;
15889         case DW_TAG_inlined_subroutine:
15890           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
15891              finish_block.  */
15892           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
15893           SYMBOL_INLINED (sym) = 1;
15894           list_to_add = cu->list_in_scope;
15895           break;
15896         case DW_TAG_template_value_param:
15897           suppress_add = 1;
15898           /* Fall through.  */
15899         case DW_TAG_constant:
15900         case DW_TAG_variable:
15901         case DW_TAG_member:
15902           /* Compilation with minimal debug info may result in
15903              variables with missing type entries.  Change the
15904              misleading `void' type to something sensible.  */
15905           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
15906             SYMBOL_TYPE (sym)
15907               = objfile_type (objfile)->nodebug_data_symbol;
15908
15909           attr = dwarf2_attr (die, DW_AT_const_value, cu);
15910           /* In the case of DW_TAG_member, we should only be called for
15911              static const members.  */
15912           if (die->tag == DW_TAG_member)
15913             {
15914               /* dwarf2_add_field uses die_is_declaration,
15915                  so we do the same.  */
15916               gdb_assert (die_is_declaration (die, cu));
15917               gdb_assert (attr);
15918             }
15919           if (attr)
15920             {
15921               dwarf2_const_value (attr, sym, cu);
15922               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15923               if (!suppress_add)
15924                 {
15925                   if (attr2 && (DW_UNSND (attr2) != 0))
15926                     list_to_add = &global_symbols;
15927                   else
15928                     list_to_add = cu->list_in_scope;
15929                 }
15930               break;
15931             }
15932           attr = dwarf2_attr (die, DW_AT_location, cu);
15933           if (attr)
15934             {
15935               var_decode_location (attr, sym, cu);
15936               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15937
15938               /* Fortran explicitly imports any global symbols to the local
15939                  scope by DW_TAG_common_block.  */
15940               if (cu->language == language_fortran && die->parent
15941                   && die->parent->tag == DW_TAG_common_block)
15942                 attr2 = NULL;
15943
15944               if (SYMBOL_CLASS (sym) == LOC_STATIC
15945                   && SYMBOL_VALUE_ADDRESS (sym) == 0
15946                   && !dwarf2_per_objfile->has_section_at_zero)
15947                 {
15948                   /* When a static variable is eliminated by the linker,
15949                      the corresponding debug information is not stripped
15950                      out, but the variable address is set to null;
15951                      do not add such variables into symbol table.  */
15952                 }
15953               else if (attr2 && (DW_UNSND (attr2) != 0))
15954                 {
15955                   /* Workaround gfortran PR debug/40040 - it uses
15956                      DW_AT_location for variables in -fPIC libraries which may
15957                      get overriden by other libraries/executable and get
15958                      a different address.  Resolve it by the minimal symbol
15959                      which may come from inferior's executable using copy
15960                      relocation.  Make this workaround only for gfortran as for
15961                      other compilers GDB cannot guess the minimal symbol
15962                      Fortran mangling kind.  */
15963                   if (cu->language == language_fortran && die->parent
15964                       && die->parent->tag == DW_TAG_module
15965                       && cu->producer
15966                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
15967                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
15968
15969                   /* A variable with DW_AT_external is never static,
15970                      but it may be block-scoped.  */
15971                   list_to_add = (cu->list_in_scope == &file_symbols
15972                                  ? &global_symbols : cu->list_in_scope);
15973                 }
15974               else
15975                 list_to_add = cu->list_in_scope;
15976             }
15977           else
15978             {
15979               /* We do not know the address of this symbol.
15980                  If it is an external symbol and we have type information
15981                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
15982                  The address of the variable will then be determined from
15983                  the minimal symbol table whenever the variable is
15984                  referenced.  */
15985               attr2 = dwarf2_attr (die, DW_AT_external, cu);
15986
15987               /* Fortran explicitly imports any global symbols to the local
15988                  scope by DW_TAG_common_block.  */
15989               if (cu->language == language_fortran && die->parent
15990                   && die->parent->tag == DW_TAG_common_block)
15991                 {
15992                   /* SYMBOL_CLASS doesn't matter here because
15993                      read_common_block is going to reset it.  */
15994                   if (!suppress_add)
15995                     list_to_add = cu->list_in_scope;
15996                 }
15997               else if (attr2 && (DW_UNSND (attr2) != 0)
15998                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
15999                 {
16000                   /* A variable with DW_AT_external is never static, but it
16001                      may be block-scoped.  */
16002                   list_to_add = (cu->list_in_scope == &file_symbols
16003                                  ? &global_symbols : cu->list_in_scope);
16004
16005                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
16006                 }
16007               else if (!die_is_declaration (die, cu))
16008                 {
16009                   /* Use the default LOC_OPTIMIZED_OUT class.  */
16010                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
16011                   if (!suppress_add)
16012                     list_to_add = cu->list_in_scope;
16013                 }
16014             }
16015           break;
16016         case DW_TAG_formal_parameter:
16017           /* If we are inside a function, mark this as an argument.  If
16018              not, we might be looking at an argument to an inlined function
16019              when we do not have enough information to show inlined frames;
16020              pretend it's a local variable in that case so that the user can
16021              still see it.  */
16022           if (context_stack_depth > 0
16023               && context_stack[context_stack_depth - 1].name != NULL)
16024             SYMBOL_IS_ARGUMENT (sym) = 1;
16025           attr = dwarf2_attr (die, DW_AT_location, cu);
16026           if (attr)
16027             {
16028               var_decode_location (attr, sym, cu);
16029             }
16030           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16031           if (attr)
16032             {
16033               dwarf2_const_value (attr, sym, cu);
16034             }
16035
16036           list_to_add = cu->list_in_scope;
16037           break;
16038         case DW_TAG_unspecified_parameters:
16039           /* From varargs functions; gdb doesn't seem to have any
16040              interest in this information, so just ignore it for now.
16041              (FIXME?) */
16042           break;
16043         case DW_TAG_template_type_param:
16044           suppress_add = 1;
16045           /* Fall through.  */
16046         case DW_TAG_class_type:
16047         case DW_TAG_interface_type:
16048         case DW_TAG_structure_type:
16049         case DW_TAG_union_type:
16050         case DW_TAG_set_type:
16051         case DW_TAG_enumeration_type:
16052           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16053           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
16054
16055           {
16056             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
16057                really ever be static objects: otherwise, if you try
16058                to, say, break of a class's method and you're in a file
16059                which doesn't mention that class, it won't work unless
16060                the check for all static symbols in lookup_symbol_aux
16061                saves you.  See the OtherFileClass tests in
16062                gdb.c++/namespace.exp.  */
16063
16064             if (!suppress_add)
16065               {
16066                 list_to_add = (cu->list_in_scope == &file_symbols
16067                                && (cu->language == language_cplus
16068                                    || cu->language == language_java)
16069                                ? &global_symbols : cu->list_in_scope);
16070
16071                 /* The semantics of C++ state that "struct foo {
16072                    ... }" also defines a typedef for "foo".  A Java
16073                    class declaration also defines a typedef for the
16074                    class.  */
16075                 if (cu->language == language_cplus
16076                     || cu->language == language_java
16077                     || cu->language == language_ada)
16078                   {
16079                     /* The symbol's name is already allocated along
16080                        with this objfile, so we don't need to
16081                        duplicate it for the type.  */
16082                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
16083                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
16084                   }
16085               }
16086           }
16087           break;
16088         case DW_TAG_typedef:
16089           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16090           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16091           list_to_add = cu->list_in_scope;
16092           break;
16093         case DW_TAG_base_type:
16094         case DW_TAG_subrange_type:
16095           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16096           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
16097           list_to_add = cu->list_in_scope;
16098           break;
16099         case DW_TAG_enumerator:
16100           attr = dwarf2_attr (die, DW_AT_const_value, cu);
16101           if (attr)
16102             {
16103               dwarf2_const_value (attr, sym, cu);
16104             }
16105           {
16106             /* NOTE: carlton/2003-11-10: See comment above in the
16107                DW_TAG_class_type, etc. block.  */
16108
16109             list_to_add = (cu->list_in_scope == &file_symbols
16110                            && (cu->language == language_cplus
16111                                || cu->language == language_java)
16112                            ? &global_symbols : cu->list_in_scope);
16113           }
16114           break;
16115         case DW_TAG_namespace:
16116           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
16117           list_to_add = &global_symbols;
16118           break;
16119         case DW_TAG_common_block:
16120           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
16121           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
16122           add_symbol_to_list (sym, cu->list_in_scope);
16123           break;
16124         default:
16125           /* Not a tag we recognize.  Hopefully we aren't processing
16126              trash data, but since we must specifically ignore things
16127              we don't recognize, there is nothing else we should do at
16128              this point.  */
16129           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
16130                      dwarf_tag_name (die->tag));
16131           break;
16132         }
16133
16134       if (suppress_add)
16135         {
16136           sym->hash_next = objfile->template_symbols;
16137           objfile->template_symbols = sym;
16138           list_to_add = NULL;
16139         }
16140
16141       if (list_to_add != NULL)
16142         add_symbol_to_list (sym, list_to_add);
16143
16144       /* For the benefit of old versions of GCC, check for anonymous
16145          namespaces based on the demangled name.  */
16146       if (!cu->processing_has_namespace_info
16147           && cu->language == language_cplus)
16148         cp_scan_for_anonymous_namespaces (sym, objfile);
16149     }
16150   return (sym);
16151 }
16152
16153 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
16154
16155 static struct symbol *
16156 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
16157 {
16158   return new_symbol_full (die, type, cu, NULL);
16159 }
16160
16161 /* Given an attr with a DW_FORM_dataN value in host byte order,
16162    zero-extend it as appropriate for the symbol's type.  The DWARF
16163    standard (v4) is not entirely clear about the meaning of using
16164    DW_FORM_dataN for a constant with a signed type, where the type is
16165    wider than the data.  The conclusion of a discussion on the DWARF
16166    list was that this is unspecified.  We choose to always zero-extend
16167    because that is the interpretation long in use by GCC.  */
16168
16169 static gdb_byte *
16170 dwarf2_const_value_data (struct attribute *attr, struct type *type,
16171                          const char *name, struct obstack *obstack,
16172                          struct dwarf2_cu *cu, LONGEST *value, int bits)
16173 {
16174   struct objfile *objfile = cu->objfile;
16175   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
16176                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
16177   LONGEST l = DW_UNSND (attr);
16178
16179   if (bits < sizeof (*value) * 8)
16180     {
16181       l &= ((LONGEST) 1 << bits) - 1;
16182       *value = l;
16183     }
16184   else if (bits == sizeof (*value) * 8)
16185     *value = l;
16186   else
16187     {
16188       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
16189       store_unsigned_integer (bytes, bits / 8, byte_order, l);
16190       return bytes;
16191     }
16192
16193   return NULL;
16194 }
16195
16196 /* Read a constant value from an attribute.  Either set *VALUE, or if
16197    the value does not fit in *VALUE, set *BYTES - either already
16198    allocated on the objfile obstack, or newly allocated on OBSTACK,
16199    or, set *BATON, if we translated the constant to a location
16200    expression.  */
16201
16202 static void
16203 dwarf2_const_value_attr (struct attribute *attr, struct type *type,
16204                          const char *name, struct obstack *obstack,
16205                          struct dwarf2_cu *cu,
16206                          LONGEST *value, gdb_byte **bytes,
16207                          struct dwarf2_locexpr_baton **baton)
16208 {
16209   struct objfile *objfile = cu->objfile;
16210   struct comp_unit_head *cu_header = &cu->header;
16211   struct dwarf_block *blk;
16212   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
16213                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
16214
16215   *value = 0;
16216   *bytes = NULL;
16217   *baton = NULL;
16218
16219   switch (attr->form)
16220     {
16221     case DW_FORM_addr:
16222     case DW_FORM_GNU_addr_index:
16223       {
16224         gdb_byte *data;
16225
16226         if (TYPE_LENGTH (type) != cu_header->addr_size)
16227           dwarf2_const_value_length_mismatch_complaint (name,
16228                                                         cu_header->addr_size,
16229                                                         TYPE_LENGTH (type));
16230         /* Symbols of this form are reasonably rare, so we just
16231            piggyback on the existing location code rather than writing
16232            a new implementation of symbol_computed_ops.  */
16233         *baton = obstack_alloc (&objfile->objfile_obstack,
16234                                 sizeof (struct dwarf2_locexpr_baton));
16235         (*baton)->per_cu = cu->per_cu;
16236         gdb_assert ((*baton)->per_cu);
16237
16238         (*baton)->size = 2 + cu_header->addr_size;
16239         data = obstack_alloc (&objfile->objfile_obstack, (*baton)->size);
16240         (*baton)->data = data;
16241
16242         data[0] = DW_OP_addr;
16243         store_unsigned_integer (&data[1], cu_header->addr_size,
16244                                 byte_order, DW_ADDR (attr));
16245         data[cu_header->addr_size + 1] = DW_OP_stack_value;
16246       }
16247       break;
16248     case DW_FORM_string:
16249     case DW_FORM_strp:
16250     case DW_FORM_GNU_str_index:
16251     case DW_FORM_GNU_strp_alt:
16252       /* DW_STRING is already allocated on the objfile obstack, point
16253          directly to it.  */
16254       *bytes = (gdb_byte *) DW_STRING (attr);
16255       break;
16256     case DW_FORM_block1:
16257     case DW_FORM_block2:
16258     case DW_FORM_block4:
16259     case DW_FORM_block:
16260     case DW_FORM_exprloc:
16261       blk = DW_BLOCK (attr);
16262       if (TYPE_LENGTH (type) != blk->size)
16263         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
16264                                                       TYPE_LENGTH (type));
16265       *bytes = blk->data;
16266       break;
16267
16268       /* The DW_AT_const_value attributes are supposed to carry the
16269          symbol's value "represented as it would be on the target
16270          architecture."  By the time we get here, it's already been
16271          converted to host endianness, so we just need to sign- or
16272          zero-extend it as appropriate.  */
16273     case DW_FORM_data1:
16274       *bytes = dwarf2_const_value_data (attr, type, name,
16275                                         obstack, cu, value, 8);
16276       break;
16277     case DW_FORM_data2:
16278       *bytes = dwarf2_const_value_data (attr, type, name,
16279                                         obstack, cu, value, 16);
16280       break;
16281     case DW_FORM_data4:
16282       *bytes = dwarf2_const_value_data (attr, type, name,
16283                                         obstack, cu, value, 32);
16284       break;
16285     case DW_FORM_data8:
16286       *bytes = dwarf2_const_value_data (attr, type, name,
16287                                         obstack, cu, value, 64);
16288       break;
16289
16290     case DW_FORM_sdata:
16291       *value = DW_SND (attr);
16292       break;
16293
16294     case DW_FORM_udata:
16295       *value = DW_UNSND (attr);
16296       break;
16297
16298     default:
16299       complaint (&symfile_complaints,
16300                  _("unsupported const value attribute form: '%s'"),
16301                  dwarf_form_name (attr->form));
16302       *value = 0;
16303       break;
16304     }
16305 }
16306
16307
16308 /* Copy constant value from an attribute to a symbol.  */
16309
16310 static void
16311 dwarf2_const_value (struct attribute *attr, struct symbol *sym,
16312                     struct dwarf2_cu *cu)
16313 {
16314   struct objfile *objfile = cu->objfile;
16315   struct comp_unit_head *cu_header = &cu->header;
16316   LONGEST value;
16317   gdb_byte *bytes;
16318   struct dwarf2_locexpr_baton *baton;
16319
16320   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
16321                            SYMBOL_PRINT_NAME (sym),
16322                            &objfile->objfile_obstack, cu,
16323                            &value, &bytes, &baton);
16324
16325   if (baton != NULL)
16326     {
16327       SYMBOL_LOCATION_BATON (sym) = baton;
16328       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16329     }
16330   else if (bytes != NULL)
16331      {
16332       SYMBOL_VALUE_BYTES (sym) = bytes;
16333       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
16334     }
16335   else
16336     {
16337       SYMBOL_VALUE (sym) = value;
16338       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
16339     }
16340 }
16341
16342 /* Return the type of the die in question using its DW_AT_type attribute.  */
16343
16344 static struct type *
16345 die_type (struct die_info *die, struct dwarf2_cu *cu)
16346 {
16347   struct attribute *type_attr;
16348
16349   type_attr = dwarf2_attr (die, DW_AT_type, cu);
16350   if (!type_attr)
16351     {
16352       /* A missing DW_AT_type represents a void type.  */
16353       return objfile_type (cu->objfile)->builtin_void;
16354     }
16355
16356   return lookup_die_type (die, type_attr, cu);
16357 }
16358
16359 /* True iff CU's producer generates GNAT Ada auxiliary information
16360    that allows to find parallel types through that information instead
16361    of having to do expensive parallel lookups by type name.  */
16362
16363 static int
16364 need_gnat_info (struct dwarf2_cu *cu)
16365 {
16366   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
16367      of GNAT produces this auxiliary information, without any indication
16368      that it is produced.  Part of enhancing the FSF version of GNAT
16369      to produce that information will be to put in place an indicator
16370      that we can use in order to determine whether the descriptive type
16371      info is available or not.  One suggestion that has been made is
16372      to use a new attribute, attached to the CU die.  For now, assume
16373      that the descriptive type info is not available.  */
16374   return 0;
16375 }
16376
16377 /* Return the auxiliary type of the die in question using its
16378    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
16379    attribute is not present.  */
16380
16381 static struct type *
16382 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
16383 {
16384   struct attribute *type_attr;
16385
16386   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
16387   if (!type_attr)
16388     return NULL;
16389
16390   return lookup_die_type (die, type_attr, cu);
16391 }
16392
16393 /* If DIE has a descriptive_type attribute, then set the TYPE's
16394    descriptive type accordingly.  */
16395
16396 static void
16397 set_descriptive_type (struct type *type, struct die_info *die,
16398                       struct dwarf2_cu *cu)
16399 {
16400   struct type *descriptive_type = die_descriptive_type (die, cu);
16401
16402   if (descriptive_type)
16403     {
16404       ALLOCATE_GNAT_AUX_TYPE (type);
16405       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
16406     }
16407 }
16408
16409 /* Return the containing type of the die in question using its
16410    DW_AT_containing_type attribute.  */
16411
16412 static struct type *
16413 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
16414 {
16415   struct attribute *type_attr;
16416
16417   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
16418   if (!type_attr)
16419     error (_("Dwarf Error: Problem turning containing type into gdb type "
16420              "[in module %s]"), cu->objfile->name);
16421
16422   return lookup_die_type (die, type_attr, cu);
16423 }
16424
16425 /* Look up the type of DIE in CU using its type attribute ATTR.
16426    If there is no type substitute an error marker.  */
16427
16428 static struct type *
16429 lookup_die_type (struct die_info *die, struct attribute *attr,
16430                  struct dwarf2_cu *cu)
16431 {
16432   struct objfile *objfile = cu->objfile;
16433   struct type *this_type;
16434
16435   /* First see if we have it cached.  */
16436
16437   if (attr->form == DW_FORM_GNU_ref_alt)
16438     {
16439       struct dwarf2_per_cu_data *per_cu;
16440       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16441
16442       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
16443       this_type = get_die_type_at_offset (offset, per_cu);
16444     }
16445   else if (is_ref_attr (attr))
16446     {
16447       sect_offset offset = dwarf2_get_ref_die_offset (attr);
16448
16449       this_type = get_die_type_at_offset (offset, cu->per_cu);
16450     }
16451   else if (attr->form == DW_FORM_ref_sig8)
16452     {
16453       struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
16454
16455       /* sig_type will be NULL if the signatured type is missing from
16456          the debug info.  */
16457       if (sig_type == NULL)
16458         error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
16459                  "at 0x%x [in module %s]"),
16460                die->offset.sect_off, objfile->name);
16461
16462       gdb_assert (sig_type->per_cu.is_debug_types);
16463       /* If we haven't filled in type_offset_in_section yet, then we
16464          haven't read the type in yet.  */
16465       this_type = NULL;
16466       if (sig_type->type_offset_in_section.sect_off != 0)
16467         {
16468           this_type =
16469             get_die_type_at_offset (sig_type->type_offset_in_section,
16470                                     &sig_type->per_cu);
16471         }
16472     }
16473   else
16474     {
16475       dump_die_for_error (die);
16476       error (_("Dwarf Error: Bad type attribute %s [in module %s]"),
16477              dwarf_attr_name (attr->name), objfile->name);
16478     }
16479
16480   /* If not cached we need to read it in.  */
16481
16482   if (this_type == NULL)
16483     {
16484       struct die_info *type_die;
16485       struct dwarf2_cu *type_cu = cu;
16486
16487       type_die = follow_die_ref_or_sig (die, attr, &type_cu);
16488       /* If we found the type now, it's probably because the type came
16489          from an inter-CU reference and the type's CU got expanded before
16490          ours.  */
16491       this_type = get_die_type (type_die, type_cu);
16492       if (this_type == NULL)
16493         this_type = read_type_die_1 (type_die, type_cu);
16494     }
16495
16496   /* If we still don't have a type use an error marker.  */
16497
16498   if (this_type == NULL)
16499     {
16500       char *message, *saved;
16501
16502       /* read_type_die already issued a complaint.  */
16503       message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
16504                             objfile->name,
16505                             cu->header.offset.sect_off,
16506                             die->offset.sect_off);
16507       saved = obstack_copy0 (&objfile->objfile_obstack,
16508                              message, strlen (message));
16509       xfree (message);
16510
16511       this_type = init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
16512     }
16513
16514   return this_type;
16515 }
16516
16517 /* Return the type in DIE, CU.
16518    Returns NULL for invalid types.
16519
16520    This first does a lookup in the appropriate type_hash table,
16521    and only reads the die in if necessary.
16522
16523    NOTE: This can be called when reading in partial or full symbols.  */
16524
16525 static struct type *
16526 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
16527 {
16528   struct type *this_type;
16529
16530   this_type = get_die_type (die, cu);
16531   if (this_type)
16532     return this_type;
16533
16534   return read_type_die_1 (die, cu);
16535 }
16536
16537 /* Read the type in DIE, CU.
16538    Returns NULL for invalid types.  */
16539
16540 static struct type *
16541 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
16542 {
16543   struct type *this_type = NULL;
16544
16545   switch (die->tag)
16546     {
16547     case DW_TAG_class_type:
16548     case DW_TAG_interface_type:
16549     case DW_TAG_structure_type:
16550     case DW_TAG_union_type:
16551       this_type = read_structure_type (die, cu);
16552       break;
16553     case DW_TAG_enumeration_type:
16554       this_type = read_enumeration_type (die, cu);
16555       break;
16556     case DW_TAG_subprogram:
16557     case DW_TAG_subroutine_type:
16558     case DW_TAG_inlined_subroutine:
16559       this_type = read_subroutine_type (die, cu);
16560       break;
16561     case DW_TAG_array_type:
16562       this_type = read_array_type (die, cu);
16563       break;
16564     case DW_TAG_set_type:
16565       this_type = read_set_type (die, cu);
16566       break;
16567     case DW_TAG_pointer_type:
16568       this_type = read_tag_pointer_type (die, cu);
16569       break;
16570     case DW_TAG_ptr_to_member_type:
16571       this_type = read_tag_ptr_to_member_type (die, cu);
16572       break;
16573     case DW_TAG_reference_type:
16574       this_type = read_tag_reference_type (die, cu);
16575       break;
16576     case DW_TAG_const_type:
16577       this_type = read_tag_const_type (die, cu);
16578       break;
16579     case DW_TAG_volatile_type:
16580       this_type = read_tag_volatile_type (die, cu);
16581       break;
16582     case DW_TAG_restrict_type:
16583       this_type = read_tag_restrict_type (die, cu);
16584       break;
16585     case DW_TAG_string_type:
16586       this_type = read_tag_string_type (die, cu);
16587       break;
16588     case DW_TAG_typedef:
16589       this_type = read_typedef (die, cu);
16590       break;
16591     case DW_TAG_subrange_type:
16592       this_type = read_subrange_type (die, cu);
16593       break;
16594     case DW_TAG_base_type:
16595       this_type = read_base_type (die, cu);
16596       break;
16597     case DW_TAG_unspecified_type:
16598       this_type = read_unspecified_type (die, cu);
16599       break;
16600     case DW_TAG_namespace:
16601       this_type = read_namespace_type (die, cu);
16602       break;
16603     case DW_TAG_module:
16604       this_type = read_module_type (die, cu);
16605       break;
16606     default:
16607       complaint (&symfile_complaints,
16608                  _("unexpected tag in read_type_die: '%s'"),
16609                  dwarf_tag_name (die->tag));
16610       break;
16611     }
16612
16613   return this_type;
16614 }
16615
16616 /* See if we can figure out if the class lives in a namespace.  We do
16617    this by looking for a member function; its demangled name will
16618    contain namespace info, if there is any.
16619    Return the computed name or NULL.
16620    Space for the result is allocated on the objfile's obstack.
16621    This is the full-die version of guess_partial_die_structure_name.
16622    In this case we know DIE has no useful parent.  */
16623
16624 static char *
16625 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
16626 {
16627   struct die_info *spec_die;
16628   struct dwarf2_cu *spec_cu;
16629   struct die_info *child;
16630
16631   spec_cu = cu;
16632   spec_die = die_specification (die, &spec_cu);
16633   if (spec_die != NULL)
16634     {
16635       die = spec_die;
16636       cu = spec_cu;
16637     }
16638
16639   for (child = die->child;
16640        child != NULL;
16641        child = child->sibling)
16642     {
16643       if (child->tag == DW_TAG_subprogram)
16644         {
16645           struct attribute *attr;
16646
16647           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
16648           if (attr == NULL)
16649             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
16650           if (attr != NULL)
16651             {
16652               char *actual_name
16653                 = language_class_name_from_physname (cu->language_defn,
16654                                                      DW_STRING (attr));
16655               char *name = NULL;
16656
16657               if (actual_name != NULL)
16658                 {
16659                   const char *die_name = dwarf2_name (die, cu);
16660
16661                   if (die_name != NULL
16662                       && strcmp (die_name, actual_name) != 0)
16663                     {
16664                       /* Strip off the class name from the full name.
16665                          We want the prefix.  */
16666                       int die_name_len = strlen (die_name);
16667                       int actual_name_len = strlen (actual_name);
16668
16669                       /* Test for '::' as a sanity check.  */
16670                       if (actual_name_len > die_name_len + 2
16671                           && actual_name[actual_name_len
16672                                          - die_name_len - 1] == ':')
16673                         name =
16674                           obstack_copy0 (&cu->objfile->objfile_obstack,
16675                                          actual_name,
16676                                          actual_name_len - die_name_len - 2);
16677                     }
16678                 }
16679               xfree (actual_name);
16680               return name;
16681             }
16682         }
16683     }
16684
16685   return NULL;
16686 }
16687
16688 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
16689    prefix part in such case.  See
16690    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16691
16692 static char *
16693 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
16694 {
16695   struct attribute *attr;
16696   char *base;
16697
16698   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
16699       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
16700     return NULL;
16701
16702   attr = dwarf2_attr (die, DW_AT_name, cu);
16703   if (attr != NULL && DW_STRING (attr) != NULL)
16704     return NULL;
16705
16706   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
16707   if (attr == NULL)
16708     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
16709   if (attr == NULL || DW_STRING (attr) == NULL)
16710     return NULL;
16711
16712   /* dwarf2_name had to be already called.  */
16713   gdb_assert (DW_STRING_IS_CANONICAL (attr));
16714
16715   /* Strip the base name, keep any leading namespaces/classes.  */
16716   base = strrchr (DW_STRING (attr), ':');
16717   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
16718     return "";
16719
16720   return obstack_copy0 (&cu->objfile->objfile_obstack,
16721                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
16722 }
16723
16724 /* Return the name of the namespace/class that DIE is defined within,
16725    or "" if we can't tell.  The caller should not xfree the result.
16726
16727    For example, if we're within the method foo() in the following
16728    code:
16729
16730    namespace N {
16731      class C {
16732        void foo () {
16733        }
16734      };
16735    }
16736
16737    then determine_prefix on foo's die will return "N::C".  */
16738
16739 static const char *
16740 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
16741 {
16742   struct die_info *parent, *spec_die;
16743   struct dwarf2_cu *spec_cu;
16744   struct type *parent_type;
16745   char *retval;
16746
16747   if (cu->language != language_cplus && cu->language != language_java
16748       && cu->language != language_fortran)
16749     return "";
16750
16751   retval = anonymous_struct_prefix (die, cu);
16752   if (retval)
16753     return retval;
16754
16755   /* We have to be careful in the presence of DW_AT_specification.
16756      For example, with GCC 3.4, given the code
16757
16758      namespace N {
16759        void foo() {
16760          // Definition of N::foo.
16761        }
16762      }
16763
16764      then we'll have a tree of DIEs like this:
16765
16766      1: DW_TAG_compile_unit
16767        2: DW_TAG_namespace        // N
16768          3: DW_TAG_subprogram     // declaration of N::foo
16769        4: DW_TAG_subprogram       // definition of N::foo
16770             DW_AT_specification   // refers to die #3
16771
16772      Thus, when processing die #4, we have to pretend that we're in
16773      the context of its DW_AT_specification, namely the contex of die
16774      #3.  */
16775   spec_cu = cu;
16776   spec_die = die_specification (die, &spec_cu);
16777   if (spec_die == NULL)
16778     parent = die->parent;
16779   else
16780     {
16781       parent = spec_die->parent;
16782       cu = spec_cu;
16783     }
16784
16785   if (parent == NULL)
16786     return "";
16787   else if (parent->building_fullname)
16788     {
16789       const char *name;
16790       const char *parent_name;
16791
16792       /* It has been seen on RealView 2.2 built binaries,
16793          DW_TAG_template_type_param types actually _defined_ as
16794          children of the parent class:
16795
16796          enum E {};
16797          template class <class Enum> Class{};
16798          Class<enum E> class_e;
16799
16800          1: DW_TAG_class_type (Class)
16801            2: DW_TAG_enumeration_type (E)
16802              3: DW_TAG_enumerator (enum1:0)
16803              3: DW_TAG_enumerator (enum2:1)
16804              ...
16805            2: DW_TAG_template_type_param
16806               DW_AT_type  DW_FORM_ref_udata (E)
16807
16808          Besides being broken debug info, it can put GDB into an
16809          infinite loop.  Consider:
16810
16811          When we're building the full name for Class<E>, we'll start
16812          at Class, and go look over its template type parameters,
16813          finding E.  We'll then try to build the full name of E, and
16814          reach here.  We're now trying to build the full name of E,
16815          and look over the parent DIE for containing scope.  In the
16816          broken case, if we followed the parent DIE of E, we'd again
16817          find Class, and once again go look at its template type
16818          arguments, etc., etc.  Simply don't consider such parent die
16819          as source-level parent of this die (it can't be, the language
16820          doesn't allow it), and break the loop here.  */
16821       name = dwarf2_name (die, cu);
16822       parent_name = dwarf2_name (parent, cu);
16823       complaint (&symfile_complaints,
16824                  _("template param type '%s' defined within parent '%s'"),
16825                  name ? name : "<unknown>",
16826                  parent_name ? parent_name : "<unknown>");
16827       return "";
16828     }
16829   else
16830     switch (parent->tag)
16831       {
16832       case DW_TAG_namespace:
16833         parent_type = read_type_die (parent, cu);
16834         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
16835            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
16836            Work around this problem here.  */
16837         if (cu->language == language_cplus
16838             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
16839           return "";
16840         /* We give a name to even anonymous namespaces.  */
16841         return TYPE_TAG_NAME (parent_type);
16842       case DW_TAG_class_type:
16843       case DW_TAG_interface_type:
16844       case DW_TAG_structure_type:
16845       case DW_TAG_union_type:
16846       case DW_TAG_module:
16847         parent_type = read_type_die (parent, cu);
16848         if (TYPE_TAG_NAME (parent_type) != NULL)
16849           return TYPE_TAG_NAME (parent_type);
16850         else
16851           /* An anonymous structure is only allowed non-static data
16852              members; no typedefs, no member functions, et cetera.
16853              So it does not need a prefix.  */
16854           return "";
16855       case DW_TAG_compile_unit:
16856       case DW_TAG_partial_unit:
16857         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
16858         if (cu->language == language_cplus
16859             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16860             && die->child != NULL
16861             && (die->tag == DW_TAG_class_type
16862                 || die->tag == DW_TAG_structure_type
16863                 || die->tag == DW_TAG_union_type))
16864           {
16865             char *name = guess_full_die_structure_name (die, cu);
16866             if (name != NULL)
16867               return name;
16868           }
16869         return "";
16870       default:
16871         return determine_prefix (parent, cu);
16872       }
16873 }
16874
16875 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
16876    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
16877    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
16878    an obconcat, otherwise allocate storage for the result.  The CU argument is
16879    used to determine the language and hence, the appropriate separator.  */
16880
16881 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
16882
16883 static char *
16884 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
16885                  int physname, struct dwarf2_cu *cu)
16886 {
16887   const char *lead = "";
16888   const char *sep;
16889
16890   if (suffix == NULL || suffix[0] == '\0'
16891       || prefix == NULL || prefix[0] == '\0')
16892     sep = "";
16893   else if (cu->language == language_java)
16894     sep = ".";
16895   else if (cu->language == language_fortran && physname)
16896     {
16897       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
16898          DW_AT_MIPS_linkage_name is preferred and used instead.  */
16899
16900       lead = "__";
16901       sep = "_MOD_";
16902     }
16903   else
16904     sep = "::";
16905
16906   if (prefix == NULL)
16907     prefix = "";
16908   if (suffix == NULL)
16909     suffix = "";
16910
16911   if (obs == NULL)
16912     {
16913       char *retval
16914         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
16915
16916       strcpy (retval, lead);
16917       strcat (retval, prefix);
16918       strcat (retval, sep);
16919       strcat (retval, suffix);
16920       return retval;
16921     }
16922   else
16923     {
16924       /* We have an obstack.  */
16925       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
16926     }
16927 }
16928
16929 /* Return sibling of die, NULL if no sibling.  */
16930
16931 static struct die_info *
16932 sibling_die (struct die_info *die)
16933 {
16934   return die->sibling;
16935 }
16936
16937 /* Get name of a die, return NULL if not found.  */
16938
16939 static const char *
16940 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
16941                           struct obstack *obstack)
16942 {
16943   if (name && cu->language == language_cplus)
16944     {
16945       char *canon_name = cp_canonicalize_string (name);
16946
16947       if (canon_name != NULL)
16948         {
16949           if (strcmp (canon_name, name) != 0)
16950             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
16951           xfree (canon_name);
16952         }
16953     }
16954
16955   return name;
16956 }
16957
16958 /* Get name of a die, return NULL if not found.  */
16959
16960 static const char *
16961 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
16962 {
16963   struct attribute *attr;
16964
16965   attr = dwarf2_attr (die, DW_AT_name, cu);
16966   if ((!attr || !DW_STRING (attr))
16967       && die->tag != DW_TAG_class_type
16968       && die->tag != DW_TAG_interface_type
16969       && die->tag != DW_TAG_structure_type
16970       && die->tag != DW_TAG_union_type)
16971     return NULL;
16972
16973   switch (die->tag)
16974     {
16975     case DW_TAG_compile_unit:
16976     case DW_TAG_partial_unit:
16977       /* Compilation units have a DW_AT_name that is a filename, not
16978          a source language identifier.  */
16979     case DW_TAG_enumeration_type:
16980     case DW_TAG_enumerator:
16981       /* These tags always have simple identifiers already; no need
16982          to canonicalize them.  */
16983       return DW_STRING (attr);
16984
16985     case DW_TAG_subprogram:
16986       /* Java constructors will all be named "<init>", so return
16987          the class name when we see this special case.  */
16988       if (cu->language == language_java
16989           && DW_STRING (attr) != NULL
16990           && strcmp (DW_STRING (attr), "<init>") == 0)
16991         {
16992           struct dwarf2_cu *spec_cu = cu;
16993           struct die_info *spec_die;
16994
16995           /* GCJ will output '<init>' for Java constructor names.
16996              For this special case, return the name of the parent class.  */
16997
16998           /* GCJ may output suprogram DIEs with AT_specification set.
16999              If so, use the name of the specified DIE.  */
17000           spec_die = die_specification (die, &spec_cu);
17001           if (spec_die != NULL)
17002             return dwarf2_name (spec_die, spec_cu);
17003
17004           do
17005             {
17006               die = die->parent;
17007               if (die->tag == DW_TAG_class_type)
17008                 return dwarf2_name (die, cu);
17009             }
17010           while (die->tag != DW_TAG_compile_unit
17011                  && die->tag != DW_TAG_partial_unit);
17012         }
17013       break;
17014
17015     case DW_TAG_class_type:
17016     case DW_TAG_interface_type:
17017     case DW_TAG_structure_type:
17018     case DW_TAG_union_type:
17019       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
17020          structures or unions.  These were of the form "._%d" in GCC 4.1,
17021          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
17022          and GCC 4.4.  We work around this problem by ignoring these.  */
17023       if (attr && DW_STRING (attr)
17024           && (strncmp (DW_STRING (attr), "._", 2) == 0
17025               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
17026         return NULL;
17027
17028       /* GCC might emit a nameless typedef that has a linkage name.  See
17029          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17030       if (!attr || DW_STRING (attr) == NULL)
17031         {
17032           char *demangled = NULL;
17033
17034           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
17035           if (attr == NULL)
17036             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
17037
17038           if (attr == NULL || DW_STRING (attr) == NULL)
17039             return NULL;
17040
17041           /* Avoid demangling DW_STRING (attr) the second time on a second
17042              call for the same DIE.  */
17043           if (!DW_STRING_IS_CANONICAL (attr))
17044             demangled = cplus_demangle (DW_STRING (attr), DMGL_TYPES);
17045
17046           if (demangled)
17047             {
17048               char *base;
17049
17050               /* FIXME: we already did this for the partial symbol... */
17051               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
17052                                                 demangled, strlen (demangled));
17053               DW_STRING_IS_CANONICAL (attr) = 1;
17054               xfree (demangled);
17055
17056               /* Strip any leading namespaces/classes, keep only the base name.
17057                  DW_AT_name for named DIEs does not contain the prefixes.  */
17058               base = strrchr (DW_STRING (attr), ':');
17059               if (base && base > DW_STRING (attr) && base[-1] == ':')
17060                 return &base[1];
17061               else
17062                 return DW_STRING (attr);
17063             }
17064         }
17065       break;
17066
17067     default:
17068       break;
17069     }
17070
17071   if (!DW_STRING_IS_CANONICAL (attr))
17072     {
17073       DW_STRING (attr)
17074         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
17075                                     &cu->objfile->objfile_obstack);
17076       DW_STRING_IS_CANONICAL (attr) = 1;
17077     }
17078   return DW_STRING (attr);
17079 }
17080
17081 /* Return the die that this die in an extension of, or NULL if there
17082    is none.  *EXT_CU is the CU containing DIE on input, and the CU
17083    containing the return value on output.  */
17084
17085 static struct die_info *
17086 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
17087 {
17088   struct attribute *attr;
17089
17090   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
17091   if (attr == NULL)
17092     return NULL;
17093
17094   return follow_die_ref (die, attr, ext_cu);
17095 }
17096
17097 /* Convert a DIE tag into its string name.  */
17098
17099 static const char *
17100 dwarf_tag_name (unsigned tag)
17101 {
17102   const char *name = get_DW_TAG_name (tag);
17103
17104   if (name == NULL)
17105     return "DW_TAG_<unknown>";
17106
17107   return name;
17108 }
17109
17110 /* Convert a DWARF attribute code into its string name.  */
17111
17112 static const char *
17113 dwarf_attr_name (unsigned attr)
17114 {
17115   const char *name;
17116
17117 #ifdef MIPS /* collides with DW_AT_HP_block_index */
17118   if (attr == DW_AT_MIPS_fde)
17119     return "DW_AT_MIPS_fde";
17120 #else
17121   if (attr == DW_AT_HP_block_index)
17122     return "DW_AT_HP_block_index";
17123 #endif
17124
17125   name = get_DW_AT_name (attr);
17126
17127   if (name == NULL)
17128     return "DW_AT_<unknown>";
17129
17130   return name;
17131 }
17132
17133 /* Convert a DWARF value form code into its string name.  */
17134
17135 static const char *
17136 dwarf_form_name (unsigned form)
17137 {
17138   const char *name = get_DW_FORM_name (form);
17139
17140   if (name == NULL)
17141     return "DW_FORM_<unknown>";
17142
17143   return name;
17144 }
17145
17146 static char *
17147 dwarf_bool_name (unsigned mybool)
17148 {
17149   if (mybool)
17150     return "TRUE";
17151   else
17152     return "FALSE";
17153 }
17154
17155 /* Convert a DWARF type code into its string name.  */
17156
17157 static const char *
17158 dwarf_type_encoding_name (unsigned enc)
17159 {
17160   const char *name = get_DW_ATE_name (enc);
17161
17162   if (name == NULL)
17163     return "DW_ATE_<unknown>";
17164
17165   return name;
17166 }
17167
17168 static void
17169 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
17170 {
17171   unsigned int i;
17172
17173   print_spaces (indent, f);
17174   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
17175            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
17176
17177   if (die->parent != NULL)
17178     {
17179       print_spaces (indent, f);
17180       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
17181                           die->parent->offset.sect_off);
17182     }
17183
17184   print_spaces (indent, f);
17185   fprintf_unfiltered (f, "  has children: %s\n",
17186            dwarf_bool_name (die->child != NULL));
17187
17188   print_spaces (indent, f);
17189   fprintf_unfiltered (f, "  attributes:\n");
17190
17191   for (i = 0; i < die->num_attrs; ++i)
17192     {
17193       print_spaces (indent, f);
17194       fprintf_unfiltered (f, "    %s (%s) ",
17195                dwarf_attr_name (die->attrs[i].name),
17196                dwarf_form_name (die->attrs[i].form));
17197
17198       switch (die->attrs[i].form)
17199         {
17200         case DW_FORM_addr:
17201         case DW_FORM_GNU_addr_index:
17202           fprintf_unfiltered (f, "address: ");
17203           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
17204           break;
17205         case DW_FORM_block2:
17206         case DW_FORM_block4:
17207         case DW_FORM_block:
17208         case DW_FORM_block1:
17209           fprintf_unfiltered (f, "block: size %s",
17210                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17211           break;
17212         case DW_FORM_exprloc:
17213           fprintf_unfiltered (f, "expression: size %s",
17214                               pulongest (DW_BLOCK (&die->attrs[i])->size));
17215           break;
17216         case DW_FORM_ref_addr:
17217           fprintf_unfiltered (f, "ref address: ");
17218           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17219           break;
17220         case DW_FORM_GNU_ref_alt:
17221           fprintf_unfiltered (f, "alt ref address: ");
17222           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
17223           break;
17224         case DW_FORM_ref1:
17225         case DW_FORM_ref2:
17226         case DW_FORM_ref4:
17227         case DW_FORM_ref8:
17228         case DW_FORM_ref_udata:
17229           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
17230                               (long) (DW_UNSND (&die->attrs[i])));
17231           break;
17232         case DW_FORM_data1:
17233         case DW_FORM_data2:
17234         case DW_FORM_data4:
17235         case DW_FORM_data8:
17236         case DW_FORM_udata:
17237         case DW_FORM_sdata:
17238           fprintf_unfiltered (f, "constant: %s",
17239                               pulongest (DW_UNSND (&die->attrs[i])));
17240           break;
17241         case DW_FORM_sec_offset:
17242           fprintf_unfiltered (f, "section offset: %s",
17243                               pulongest (DW_UNSND (&die->attrs[i])));
17244           break;
17245         case DW_FORM_ref_sig8:
17246           if (DW_SIGNATURED_TYPE (&die->attrs[i]) != NULL)
17247             fprintf_unfiltered (f, "signatured type, offset: 0x%x",
17248                          DW_SIGNATURED_TYPE (&die->attrs[i])->per_cu.offset.sect_off);
17249           else
17250             fprintf_unfiltered (f, "signatured type, offset: unknown");
17251           break;
17252         case DW_FORM_string:
17253         case DW_FORM_strp:
17254         case DW_FORM_GNU_str_index:
17255         case DW_FORM_GNU_strp_alt:
17256           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
17257                    DW_STRING (&die->attrs[i])
17258                    ? DW_STRING (&die->attrs[i]) : "",
17259                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
17260           break;
17261         case DW_FORM_flag:
17262           if (DW_UNSND (&die->attrs[i]))
17263             fprintf_unfiltered (f, "flag: TRUE");
17264           else
17265             fprintf_unfiltered (f, "flag: FALSE");
17266           break;
17267         case DW_FORM_flag_present:
17268           fprintf_unfiltered (f, "flag: TRUE");
17269           break;
17270         case DW_FORM_indirect:
17271           /* The reader will have reduced the indirect form to
17272              the "base form" so this form should not occur.  */
17273           fprintf_unfiltered (f, 
17274                               "unexpected attribute form: DW_FORM_indirect");
17275           break;
17276         default:
17277           fprintf_unfiltered (f, "unsupported attribute form: %d.",
17278                    die->attrs[i].form);
17279           break;
17280         }
17281       fprintf_unfiltered (f, "\n");
17282     }
17283 }
17284
17285 static void
17286 dump_die_for_error (struct die_info *die)
17287 {
17288   dump_die_shallow (gdb_stderr, 0, die);
17289 }
17290
17291 static void
17292 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
17293 {
17294   int indent = level * 4;
17295
17296   gdb_assert (die != NULL);
17297
17298   if (level >= max_level)
17299     return;
17300
17301   dump_die_shallow (f, indent, die);
17302
17303   if (die->child != NULL)
17304     {
17305       print_spaces (indent, f);
17306       fprintf_unfiltered (f, "  Children:");
17307       if (level + 1 < max_level)
17308         {
17309           fprintf_unfiltered (f, "\n");
17310           dump_die_1 (f, level + 1, max_level, die->child);
17311         }
17312       else
17313         {
17314           fprintf_unfiltered (f,
17315                               " [not printed, max nesting level reached]\n");
17316         }
17317     }
17318
17319   if (die->sibling != NULL && level > 0)
17320     {
17321       dump_die_1 (f, level, max_level, die->sibling);
17322     }
17323 }
17324
17325 /* This is called from the pdie macro in gdbinit.in.
17326    It's not static so gcc will keep a copy callable from gdb.  */
17327
17328 void
17329 dump_die (struct die_info *die, int max_level)
17330 {
17331   dump_die_1 (gdb_stdlog, 0, max_level, die);
17332 }
17333
17334 static void
17335 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
17336 {
17337   void **slot;
17338
17339   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
17340                                    INSERT);
17341
17342   *slot = die;
17343 }
17344
17345 /* DW_ADDR is always stored already as sect_offset; despite for the forms
17346    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
17347
17348 static int
17349 is_ref_attr (struct attribute *attr)
17350 {
17351   switch (attr->form)
17352     {
17353     case DW_FORM_ref_addr:
17354     case DW_FORM_ref1:
17355     case DW_FORM_ref2:
17356     case DW_FORM_ref4:
17357     case DW_FORM_ref8:
17358     case DW_FORM_ref_udata:
17359     case DW_FORM_GNU_ref_alt:
17360       return 1;
17361     default:
17362       return 0;
17363     }
17364 }
17365
17366 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
17367    required kind.  */
17368
17369 static sect_offset
17370 dwarf2_get_ref_die_offset (struct attribute *attr)
17371 {
17372   sect_offset retval = { DW_UNSND (attr) };
17373
17374   if (is_ref_attr (attr))
17375     return retval;
17376
17377   retval.sect_off = 0;
17378   complaint (&symfile_complaints,
17379              _("unsupported die ref attribute form: '%s'"),
17380              dwarf_form_name (attr->form));
17381   return retval;
17382 }
17383
17384 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
17385  * the value held by the attribute is not constant.  */
17386
17387 static LONGEST
17388 dwarf2_get_attr_constant_value (struct attribute *attr, int default_value)
17389 {
17390   if (attr->form == DW_FORM_sdata)
17391     return DW_SND (attr);
17392   else if (attr->form == DW_FORM_udata
17393            || attr->form == DW_FORM_data1
17394            || attr->form == DW_FORM_data2
17395            || attr->form == DW_FORM_data4
17396            || attr->form == DW_FORM_data8)
17397     return DW_UNSND (attr);
17398   else
17399     {
17400       complaint (&symfile_complaints,
17401                  _("Attribute value is not a constant (%s)"),
17402                  dwarf_form_name (attr->form));
17403       return default_value;
17404     }
17405 }
17406
17407 /* Follow reference or signature attribute ATTR of SRC_DIE.
17408    On entry *REF_CU is the CU of SRC_DIE.
17409    On exit *REF_CU is the CU of the result.  */
17410
17411 static struct die_info *
17412 follow_die_ref_or_sig (struct die_info *src_die, struct attribute *attr,
17413                        struct dwarf2_cu **ref_cu)
17414 {
17415   struct die_info *die;
17416
17417   if (is_ref_attr (attr))
17418     die = follow_die_ref (src_die, attr, ref_cu);
17419   else if (attr->form == DW_FORM_ref_sig8)
17420     die = follow_die_sig (src_die, attr, ref_cu);
17421   else
17422     {
17423       dump_die_for_error (src_die);
17424       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
17425              (*ref_cu)->objfile->name);
17426     }
17427
17428   return die;
17429 }
17430
17431 /* Follow reference OFFSET.
17432    On entry *REF_CU is the CU of the source die referencing OFFSET.
17433    On exit *REF_CU is the CU of the result.
17434    Returns NULL if OFFSET is invalid.  */
17435
17436 static struct die_info *
17437 follow_die_offset (sect_offset offset, int offset_in_dwz,
17438                    struct dwarf2_cu **ref_cu)
17439 {
17440   struct die_info temp_die;
17441   struct dwarf2_cu *target_cu, *cu = *ref_cu;
17442
17443   gdb_assert (cu->per_cu != NULL);
17444
17445   target_cu = cu;
17446
17447   if (cu->per_cu->is_debug_types)
17448     {
17449       /* .debug_types CUs cannot reference anything outside their CU.
17450          If they need to, they have to reference a signatured type via
17451          DW_FORM_ref_sig8.  */
17452       if (! offset_in_cu_p (&cu->header, offset))
17453         return NULL;
17454     }
17455   else if (offset_in_dwz != cu->per_cu->is_dwz
17456            || ! offset_in_cu_p (&cu->header, offset))
17457     {
17458       struct dwarf2_per_cu_data *per_cu;
17459
17460       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
17461                                                  cu->objfile);
17462
17463       /* If necessary, add it to the queue and load its DIEs.  */
17464       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
17465         load_full_comp_unit (per_cu, cu->language);
17466
17467       target_cu = per_cu->cu;
17468     }
17469   else if (cu->dies == NULL)
17470     {
17471       /* We're loading full DIEs during partial symbol reading.  */
17472       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
17473       load_full_comp_unit (cu->per_cu, language_minimal);
17474     }
17475
17476   *ref_cu = target_cu;
17477   temp_die.offset = offset;
17478   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
17479 }
17480
17481 /* Follow reference attribute ATTR of SRC_DIE.
17482    On entry *REF_CU is the CU of SRC_DIE.
17483    On exit *REF_CU is the CU of the result.  */
17484
17485 static struct die_info *
17486 follow_die_ref (struct die_info *src_die, struct attribute *attr,
17487                 struct dwarf2_cu **ref_cu)
17488 {
17489   sect_offset offset = dwarf2_get_ref_die_offset (attr);
17490   struct dwarf2_cu *cu = *ref_cu;
17491   struct die_info *die;
17492
17493   die = follow_die_offset (offset,
17494                            (attr->form == DW_FORM_GNU_ref_alt
17495                             || cu->per_cu->is_dwz),
17496                            ref_cu);
17497   if (!die)
17498     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
17499            "at 0x%x [in module %s]"),
17500            offset.sect_off, src_die->offset.sect_off, cu->objfile->name);
17501
17502   return die;
17503 }
17504
17505 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
17506    Returned value is intended for DW_OP_call*.  Returned
17507    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
17508
17509 struct dwarf2_locexpr_baton
17510 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
17511                                struct dwarf2_per_cu_data *per_cu,
17512                                CORE_ADDR (*get_frame_pc) (void *baton),
17513                                void *baton)
17514 {
17515   struct dwarf2_cu *cu;
17516   struct die_info *die;
17517   struct attribute *attr;
17518   struct dwarf2_locexpr_baton retval;
17519
17520   dw2_setup (per_cu->objfile);
17521
17522   if (per_cu->cu == NULL)
17523     load_cu (per_cu);
17524   cu = per_cu->cu;
17525
17526   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
17527   if (!die)
17528     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
17529            offset.sect_off, per_cu->objfile->name);
17530
17531   attr = dwarf2_attr (die, DW_AT_location, cu);
17532   if (!attr)
17533     {
17534       /* DWARF: "If there is no such attribute, then there is no effect.".
17535          DATA is ignored if SIZE is 0.  */
17536
17537       retval.data = NULL;
17538       retval.size = 0;
17539     }
17540   else if (attr_form_is_section_offset (attr))
17541     {
17542       struct dwarf2_loclist_baton loclist_baton;
17543       CORE_ADDR pc = (*get_frame_pc) (baton);
17544       size_t size;
17545
17546       fill_in_loclist_baton (cu, &loclist_baton, attr);
17547
17548       retval.data = dwarf2_find_location_expression (&loclist_baton,
17549                                                      &size, pc);
17550       retval.size = size;
17551     }
17552   else
17553     {
17554       if (!attr_form_is_block (attr))
17555         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
17556                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
17557                offset.sect_off, per_cu->objfile->name);
17558
17559       retval.data = DW_BLOCK (attr)->data;
17560       retval.size = DW_BLOCK (attr)->size;
17561     }
17562   retval.per_cu = cu->per_cu;
17563
17564   age_cached_comp_units ();
17565
17566   return retval;
17567 }
17568
17569 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
17570    offset.  */
17571
17572 struct dwarf2_locexpr_baton
17573 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
17574                              struct dwarf2_per_cu_data *per_cu,
17575                              CORE_ADDR (*get_frame_pc) (void *baton),
17576                              void *baton)
17577 {
17578   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
17579
17580   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
17581 }
17582
17583 /* Return the type of the DIE at DIE_OFFSET in the CU named by
17584    PER_CU.  */
17585
17586 struct type *
17587 dwarf2_get_die_type (cu_offset die_offset,
17588                      struct dwarf2_per_cu_data *per_cu)
17589 {
17590   sect_offset die_offset_sect;
17591
17592   dw2_setup (per_cu->objfile);
17593
17594   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
17595   return get_die_type_at_offset (die_offset_sect, per_cu);
17596 }
17597
17598 /* Follow the signature attribute ATTR in SRC_DIE.
17599    On entry *REF_CU is the CU of SRC_DIE.
17600    On exit *REF_CU is the CU of the result.  */
17601
17602 static struct die_info *
17603 follow_die_sig (struct die_info *src_die, struct attribute *attr,
17604                 struct dwarf2_cu **ref_cu)
17605 {
17606   struct objfile *objfile = (*ref_cu)->objfile;
17607   struct die_info temp_die;
17608   struct signatured_type *sig_type = DW_SIGNATURED_TYPE (attr);
17609   struct dwarf2_cu *sig_cu;
17610   struct die_info *die;
17611
17612   /* sig_type will be NULL if the signatured type is missing from
17613      the debug info.  */
17614   if (sig_type == NULL)
17615     error (_("Dwarf Error: Cannot find signatured DIE referenced from DIE "
17616              "at 0x%x [in module %s]"),
17617            src_die->offset.sect_off, objfile->name);
17618
17619   /* If necessary, add it to the queue and load its DIEs.  */
17620
17621   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
17622     read_signatured_type (sig_type);
17623
17624   gdb_assert (sig_type->per_cu.cu != NULL);
17625
17626   sig_cu = sig_type->per_cu.cu;
17627   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
17628   temp_die.offset = sig_type->type_offset_in_section;
17629   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
17630                              temp_die.offset.sect_off);
17631   if (die)
17632     {
17633       /* For .gdb_index version 7 keep track of included TUs.
17634          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
17635       if (dwarf2_per_objfile->index_table != NULL
17636           && dwarf2_per_objfile->index_table->version <= 7)
17637         {
17638           VEC_safe_push (dwarf2_per_cu_ptr,
17639                          (*ref_cu)->per_cu->imported_symtabs,
17640                          sig_cu->per_cu);
17641         }
17642
17643       *ref_cu = sig_cu;
17644       return die;
17645     }
17646
17647   error (_("Dwarf Error: Cannot find signatured DIE at 0x%x referenced "
17648          "from DIE at 0x%x [in module %s]"),
17649          temp_die.offset.sect_off, src_die->offset.sect_off, objfile->name);
17650 }
17651
17652 /* Given an offset of a signatured type, return its signatured_type.  */
17653
17654 static struct signatured_type *
17655 lookup_signatured_type_at_offset (struct objfile *objfile,
17656                                   struct dwarf2_section_info *section,
17657                                   sect_offset offset)
17658 {
17659   gdb_byte *info_ptr = section->buffer + offset.sect_off;
17660   unsigned int length, initial_length_size;
17661   unsigned int sig_offset;
17662   struct signatured_type find_entry, *sig_type;
17663
17664   length = read_initial_length (objfile->obfd, info_ptr, &initial_length_size);
17665   sig_offset = (initial_length_size
17666                 + 2 /*version*/
17667                 + (initial_length_size == 4 ? 4 : 8) /*debug_abbrev_offset*/
17668                 + 1 /*address_size*/);
17669   find_entry.signature = bfd_get_64 (objfile->obfd, info_ptr + sig_offset);
17670   sig_type = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
17671
17672   /* This is only used to lookup previously recorded types.
17673      If we didn't find it, it's our bug.  */
17674   gdb_assert (sig_type != NULL);
17675   gdb_assert (offset.sect_off == sig_type->per_cu.offset.sect_off);
17676
17677   return sig_type;
17678 }
17679
17680 /* Load the DIEs associated with type unit PER_CU into memory.  */
17681
17682 static void
17683 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
17684 {
17685   struct signatured_type *sig_type;
17686
17687   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
17688   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
17689
17690   /* We have the per_cu, but we need the signatured_type.
17691      Fortunately this is an easy translation.  */
17692   gdb_assert (per_cu->is_debug_types);
17693   sig_type = (struct signatured_type *) per_cu;
17694
17695   gdb_assert (per_cu->cu == NULL);
17696
17697   read_signatured_type (sig_type);
17698
17699   gdb_assert (per_cu->cu != NULL);
17700 }
17701
17702 /* die_reader_func for read_signatured_type.
17703    This is identical to load_full_comp_unit_reader,
17704    but is kept separate for now.  */
17705
17706 static void
17707 read_signatured_type_reader (const struct die_reader_specs *reader,
17708                              gdb_byte *info_ptr,
17709                              struct die_info *comp_unit_die,
17710                              int has_children,
17711                              void *data)
17712 {
17713   struct dwarf2_cu *cu = reader->cu;
17714
17715   gdb_assert (cu->die_hash == NULL);
17716   cu->die_hash =
17717     htab_create_alloc_ex (cu->header.length / 12,
17718                           die_hash,
17719                           die_eq,
17720                           NULL,
17721                           &cu->comp_unit_obstack,
17722                           hashtab_obstack_allocate,
17723                           dummy_obstack_deallocate);
17724
17725   if (has_children)
17726     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
17727                                                   &info_ptr, comp_unit_die);
17728   cu->dies = comp_unit_die;
17729   /* comp_unit_die is not stored in die_hash, no need.  */
17730
17731   /* We try not to read any attributes in this function, because not
17732      all CUs needed for references have been loaded yet, and symbol
17733      table processing isn't initialized.  But we have to set the CU language,
17734      or we won't be able to build types correctly.
17735      Similarly, if we do not read the producer, we can not apply
17736      producer-specific interpretation.  */
17737   prepare_one_comp_unit (cu, cu->dies, language_minimal);
17738 }
17739
17740 /* Read in a signatured type and build its CU and DIEs.
17741    If the type is a stub for the real type in a DWO file,
17742    read in the real type from the DWO file as well.  */
17743
17744 static void
17745 read_signatured_type (struct signatured_type *sig_type)
17746 {
17747   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
17748
17749   gdb_assert (per_cu->is_debug_types);
17750   gdb_assert (per_cu->cu == NULL);
17751
17752   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
17753                            read_signatured_type_reader, NULL);
17754 }
17755
17756 /* Decode simple location descriptions.
17757    Given a pointer to a dwarf block that defines a location, compute
17758    the location and return the value.
17759
17760    NOTE drow/2003-11-18: This function is called in two situations
17761    now: for the address of static or global variables (partial symbols
17762    only) and for offsets into structures which are expected to be
17763    (more or less) constant.  The partial symbol case should go away,
17764    and only the constant case should remain.  That will let this
17765    function complain more accurately.  A few special modes are allowed
17766    without complaint for global variables (for instance, global
17767    register values and thread-local values).
17768
17769    A location description containing no operations indicates that the
17770    object is optimized out.  The return value is 0 for that case.
17771    FIXME drow/2003-11-16: No callers check for this case any more; soon all
17772    callers will only want a very basic result and this can become a
17773    complaint.
17774
17775    Note that stack[0] is unused except as a default error return.  */
17776
17777 static CORE_ADDR
17778 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
17779 {
17780   struct objfile *objfile = cu->objfile;
17781   size_t i;
17782   size_t size = blk->size;
17783   gdb_byte *data = blk->data;
17784   CORE_ADDR stack[64];
17785   int stacki;
17786   unsigned int bytes_read, unsnd;
17787   gdb_byte op;
17788
17789   i = 0;
17790   stacki = 0;
17791   stack[stacki] = 0;
17792   stack[++stacki] = 0;
17793
17794   while (i < size)
17795     {
17796       op = data[i++];
17797       switch (op)
17798         {
17799         case DW_OP_lit0:
17800         case DW_OP_lit1:
17801         case DW_OP_lit2:
17802         case DW_OP_lit3:
17803         case DW_OP_lit4:
17804         case DW_OP_lit5:
17805         case DW_OP_lit6:
17806         case DW_OP_lit7:
17807         case DW_OP_lit8:
17808         case DW_OP_lit9:
17809         case DW_OP_lit10:
17810         case DW_OP_lit11:
17811         case DW_OP_lit12:
17812         case DW_OP_lit13:
17813         case DW_OP_lit14:
17814         case DW_OP_lit15:
17815         case DW_OP_lit16:
17816         case DW_OP_lit17:
17817         case DW_OP_lit18:
17818         case DW_OP_lit19:
17819         case DW_OP_lit20:
17820         case DW_OP_lit21:
17821         case DW_OP_lit22:
17822         case DW_OP_lit23:
17823         case DW_OP_lit24:
17824         case DW_OP_lit25:
17825         case DW_OP_lit26:
17826         case DW_OP_lit27:
17827         case DW_OP_lit28:
17828         case DW_OP_lit29:
17829         case DW_OP_lit30:
17830         case DW_OP_lit31:
17831           stack[++stacki] = op - DW_OP_lit0;
17832           break;
17833
17834         case DW_OP_reg0:
17835         case DW_OP_reg1:
17836         case DW_OP_reg2:
17837         case DW_OP_reg3:
17838         case DW_OP_reg4:
17839         case DW_OP_reg5:
17840         case DW_OP_reg6:
17841         case DW_OP_reg7:
17842         case DW_OP_reg8:
17843         case DW_OP_reg9:
17844         case DW_OP_reg10:
17845         case DW_OP_reg11:
17846         case DW_OP_reg12:
17847         case DW_OP_reg13:
17848         case DW_OP_reg14:
17849         case DW_OP_reg15:
17850         case DW_OP_reg16:
17851         case DW_OP_reg17:
17852         case DW_OP_reg18:
17853         case DW_OP_reg19:
17854         case DW_OP_reg20:
17855         case DW_OP_reg21:
17856         case DW_OP_reg22:
17857         case DW_OP_reg23:
17858         case DW_OP_reg24:
17859         case DW_OP_reg25:
17860         case DW_OP_reg26:
17861         case DW_OP_reg27:
17862         case DW_OP_reg28:
17863         case DW_OP_reg29:
17864         case DW_OP_reg30:
17865         case DW_OP_reg31:
17866           stack[++stacki] = op - DW_OP_reg0;
17867           if (i < size)
17868             dwarf2_complex_location_expr_complaint ();
17869           break;
17870
17871         case DW_OP_regx:
17872           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
17873           i += bytes_read;
17874           stack[++stacki] = unsnd;
17875           if (i < size)
17876             dwarf2_complex_location_expr_complaint ();
17877           break;
17878
17879         case DW_OP_addr:
17880           stack[++stacki] = read_address (objfile->obfd, &data[i],
17881                                           cu, &bytes_read);
17882           i += bytes_read;
17883           break;
17884
17885         case DW_OP_const1u:
17886           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
17887           i += 1;
17888           break;
17889
17890         case DW_OP_const1s:
17891           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
17892           i += 1;
17893           break;
17894
17895         case DW_OP_const2u:
17896           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
17897           i += 2;
17898           break;
17899
17900         case DW_OP_const2s:
17901           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
17902           i += 2;
17903           break;
17904
17905         case DW_OP_const4u:
17906           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
17907           i += 4;
17908           break;
17909
17910         case DW_OP_const4s:
17911           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
17912           i += 4;
17913           break;
17914
17915         case DW_OP_const8u:
17916           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
17917           i += 8;
17918           break;
17919
17920         case DW_OP_constu:
17921           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
17922                                                   &bytes_read);
17923           i += bytes_read;
17924           break;
17925
17926         case DW_OP_consts:
17927           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
17928           i += bytes_read;
17929           break;
17930
17931         case DW_OP_dup:
17932           stack[stacki + 1] = stack[stacki];
17933           stacki++;
17934           break;
17935
17936         case DW_OP_plus:
17937           stack[stacki - 1] += stack[stacki];
17938           stacki--;
17939           break;
17940
17941         case DW_OP_plus_uconst:
17942           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
17943                                                  &bytes_read);
17944           i += bytes_read;
17945           break;
17946
17947         case DW_OP_minus:
17948           stack[stacki - 1] -= stack[stacki];
17949           stacki--;
17950           break;
17951
17952         case DW_OP_deref:
17953           /* If we're not the last op, then we definitely can't encode
17954              this using GDB's address_class enum.  This is valid for partial
17955              global symbols, although the variable's address will be bogus
17956              in the psymtab.  */
17957           if (i < size)
17958             dwarf2_complex_location_expr_complaint ();
17959           break;
17960
17961         case DW_OP_GNU_push_tls_address:
17962           /* The top of the stack has the offset from the beginning
17963              of the thread control block at which the variable is located.  */
17964           /* Nothing should follow this operator, so the top of stack would
17965              be returned.  */
17966           /* This is valid for partial global symbols, but the variable's
17967              address will be bogus in the psymtab.  Make it always at least
17968              non-zero to not look as a variable garbage collected by linker
17969              which have DW_OP_addr 0.  */
17970           if (i < size)
17971             dwarf2_complex_location_expr_complaint ();
17972           stack[stacki]++;
17973           break;
17974
17975         case DW_OP_GNU_uninit:
17976           break;
17977
17978         case DW_OP_GNU_addr_index:
17979         case DW_OP_GNU_const_index:
17980           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
17981                                                          &bytes_read);
17982           i += bytes_read;
17983           break;
17984
17985         default:
17986           {
17987             const char *name = get_DW_OP_name (op);
17988
17989             if (name)
17990               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
17991                          name);
17992             else
17993               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
17994                          op);
17995           }
17996
17997           return (stack[stacki]);
17998         }
17999
18000       /* Enforce maximum stack depth of SIZE-1 to avoid writing
18001          outside of the allocated space.  Also enforce minimum>0.  */
18002       if (stacki >= ARRAY_SIZE (stack) - 1)
18003         {
18004           complaint (&symfile_complaints,
18005                      _("location description stack overflow"));
18006           return 0;
18007         }
18008
18009       if (stacki <= 0)
18010         {
18011           complaint (&symfile_complaints,
18012                      _("location description stack underflow"));
18013           return 0;
18014         }
18015     }
18016   return (stack[stacki]);
18017 }
18018
18019 /* memory allocation interface */
18020
18021 static struct dwarf_block *
18022 dwarf_alloc_block (struct dwarf2_cu *cu)
18023 {
18024   struct dwarf_block *blk;
18025
18026   blk = (struct dwarf_block *)
18027     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
18028   return (blk);
18029 }
18030
18031 static struct die_info *
18032 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
18033 {
18034   struct die_info *die;
18035   size_t size = sizeof (struct die_info);
18036
18037   if (num_attrs > 1)
18038     size += (num_attrs - 1) * sizeof (struct attribute);
18039
18040   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
18041   memset (die, 0, sizeof (struct die_info));
18042   return (die);
18043 }
18044
18045 \f
18046 /* Macro support.  */
18047
18048 /* Return file name relative to the compilation directory of file number I in
18049    *LH's file name table.  The result is allocated using xmalloc; the caller is
18050    responsible for freeing it.  */
18051
18052 static char *
18053 file_file_name (int file, struct line_header *lh)
18054 {
18055   /* Is the file number a valid index into the line header's file name
18056      table?  Remember that file numbers start with one, not zero.  */
18057   if (1 <= file && file <= lh->num_file_names)
18058     {
18059       struct file_entry *fe = &lh->file_names[file - 1];
18060
18061       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
18062         return xstrdup (fe->name);
18063       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
18064                      fe->name, NULL);
18065     }
18066   else
18067     {
18068       /* The compiler produced a bogus file number.  We can at least
18069          record the macro definitions made in the file, even if we
18070          won't be able to find the file by name.  */
18071       char fake_name[80];
18072
18073       xsnprintf (fake_name, sizeof (fake_name),
18074                  "<bad macro file number %d>", file);
18075
18076       complaint (&symfile_complaints,
18077                  _("bad file number in macro information (%d)"),
18078                  file);
18079
18080       return xstrdup (fake_name);
18081     }
18082 }
18083
18084 /* Return the full name of file number I in *LH's file name table.
18085    Use COMP_DIR as the name of the current directory of the
18086    compilation.  The result is allocated using xmalloc; the caller is
18087    responsible for freeing it.  */
18088 static char *
18089 file_full_name (int file, struct line_header *lh, const char *comp_dir)
18090 {
18091   /* Is the file number a valid index into the line header's file name
18092      table?  Remember that file numbers start with one, not zero.  */
18093   if (1 <= file && file <= lh->num_file_names)
18094     {
18095       char *relative = file_file_name (file, lh);
18096
18097       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
18098         return relative;
18099       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
18100     }
18101   else
18102     return file_file_name (file, lh);
18103 }
18104
18105
18106 static struct macro_source_file *
18107 macro_start_file (int file, int line,
18108                   struct macro_source_file *current_file,
18109                   const char *comp_dir,
18110                   struct line_header *lh, struct objfile *objfile)
18111 {
18112   /* File name relative to the compilation directory of this source file.  */
18113   char *file_name = file_file_name (file, lh);
18114
18115   /* We don't create a macro table for this compilation unit
18116      at all until we actually get a filename.  */
18117   if (! pending_macros)
18118     pending_macros = new_macro_table (&objfile->per_bfd->storage_obstack,
18119                                       objfile->per_bfd->macro_cache,
18120                                       comp_dir);
18121
18122   if (! current_file)
18123     {
18124       /* If we have no current file, then this must be the start_file
18125          directive for the compilation unit's main source file.  */
18126       current_file = macro_set_main (pending_macros, file_name);
18127       macro_define_special (pending_macros);
18128     }
18129   else
18130     current_file = macro_include (current_file, line, file_name);
18131
18132   xfree (file_name);
18133
18134   return current_file;
18135 }
18136
18137
18138 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
18139    followed by a null byte.  */
18140 static char *
18141 copy_string (const char *buf, int len)
18142 {
18143   char *s = xmalloc (len + 1);
18144
18145   memcpy (s, buf, len);
18146   s[len] = '\0';
18147   return s;
18148 }
18149
18150
18151 static const char *
18152 consume_improper_spaces (const char *p, const char *body)
18153 {
18154   if (*p == ' ')
18155     {
18156       complaint (&symfile_complaints,
18157                  _("macro definition contains spaces "
18158                    "in formal argument list:\n`%s'"),
18159                  body);
18160
18161       while (*p == ' ')
18162         p++;
18163     }
18164
18165   return p;
18166 }
18167
18168
18169 static void
18170 parse_macro_definition (struct macro_source_file *file, int line,
18171                         const char *body)
18172 {
18173   const char *p;
18174
18175   /* The body string takes one of two forms.  For object-like macro
18176      definitions, it should be:
18177
18178         <macro name> " " <definition>
18179
18180      For function-like macro definitions, it should be:
18181
18182         <macro name> "() " <definition>
18183      or
18184         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
18185
18186      Spaces may appear only where explicitly indicated, and in the
18187      <definition>.
18188
18189      The Dwarf 2 spec says that an object-like macro's name is always
18190      followed by a space, but versions of GCC around March 2002 omit
18191      the space when the macro's definition is the empty string.
18192
18193      The Dwarf 2 spec says that there should be no spaces between the
18194      formal arguments in a function-like macro's formal argument list,
18195      but versions of GCC around March 2002 include spaces after the
18196      commas.  */
18197
18198
18199   /* Find the extent of the macro name.  The macro name is terminated
18200      by either a space or null character (for an object-like macro) or
18201      an opening paren (for a function-like macro).  */
18202   for (p = body; *p; p++)
18203     if (*p == ' ' || *p == '(')
18204       break;
18205
18206   if (*p == ' ' || *p == '\0')
18207     {
18208       /* It's an object-like macro.  */
18209       int name_len = p - body;
18210       char *name = copy_string (body, name_len);
18211       const char *replacement;
18212
18213       if (*p == ' ')
18214         replacement = body + name_len + 1;
18215       else
18216         {
18217           dwarf2_macro_malformed_definition_complaint (body);
18218           replacement = body + name_len;
18219         }
18220
18221       macro_define_object (file, line, name, replacement);
18222
18223       xfree (name);
18224     }
18225   else if (*p == '(')
18226     {
18227       /* It's a function-like macro.  */
18228       char *name = copy_string (body, p - body);
18229       int argc = 0;
18230       int argv_size = 1;
18231       char **argv = xmalloc (argv_size * sizeof (*argv));
18232
18233       p++;
18234
18235       p = consume_improper_spaces (p, body);
18236
18237       /* Parse the formal argument list.  */
18238       while (*p && *p != ')')
18239         {
18240           /* Find the extent of the current argument name.  */
18241           const char *arg_start = p;
18242
18243           while (*p && *p != ',' && *p != ')' && *p != ' ')
18244             p++;
18245
18246           if (! *p || p == arg_start)
18247             dwarf2_macro_malformed_definition_complaint (body);
18248           else
18249             {
18250               /* Make sure argv has room for the new argument.  */
18251               if (argc >= argv_size)
18252                 {
18253                   argv_size *= 2;
18254                   argv = xrealloc (argv, argv_size * sizeof (*argv));
18255                 }
18256
18257               argv[argc++] = copy_string (arg_start, p - arg_start);
18258             }
18259
18260           p = consume_improper_spaces (p, body);
18261
18262           /* Consume the comma, if present.  */
18263           if (*p == ',')
18264             {
18265               p++;
18266
18267               p = consume_improper_spaces (p, body);
18268             }
18269         }
18270
18271       if (*p == ')')
18272         {
18273           p++;
18274
18275           if (*p == ' ')
18276             /* Perfectly formed definition, no complaints.  */
18277             macro_define_function (file, line, name,
18278                                    argc, (const char **) argv,
18279                                    p + 1);
18280           else if (*p == '\0')
18281             {
18282               /* Complain, but do define it.  */
18283               dwarf2_macro_malformed_definition_complaint (body);
18284               macro_define_function (file, line, name,
18285                                      argc, (const char **) argv,
18286                                      p);
18287             }
18288           else
18289             /* Just complain.  */
18290             dwarf2_macro_malformed_definition_complaint (body);
18291         }
18292       else
18293         /* Just complain.  */
18294         dwarf2_macro_malformed_definition_complaint (body);
18295
18296       xfree (name);
18297       {
18298         int i;
18299
18300         for (i = 0; i < argc; i++)
18301           xfree (argv[i]);
18302       }
18303       xfree (argv);
18304     }
18305   else
18306     dwarf2_macro_malformed_definition_complaint (body);
18307 }
18308
18309 /* Skip some bytes from BYTES according to the form given in FORM.
18310    Returns the new pointer.  */
18311
18312 static gdb_byte *
18313 skip_form_bytes (bfd *abfd, gdb_byte *bytes, gdb_byte *buffer_end,
18314                  enum dwarf_form form,
18315                  unsigned int offset_size,
18316                  struct dwarf2_section_info *section)
18317 {
18318   unsigned int bytes_read;
18319
18320   switch (form)
18321     {
18322     case DW_FORM_data1:
18323     case DW_FORM_flag:
18324       ++bytes;
18325       break;
18326
18327     case DW_FORM_data2:
18328       bytes += 2;
18329       break;
18330
18331     case DW_FORM_data4:
18332       bytes += 4;
18333       break;
18334
18335     case DW_FORM_data8:
18336       bytes += 8;
18337       break;
18338
18339     case DW_FORM_string:
18340       read_direct_string (abfd, bytes, &bytes_read);
18341       bytes += bytes_read;
18342       break;
18343
18344     case DW_FORM_sec_offset:
18345     case DW_FORM_strp:
18346     case DW_FORM_GNU_strp_alt:
18347       bytes += offset_size;
18348       break;
18349
18350     case DW_FORM_block:
18351       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
18352       bytes += bytes_read;
18353       break;
18354
18355     case DW_FORM_block1:
18356       bytes += 1 + read_1_byte (abfd, bytes);
18357       break;
18358     case DW_FORM_block2:
18359       bytes += 2 + read_2_bytes (abfd, bytes);
18360       break;
18361     case DW_FORM_block4:
18362       bytes += 4 + read_4_bytes (abfd, bytes);
18363       break;
18364
18365     case DW_FORM_sdata:
18366     case DW_FORM_udata:
18367     case DW_FORM_GNU_addr_index:
18368     case DW_FORM_GNU_str_index:
18369       bytes = (gdb_byte *) gdb_skip_leb128 (bytes, buffer_end);
18370       if (bytes == NULL)
18371         {
18372           dwarf2_section_buffer_overflow_complaint (section);
18373           return NULL;
18374         }
18375       break;
18376
18377     default:
18378       {
18379       complain:
18380         complaint (&symfile_complaints,
18381                    _("invalid form 0x%x in `%s'"),
18382                    form,
18383                    section->asection->name);
18384         return NULL;
18385       }
18386     }
18387
18388   return bytes;
18389 }
18390
18391 /* A helper for dwarf_decode_macros that handles skipping an unknown
18392    opcode.  Returns an updated pointer to the macro data buffer; or,
18393    on error, issues a complaint and returns NULL.  */
18394
18395 static gdb_byte *
18396 skip_unknown_opcode (unsigned int opcode,
18397                      gdb_byte **opcode_definitions,
18398                      gdb_byte *mac_ptr, gdb_byte *mac_end,
18399                      bfd *abfd,
18400                      unsigned int offset_size,
18401                      struct dwarf2_section_info *section)
18402 {
18403   unsigned int bytes_read, i;
18404   unsigned long arg;
18405   gdb_byte *defn;
18406
18407   if (opcode_definitions[opcode] == NULL)
18408     {
18409       complaint (&symfile_complaints,
18410                  _("unrecognized DW_MACFINO opcode 0x%x"),
18411                  opcode);
18412       return NULL;
18413     }
18414
18415   defn = opcode_definitions[opcode];
18416   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
18417   defn += bytes_read;
18418
18419   for (i = 0; i < arg; ++i)
18420     {
18421       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
18422                                  section);
18423       if (mac_ptr == NULL)
18424         {
18425           /* skip_form_bytes already issued the complaint.  */
18426           return NULL;
18427         }
18428     }
18429
18430   return mac_ptr;
18431 }
18432
18433 /* A helper function which parses the header of a macro section.
18434    If the macro section is the extended (for now called "GNU") type,
18435    then this updates *OFFSET_SIZE.  Returns a pointer to just after
18436    the header, or issues a complaint and returns NULL on error.  */
18437
18438 static gdb_byte *
18439 dwarf_parse_macro_header (gdb_byte **opcode_definitions,
18440                           bfd *abfd,
18441                           gdb_byte *mac_ptr,
18442                           unsigned int *offset_size,
18443                           int section_is_gnu)
18444 {
18445   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
18446
18447   if (section_is_gnu)
18448     {
18449       unsigned int version, flags;
18450
18451       version = read_2_bytes (abfd, mac_ptr);
18452       if (version != 4)
18453         {
18454           complaint (&symfile_complaints,
18455                      _("unrecognized version `%d' in .debug_macro section"),
18456                      version);
18457           return NULL;
18458         }
18459       mac_ptr += 2;
18460
18461       flags = read_1_byte (abfd, mac_ptr);
18462       ++mac_ptr;
18463       *offset_size = (flags & 1) ? 8 : 4;
18464
18465       if ((flags & 2) != 0)
18466         /* We don't need the line table offset.  */
18467         mac_ptr += *offset_size;
18468
18469       /* Vendor opcode descriptions.  */
18470       if ((flags & 4) != 0)
18471         {
18472           unsigned int i, count;
18473
18474           count = read_1_byte (abfd, mac_ptr);
18475           ++mac_ptr;
18476           for (i = 0; i < count; ++i)
18477             {
18478               unsigned int opcode, bytes_read;
18479               unsigned long arg;
18480
18481               opcode = read_1_byte (abfd, mac_ptr);
18482               ++mac_ptr;
18483               opcode_definitions[opcode] = mac_ptr;
18484               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18485               mac_ptr += bytes_read;
18486               mac_ptr += arg;
18487             }
18488         }
18489     }
18490
18491   return mac_ptr;
18492 }
18493
18494 /* A helper for dwarf_decode_macros that handles the GNU extensions,
18495    including DW_MACRO_GNU_transparent_include.  */
18496
18497 static void
18498 dwarf_decode_macro_bytes (bfd *abfd, gdb_byte *mac_ptr, gdb_byte *mac_end,
18499                           struct macro_source_file *current_file,
18500                           struct line_header *lh, const char *comp_dir,
18501                           struct dwarf2_section_info *section,
18502                           int section_is_gnu, int section_is_dwz,
18503                           unsigned int offset_size,
18504                           struct objfile *objfile,
18505                           htab_t include_hash)
18506 {
18507   enum dwarf_macro_record_type macinfo_type;
18508   int at_commandline;
18509   gdb_byte *opcode_definitions[256];
18510
18511   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18512                                       &offset_size, section_is_gnu);
18513   if (mac_ptr == NULL)
18514     {
18515       /* We already issued a complaint.  */
18516       return;
18517     }
18518
18519   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
18520      GDB is still reading the definitions from command line.  First
18521      DW_MACINFO_start_file will need to be ignored as it was already executed
18522      to create CURRENT_FILE for the main source holding also the command line
18523      definitions.  On first met DW_MACINFO_start_file this flag is reset to
18524      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
18525
18526   at_commandline = 1;
18527
18528   do
18529     {
18530       /* Do we at least have room for a macinfo type byte?  */
18531       if (mac_ptr >= mac_end)
18532         {
18533           dwarf2_section_buffer_overflow_complaint (section);
18534           break;
18535         }
18536
18537       macinfo_type = read_1_byte (abfd, mac_ptr);
18538       mac_ptr++;
18539
18540       /* Note that we rely on the fact that the corresponding GNU and
18541          DWARF constants are the same.  */
18542       switch (macinfo_type)
18543         {
18544           /* A zero macinfo type indicates the end of the macro
18545              information.  */
18546         case 0:
18547           break;
18548
18549         case DW_MACRO_GNU_define:
18550         case DW_MACRO_GNU_undef:
18551         case DW_MACRO_GNU_define_indirect:
18552         case DW_MACRO_GNU_undef_indirect:
18553         case DW_MACRO_GNU_define_indirect_alt:
18554         case DW_MACRO_GNU_undef_indirect_alt:
18555           {
18556             unsigned int bytes_read;
18557             int line;
18558             char *body;
18559             int is_define;
18560
18561             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18562             mac_ptr += bytes_read;
18563
18564             if (macinfo_type == DW_MACRO_GNU_define
18565                 || macinfo_type == DW_MACRO_GNU_undef)
18566               {
18567                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
18568                 mac_ptr += bytes_read;
18569               }
18570             else
18571               {
18572                 LONGEST str_offset;
18573
18574                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
18575                 mac_ptr += offset_size;
18576
18577                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
18578                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
18579                     || section_is_dwz)
18580                   {
18581                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
18582
18583                     body = read_indirect_string_from_dwz (dwz, str_offset);
18584                   }
18585                 else
18586                   body = read_indirect_string_at_offset (abfd, str_offset);
18587               }
18588
18589             is_define = (macinfo_type == DW_MACRO_GNU_define
18590                          || macinfo_type == DW_MACRO_GNU_define_indirect
18591                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
18592             if (! current_file)
18593               {
18594                 /* DWARF violation as no main source is present.  */
18595                 complaint (&symfile_complaints,
18596                            _("debug info with no main source gives macro %s "
18597                              "on line %d: %s"),
18598                            is_define ? _("definition") : _("undefinition"),
18599                            line, body);
18600                 break;
18601               }
18602             if ((line == 0 && !at_commandline)
18603                 || (line != 0 && at_commandline))
18604               complaint (&symfile_complaints,
18605                          _("debug info gives %s macro %s with %s line %d: %s"),
18606                          at_commandline ? _("command-line") : _("in-file"),
18607                          is_define ? _("definition") : _("undefinition"),
18608                          line == 0 ? _("zero") : _("non-zero"), line, body);
18609
18610             if (is_define)
18611               parse_macro_definition (current_file, line, body);
18612             else
18613               {
18614                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
18615                             || macinfo_type == DW_MACRO_GNU_undef_indirect
18616                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
18617                 macro_undef (current_file, line, body);
18618               }
18619           }
18620           break;
18621
18622         case DW_MACRO_GNU_start_file:
18623           {
18624             unsigned int bytes_read;
18625             int line, file;
18626
18627             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18628             mac_ptr += bytes_read;
18629             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18630             mac_ptr += bytes_read;
18631
18632             if ((line == 0 && !at_commandline)
18633                 || (line != 0 && at_commandline))
18634               complaint (&symfile_complaints,
18635                          _("debug info gives source %d included "
18636                            "from %s at %s line %d"),
18637                          file, at_commandline ? _("command-line") : _("file"),
18638                          line == 0 ? _("zero") : _("non-zero"), line);
18639
18640             if (at_commandline)
18641               {
18642                 /* This DW_MACRO_GNU_start_file was executed in the
18643                    pass one.  */
18644                 at_commandline = 0;
18645               }
18646             else
18647               current_file = macro_start_file (file, line,
18648                                                current_file, comp_dir,
18649                                                lh, objfile);
18650           }
18651           break;
18652
18653         case DW_MACRO_GNU_end_file:
18654           if (! current_file)
18655             complaint (&symfile_complaints,
18656                        _("macro debug info has an unmatched "
18657                          "`close_file' directive"));
18658           else
18659             {
18660               current_file = current_file->included_by;
18661               if (! current_file)
18662                 {
18663                   enum dwarf_macro_record_type next_type;
18664
18665                   /* GCC circa March 2002 doesn't produce the zero
18666                      type byte marking the end of the compilation
18667                      unit.  Complain if it's not there, but exit no
18668                      matter what.  */
18669
18670                   /* Do we at least have room for a macinfo type byte?  */
18671                   if (mac_ptr >= mac_end)
18672                     {
18673                       dwarf2_section_buffer_overflow_complaint (section);
18674                       return;
18675                     }
18676
18677                   /* We don't increment mac_ptr here, so this is just
18678                      a look-ahead.  */
18679                   next_type = read_1_byte (abfd, mac_ptr);
18680                   if (next_type != 0)
18681                     complaint (&symfile_complaints,
18682                                _("no terminating 0-type entry for "
18683                                  "macros in `.debug_macinfo' section"));
18684
18685                   return;
18686                 }
18687             }
18688           break;
18689
18690         case DW_MACRO_GNU_transparent_include:
18691         case DW_MACRO_GNU_transparent_include_alt:
18692           {
18693             LONGEST offset;
18694             void **slot;
18695             bfd *include_bfd = abfd;
18696             struct dwarf2_section_info *include_section = section;
18697             struct dwarf2_section_info alt_section;
18698             gdb_byte *include_mac_end = mac_end;
18699             int is_dwz = section_is_dwz;
18700             gdb_byte *new_mac_ptr;
18701
18702             offset = read_offset_1 (abfd, mac_ptr, offset_size);
18703             mac_ptr += offset_size;
18704
18705             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
18706               {
18707                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
18708
18709                 dwarf2_read_section (dwarf2_per_objfile->objfile,
18710                                      &dwz->macro);
18711
18712                 include_bfd = dwz->macro.asection->owner;
18713                 include_section = &dwz->macro;
18714                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
18715                 is_dwz = 1;
18716               }
18717
18718             new_mac_ptr = include_section->buffer + offset;
18719             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
18720
18721             if (*slot != NULL)
18722               {
18723                 /* This has actually happened; see
18724                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
18725                 complaint (&symfile_complaints,
18726                            _("recursive DW_MACRO_GNU_transparent_include in "
18727                              ".debug_macro section"));
18728               }
18729             else
18730               {
18731                 *slot = new_mac_ptr;
18732
18733                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
18734                                           include_mac_end, current_file,
18735                                           lh, comp_dir,
18736                                           section, section_is_gnu, is_dwz,
18737                                           offset_size, objfile, include_hash);
18738
18739                 htab_remove_elt (include_hash, new_mac_ptr);
18740               }
18741           }
18742           break;
18743
18744         case DW_MACINFO_vendor_ext:
18745           if (!section_is_gnu)
18746             {
18747               unsigned int bytes_read;
18748               int constant;
18749
18750               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18751               mac_ptr += bytes_read;
18752               read_direct_string (abfd, mac_ptr, &bytes_read);
18753               mac_ptr += bytes_read;
18754
18755               /* We don't recognize any vendor extensions.  */
18756               break;
18757             }
18758           /* FALLTHROUGH */
18759
18760         default:
18761           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18762                                          mac_ptr, mac_end, abfd, offset_size,
18763                                          section);
18764           if (mac_ptr == NULL)
18765             return;
18766           break;
18767         }
18768     } while (macinfo_type != 0);
18769 }
18770
18771 static void
18772 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
18773                      const char *comp_dir, int section_is_gnu)
18774 {
18775   struct objfile *objfile = dwarf2_per_objfile->objfile;
18776   struct line_header *lh = cu->line_header;
18777   bfd *abfd;
18778   gdb_byte *mac_ptr, *mac_end;
18779   struct macro_source_file *current_file = 0;
18780   enum dwarf_macro_record_type macinfo_type;
18781   unsigned int offset_size = cu->header.offset_size;
18782   gdb_byte *opcode_definitions[256];
18783   struct cleanup *cleanup;
18784   htab_t include_hash;
18785   void **slot;
18786   struct dwarf2_section_info *section;
18787   const char *section_name;
18788
18789   if (cu->dwo_unit != NULL)
18790     {
18791       if (section_is_gnu)
18792         {
18793           section = &cu->dwo_unit->dwo_file->sections.macro;
18794           section_name = ".debug_macro.dwo";
18795         }
18796       else
18797         {
18798           section = &cu->dwo_unit->dwo_file->sections.macinfo;
18799           section_name = ".debug_macinfo.dwo";
18800         }
18801     }
18802   else
18803     {
18804       if (section_is_gnu)
18805         {
18806           section = &dwarf2_per_objfile->macro;
18807           section_name = ".debug_macro";
18808         }
18809       else
18810         {
18811           section = &dwarf2_per_objfile->macinfo;
18812           section_name = ".debug_macinfo";
18813         }
18814     }
18815
18816   dwarf2_read_section (objfile, section);
18817   if (section->buffer == NULL)
18818     {
18819       complaint (&symfile_complaints, _("missing %s section"), section_name);
18820       return;
18821     }
18822   abfd = section->asection->owner;
18823
18824   /* First pass: Find the name of the base filename.
18825      This filename is needed in order to process all macros whose definition
18826      (or undefinition) comes from the command line.  These macros are defined
18827      before the first DW_MACINFO_start_file entry, and yet still need to be
18828      associated to the base file.
18829
18830      To determine the base file name, we scan the macro definitions until we
18831      reach the first DW_MACINFO_start_file entry.  We then initialize
18832      CURRENT_FILE accordingly so that any macro definition found before the
18833      first DW_MACINFO_start_file can still be associated to the base file.  */
18834
18835   mac_ptr = section->buffer + offset;
18836   mac_end = section->buffer + section->size;
18837
18838   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
18839                                       &offset_size, section_is_gnu);
18840   if (mac_ptr == NULL)
18841     {
18842       /* We already issued a complaint.  */
18843       return;
18844     }
18845
18846   do
18847     {
18848       /* Do we at least have room for a macinfo type byte?  */
18849       if (mac_ptr >= mac_end)
18850         {
18851           /* Complaint is printed during the second pass as GDB will probably
18852              stop the first pass earlier upon finding
18853              DW_MACINFO_start_file.  */
18854           break;
18855         }
18856
18857       macinfo_type = read_1_byte (abfd, mac_ptr);
18858       mac_ptr++;
18859
18860       /* Note that we rely on the fact that the corresponding GNU and
18861          DWARF constants are the same.  */
18862       switch (macinfo_type)
18863         {
18864           /* A zero macinfo type indicates the end of the macro
18865              information.  */
18866         case 0:
18867           break;
18868
18869         case DW_MACRO_GNU_define:
18870         case DW_MACRO_GNU_undef:
18871           /* Only skip the data by MAC_PTR.  */
18872           {
18873             unsigned int bytes_read;
18874
18875             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18876             mac_ptr += bytes_read;
18877             read_direct_string (abfd, mac_ptr, &bytes_read);
18878             mac_ptr += bytes_read;
18879           }
18880           break;
18881
18882         case DW_MACRO_GNU_start_file:
18883           {
18884             unsigned int bytes_read;
18885             int line, file;
18886
18887             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18888             mac_ptr += bytes_read;
18889             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18890             mac_ptr += bytes_read;
18891
18892             current_file = macro_start_file (file, line, current_file,
18893                                              comp_dir, lh, objfile);
18894           }
18895           break;
18896
18897         case DW_MACRO_GNU_end_file:
18898           /* No data to skip by MAC_PTR.  */
18899           break;
18900
18901         case DW_MACRO_GNU_define_indirect:
18902         case DW_MACRO_GNU_undef_indirect:
18903         case DW_MACRO_GNU_define_indirect_alt:
18904         case DW_MACRO_GNU_undef_indirect_alt:
18905           {
18906             unsigned int bytes_read;
18907
18908             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18909             mac_ptr += bytes_read;
18910             mac_ptr += offset_size;
18911           }
18912           break;
18913
18914         case DW_MACRO_GNU_transparent_include:
18915         case DW_MACRO_GNU_transparent_include_alt:
18916           /* Note that, according to the spec, a transparent include
18917              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
18918              skip this opcode.  */
18919           mac_ptr += offset_size;
18920           break;
18921
18922         case DW_MACINFO_vendor_ext:
18923           /* Only skip the data by MAC_PTR.  */
18924           if (!section_is_gnu)
18925             {
18926               unsigned int bytes_read;
18927
18928               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
18929               mac_ptr += bytes_read;
18930               read_direct_string (abfd, mac_ptr, &bytes_read);
18931               mac_ptr += bytes_read;
18932             }
18933           /* FALLTHROUGH */
18934
18935         default:
18936           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
18937                                          mac_ptr, mac_end, abfd, offset_size,
18938                                          section);
18939           if (mac_ptr == NULL)
18940             return;
18941           break;
18942         }
18943     } while (macinfo_type != 0 && current_file == NULL);
18944
18945   /* Second pass: Process all entries.
18946
18947      Use the AT_COMMAND_LINE flag to determine whether we are still processing
18948      command-line macro definitions/undefinitions.  This flag is unset when we
18949      reach the first DW_MACINFO_start_file entry.  */
18950
18951   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
18952                                     NULL, xcalloc, xfree);
18953   cleanup = make_cleanup_htab_delete (include_hash);
18954   mac_ptr = section->buffer + offset;
18955   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
18956   *slot = mac_ptr;
18957   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
18958                             current_file, lh, comp_dir, section,
18959                             section_is_gnu, 0,
18960                             offset_size, objfile, include_hash);
18961   do_cleanups (cleanup);
18962 }
18963
18964 /* Check if the attribute's form is a DW_FORM_block*
18965    if so return true else false.  */
18966
18967 static int
18968 attr_form_is_block (struct attribute *attr)
18969 {
18970   return (attr == NULL ? 0 :
18971       attr->form == DW_FORM_block1
18972       || attr->form == DW_FORM_block2
18973       || attr->form == DW_FORM_block4
18974       || attr->form == DW_FORM_block
18975       || attr->form == DW_FORM_exprloc);
18976 }
18977
18978 /* Return non-zero if ATTR's value is a section offset --- classes
18979    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
18980    You may use DW_UNSND (attr) to retrieve such offsets.
18981
18982    Section 7.5.4, "Attribute Encodings", explains that no attribute
18983    may have a value that belongs to more than one of these classes; it
18984    would be ambiguous if we did, because we use the same forms for all
18985    of them.  */
18986
18987 static int
18988 attr_form_is_section_offset (struct attribute *attr)
18989 {
18990   return (attr->form == DW_FORM_data4
18991           || attr->form == DW_FORM_data8
18992           || attr->form == DW_FORM_sec_offset);
18993 }
18994
18995 /* Return non-zero if ATTR's value falls in the 'constant' class, or
18996    zero otherwise.  When this function returns true, you can apply
18997    dwarf2_get_attr_constant_value to it.
18998
18999    However, note that for some attributes you must check
19000    attr_form_is_section_offset before using this test.  DW_FORM_data4
19001    and DW_FORM_data8 are members of both the constant class, and of
19002    the classes that contain offsets into other debug sections
19003    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
19004    that, if an attribute's can be either a constant or one of the
19005    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
19006    taken as section offsets, not constants.  */
19007
19008 static int
19009 attr_form_is_constant (struct attribute *attr)
19010 {
19011   switch (attr->form)
19012     {
19013     case DW_FORM_sdata:
19014     case DW_FORM_udata:
19015     case DW_FORM_data1:
19016     case DW_FORM_data2:
19017     case DW_FORM_data4:
19018     case DW_FORM_data8:
19019       return 1;
19020     default:
19021       return 0;
19022     }
19023 }
19024
19025 /* Return the .debug_loc section to use for CU.
19026    For DWO files use .debug_loc.dwo.  */
19027
19028 static struct dwarf2_section_info *
19029 cu_debug_loc_section (struct dwarf2_cu *cu)
19030 {
19031   if (cu->dwo_unit)
19032     return &cu->dwo_unit->dwo_file->sections.loc;
19033   return &dwarf2_per_objfile->loc;
19034 }
19035
19036 /* A helper function that fills in a dwarf2_loclist_baton.  */
19037
19038 static void
19039 fill_in_loclist_baton (struct dwarf2_cu *cu,
19040                        struct dwarf2_loclist_baton *baton,
19041                        struct attribute *attr)
19042 {
19043   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19044
19045   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
19046
19047   baton->per_cu = cu->per_cu;
19048   gdb_assert (baton->per_cu);
19049   /* We don't know how long the location list is, but make sure we
19050      don't run off the edge of the section.  */
19051   baton->size = section->size - DW_UNSND (attr);
19052   baton->data = section->buffer + DW_UNSND (attr);
19053   baton->base_address = cu->base_address;
19054   baton->from_dwo = cu->dwo_unit != NULL;
19055 }
19056
19057 static void
19058 dwarf2_symbol_mark_computed (struct attribute *attr, struct symbol *sym,
19059                              struct dwarf2_cu *cu, int is_block)
19060 {
19061   struct objfile *objfile = dwarf2_per_objfile->objfile;
19062   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
19063
19064   if (attr_form_is_section_offset (attr)
19065       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
19066          the section.  If so, fall through to the complaint in the
19067          other branch.  */
19068       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
19069     {
19070       struct dwarf2_loclist_baton *baton;
19071
19072       baton = obstack_alloc (&objfile->objfile_obstack,
19073                              sizeof (struct dwarf2_loclist_baton));
19074
19075       fill_in_loclist_baton (cu, baton, attr);
19076
19077       if (cu->base_known == 0)
19078         complaint (&symfile_complaints,
19079                    _("Location list used without "
19080                      "specifying the CU base address."));
19081
19082       SYMBOL_ACLASS_INDEX (sym) = (is_block
19083                                    ? dwarf2_loclist_block_index
19084                                    : dwarf2_loclist_index);
19085       SYMBOL_LOCATION_BATON (sym) = baton;
19086     }
19087   else
19088     {
19089       struct dwarf2_locexpr_baton *baton;
19090
19091       baton = obstack_alloc (&objfile->objfile_obstack,
19092                              sizeof (struct dwarf2_locexpr_baton));
19093       baton->per_cu = cu->per_cu;
19094       gdb_assert (baton->per_cu);
19095
19096       if (attr_form_is_block (attr))
19097         {
19098           /* Note that we're just copying the block's data pointer
19099              here, not the actual data.  We're still pointing into the
19100              info_buffer for SYM's objfile; right now we never release
19101              that buffer, but when we do clean up properly this may
19102              need to change.  */
19103           baton->size = DW_BLOCK (attr)->size;
19104           baton->data = DW_BLOCK (attr)->data;
19105         }
19106       else
19107         {
19108           dwarf2_invalid_attrib_class_complaint ("location description",
19109                                                  SYMBOL_NATURAL_NAME (sym));
19110           baton->size = 0;
19111         }
19112
19113       SYMBOL_ACLASS_INDEX (sym) = (is_block
19114                                    ? dwarf2_locexpr_block_index
19115                                    : dwarf2_locexpr_index);
19116       SYMBOL_LOCATION_BATON (sym) = baton;
19117     }
19118 }
19119
19120 /* Return the OBJFILE associated with the compilation unit CU.  If CU
19121    came from a separate debuginfo file, then the master objfile is
19122    returned.  */
19123
19124 struct objfile *
19125 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
19126 {
19127   struct objfile *objfile = per_cu->objfile;
19128
19129   /* Return the master objfile, so that we can report and look up the
19130      correct file containing this variable.  */
19131   if (objfile->separate_debug_objfile_backlink)
19132     objfile = objfile->separate_debug_objfile_backlink;
19133
19134   return objfile;
19135 }
19136
19137 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
19138    (CU_HEADERP is unused in such case) or prepare a temporary copy at
19139    CU_HEADERP first.  */
19140
19141 static const struct comp_unit_head *
19142 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
19143                        struct dwarf2_per_cu_data *per_cu)
19144 {
19145   gdb_byte *info_ptr;
19146
19147   if (per_cu->cu)
19148     return &per_cu->cu->header;
19149
19150   info_ptr = per_cu->info_or_types_section->buffer + per_cu->offset.sect_off;
19151
19152   memset (cu_headerp, 0, sizeof (*cu_headerp));
19153   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
19154
19155   return cu_headerp;
19156 }
19157
19158 /* Return the address size given in the compilation unit header for CU.  */
19159
19160 int
19161 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
19162 {
19163   struct comp_unit_head cu_header_local;
19164   const struct comp_unit_head *cu_headerp;
19165
19166   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19167
19168   return cu_headerp->addr_size;
19169 }
19170
19171 /* Return the offset size given in the compilation unit header for CU.  */
19172
19173 int
19174 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
19175 {
19176   struct comp_unit_head cu_header_local;
19177   const struct comp_unit_head *cu_headerp;
19178
19179   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19180
19181   return cu_headerp->offset_size;
19182 }
19183
19184 /* See its dwarf2loc.h declaration.  */
19185
19186 int
19187 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
19188 {
19189   struct comp_unit_head cu_header_local;
19190   const struct comp_unit_head *cu_headerp;
19191
19192   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
19193
19194   if (cu_headerp->version == 2)
19195     return cu_headerp->addr_size;
19196   else
19197     return cu_headerp->offset_size;
19198 }
19199
19200 /* Return the text offset of the CU.  The returned offset comes from
19201    this CU's objfile.  If this objfile came from a separate debuginfo
19202    file, then the offset may be different from the corresponding
19203    offset in the parent objfile.  */
19204
19205 CORE_ADDR
19206 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
19207 {
19208   struct objfile *objfile = per_cu->objfile;
19209
19210   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19211 }
19212
19213 /* Locate the .debug_info compilation unit from CU's objfile which contains
19214    the DIE at OFFSET.  Raises an error on failure.  */
19215
19216 static struct dwarf2_per_cu_data *
19217 dwarf2_find_containing_comp_unit (sect_offset offset,
19218                                   unsigned int offset_in_dwz,
19219                                   struct objfile *objfile)
19220 {
19221   struct dwarf2_per_cu_data *this_cu;
19222   int low, high;
19223   const sect_offset *cu_off;
19224
19225   low = 0;
19226   high = dwarf2_per_objfile->n_comp_units - 1;
19227   while (high > low)
19228     {
19229       struct dwarf2_per_cu_data *mid_cu;
19230       int mid = low + (high - low) / 2;
19231
19232       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
19233       cu_off = &mid_cu->offset;
19234       if (mid_cu->is_dwz > offset_in_dwz
19235           || (mid_cu->is_dwz == offset_in_dwz
19236               && cu_off->sect_off >= offset.sect_off))
19237         high = mid;
19238       else
19239         low = mid + 1;
19240     }
19241   gdb_assert (low == high);
19242   this_cu = dwarf2_per_objfile->all_comp_units[low];
19243   cu_off = &this_cu->offset;
19244   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
19245     {
19246       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
19247         error (_("Dwarf Error: could not find partial DIE containing "
19248                "offset 0x%lx [in module %s]"),
19249                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
19250
19251       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
19252                   <= offset.sect_off);
19253       return dwarf2_per_objfile->all_comp_units[low-1];
19254     }
19255   else
19256     {
19257       this_cu = dwarf2_per_objfile->all_comp_units[low];
19258       if (low == dwarf2_per_objfile->n_comp_units - 1
19259           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
19260         error (_("invalid dwarf2 offset %u"), offset.sect_off);
19261       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
19262       return this_cu;
19263     }
19264 }
19265
19266 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
19267
19268 static void
19269 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
19270 {
19271   memset (cu, 0, sizeof (*cu));
19272   per_cu->cu = cu;
19273   cu->per_cu = per_cu;
19274   cu->objfile = per_cu->objfile;
19275   obstack_init (&cu->comp_unit_obstack);
19276 }
19277
19278 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
19279
19280 static void
19281 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
19282                        enum language pretend_language)
19283 {
19284   struct attribute *attr;
19285
19286   /* Set the language we're debugging.  */
19287   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
19288   if (attr)
19289     set_cu_language (DW_UNSND (attr), cu);
19290   else
19291     {
19292       cu->language = pretend_language;
19293       cu->language_defn = language_def (cu->language);
19294     }
19295
19296   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
19297   if (attr)
19298     cu->producer = DW_STRING (attr);
19299 }
19300
19301 /* Release one cached compilation unit, CU.  We unlink it from the tree
19302    of compilation units, but we don't remove it from the read_in_chain;
19303    the caller is responsible for that.
19304    NOTE: DATA is a void * because this function is also used as a
19305    cleanup routine.  */
19306
19307 static void
19308 free_heap_comp_unit (void *data)
19309 {
19310   struct dwarf2_cu *cu = data;
19311
19312   gdb_assert (cu->per_cu != NULL);
19313   cu->per_cu->cu = NULL;
19314   cu->per_cu = NULL;
19315
19316   obstack_free (&cu->comp_unit_obstack, NULL);
19317
19318   xfree (cu);
19319 }
19320
19321 /* This cleanup function is passed the address of a dwarf2_cu on the stack
19322    when we're finished with it.  We can't free the pointer itself, but be
19323    sure to unlink it from the cache.  Also release any associated storage.  */
19324
19325 static void
19326 free_stack_comp_unit (void *data)
19327 {
19328   struct dwarf2_cu *cu = data;
19329
19330   gdb_assert (cu->per_cu != NULL);
19331   cu->per_cu->cu = NULL;
19332   cu->per_cu = NULL;
19333
19334   obstack_free (&cu->comp_unit_obstack, NULL);
19335   cu->partial_dies = NULL;
19336 }
19337
19338 /* Free all cached compilation units.  */
19339
19340 static void
19341 free_cached_comp_units (void *data)
19342 {
19343   struct dwarf2_per_cu_data *per_cu, **last_chain;
19344
19345   per_cu = dwarf2_per_objfile->read_in_chain;
19346   last_chain = &dwarf2_per_objfile->read_in_chain;
19347   while (per_cu != NULL)
19348     {
19349       struct dwarf2_per_cu_data *next_cu;
19350
19351       next_cu = per_cu->cu->read_in_chain;
19352
19353       free_heap_comp_unit (per_cu->cu);
19354       *last_chain = next_cu;
19355
19356       per_cu = next_cu;
19357     }
19358 }
19359
19360 /* Increase the age counter on each cached compilation unit, and free
19361    any that are too old.  */
19362
19363 static void
19364 age_cached_comp_units (void)
19365 {
19366   struct dwarf2_per_cu_data *per_cu, **last_chain;
19367
19368   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
19369   per_cu = dwarf2_per_objfile->read_in_chain;
19370   while (per_cu != NULL)
19371     {
19372       per_cu->cu->last_used ++;
19373       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
19374         dwarf2_mark (per_cu->cu);
19375       per_cu = per_cu->cu->read_in_chain;
19376     }
19377
19378   per_cu = dwarf2_per_objfile->read_in_chain;
19379   last_chain = &dwarf2_per_objfile->read_in_chain;
19380   while (per_cu != NULL)
19381     {
19382       struct dwarf2_per_cu_data *next_cu;
19383
19384       next_cu = per_cu->cu->read_in_chain;
19385
19386       if (!per_cu->cu->mark)
19387         {
19388           free_heap_comp_unit (per_cu->cu);
19389           *last_chain = next_cu;
19390         }
19391       else
19392         last_chain = &per_cu->cu->read_in_chain;
19393
19394       per_cu = next_cu;
19395     }
19396 }
19397
19398 /* Remove a single compilation unit from the cache.  */
19399
19400 static void
19401 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
19402 {
19403   struct dwarf2_per_cu_data *per_cu, **last_chain;
19404
19405   per_cu = dwarf2_per_objfile->read_in_chain;
19406   last_chain = &dwarf2_per_objfile->read_in_chain;
19407   while (per_cu != NULL)
19408     {
19409       struct dwarf2_per_cu_data *next_cu;
19410
19411       next_cu = per_cu->cu->read_in_chain;
19412
19413       if (per_cu == target_per_cu)
19414         {
19415           free_heap_comp_unit (per_cu->cu);
19416           per_cu->cu = NULL;
19417           *last_chain = next_cu;
19418           break;
19419         }
19420       else
19421         last_chain = &per_cu->cu->read_in_chain;
19422
19423       per_cu = next_cu;
19424     }
19425 }
19426
19427 /* Release all extra memory associated with OBJFILE.  */
19428
19429 void
19430 dwarf2_free_objfile (struct objfile *objfile)
19431 {
19432   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
19433
19434   if (dwarf2_per_objfile == NULL)
19435     return;
19436
19437   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
19438   free_cached_comp_units (NULL);
19439
19440   if (dwarf2_per_objfile->quick_file_names_table)
19441     htab_delete (dwarf2_per_objfile->quick_file_names_table);
19442
19443   /* Everything else should be on the objfile obstack.  */
19444 }
19445
19446 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
19447    We store these in a hash table separate from the DIEs, and preserve them
19448    when the DIEs are flushed out of cache.
19449
19450    The CU "per_cu" pointer is needed because offset alone is not enough to
19451    uniquely identify the type.  A file may have multiple .debug_types sections,
19452    or the type may come from a DWO file.  We have to use something in
19453    dwarf2_per_cu_data (or the pointer to it) because we can enter the lookup
19454    routine, get_die_type_at_offset, from outside this file, and thus won't
19455    necessarily have PER_CU->cu.  Fortunately, PER_CU is stable for the life
19456    of the objfile.  */
19457
19458 struct dwarf2_per_cu_offset_and_type
19459 {
19460   const struct dwarf2_per_cu_data *per_cu;
19461   sect_offset offset;
19462   struct type *type;
19463 };
19464
19465 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
19466
19467 static hashval_t
19468 per_cu_offset_and_type_hash (const void *item)
19469 {
19470   const struct dwarf2_per_cu_offset_and_type *ofs = item;
19471
19472   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
19473 }
19474
19475 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
19476
19477 static int
19478 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
19479 {
19480   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
19481   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
19482
19483   return (ofs_lhs->per_cu == ofs_rhs->per_cu
19484           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
19485 }
19486
19487 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
19488    table if necessary.  For convenience, return TYPE.
19489
19490    The DIEs reading must have careful ordering to:
19491     * Not cause infite loops trying to read in DIEs as a prerequisite for
19492       reading current DIE.
19493     * Not trying to dereference contents of still incompletely read in types
19494       while reading in other DIEs.
19495     * Enable referencing still incompletely read in types just by a pointer to
19496       the type without accessing its fields.
19497
19498    Therefore caller should follow these rules:
19499      * Try to fetch any prerequisite types we may need to build this DIE type
19500        before building the type and calling set_die_type.
19501      * After building type call set_die_type for current DIE as soon as
19502        possible before fetching more types to complete the current type.
19503      * Make the type as complete as possible before fetching more types.  */
19504
19505 static struct type *
19506 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19507 {
19508   struct dwarf2_per_cu_offset_and_type **slot, ofs;
19509   struct objfile *objfile = cu->objfile;
19510
19511   /* For Ada types, make sure that the gnat-specific data is always
19512      initialized (if not already set).  There are a few types where
19513      we should not be doing so, because the type-specific area is
19514      already used to hold some other piece of info (eg: TYPE_CODE_FLT
19515      where the type-specific area is used to store the floatformat).
19516      But this is not a problem, because the gnat-specific information
19517      is actually not needed for these types.  */
19518   if (need_gnat_info (cu)
19519       && TYPE_CODE (type) != TYPE_CODE_FUNC
19520       && TYPE_CODE (type) != TYPE_CODE_FLT
19521       && !HAVE_GNAT_AUX_INFO (type))
19522     INIT_GNAT_SPECIFIC (type);
19523
19524   if (dwarf2_per_objfile->die_type_hash == NULL)
19525     {
19526       dwarf2_per_objfile->die_type_hash =
19527         htab_create_alloc_ex (127,
19528                               per_cu_offset_and_type_hash,
19529                               per_cu_offset_and_type_eq,
19530                               NULL,
19531                               &objfile->objfile_obstack,
19532                               hashtab_obstack_allocate,
19533                               dummy_obstack_deallocate);
19534     }
19535
19536   ofs.per_cu = cu->per_cu;
19537   ofs.offset = die->offset;
19538   ofs.type = type;
19539   slot = (struct dwarf2_per_cu_offset_and_type **)
19540     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
19541   if (*slot)
19542     complaint (&symfile_complaints,
19543                _("A problem internal to GDB: DIE 0x%x has type already set"),
19544                die->offset.sect_off);
19545   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
19546   **slot = ofs;
19547   return type;
19548 }
19549
19550 /* Look up the type for the die at OFFSET in the appropriate type_hash
19551    table, or return NULL if the die does not have a saved type.  */
19552
19553 static struct type *
19554 get_die_type_at_offset (sect_offset offset,
19555                         struct dwarf2_per_cu_data *per_cu)
19556 {
19557   struct dwarf2_per_cu_offset_and_type *slot, ofs;
19558
19559   if (dwarf2_per_objfile->die_type_hash == NULL)
19560     return NULL;
19561
19562   ofs.per_cu = per_cu;
19563   ofs.offset = offset;
19564   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
19565   if (slot)
19566     return slot->type;
19567   else
19568     return NULL;
19569 }
19570
19571 /* Look up the type for DIE in the appropriate type_hash table,
19572    or return NULL if DIE does not have a saved type.  */
19573
19574 static struct type *
19575 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
19576 {
19577   return get_die_type_at_offset (die->offset, cu->per_cu);
19578 }
19579
19580 /* Add a dependence relationship from CU to REF_PER_CU.  */
19581
19582 static void
19583 dwarf2_add_dependence (struct dwarf2_cu *cu,
19584                        struct dwarf2_per_cu_data *ref_per_cu)
19585 {
19586   void **slot;
19587
19588   if (cu->dependencies == NULL)
19589     cu->dependencies
19590       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
19591                               NULL, &cu->comp_unit_obstack,
19592                               hashtab_obstack_allocate,
19593                               dummy_obstack_deallocate);
19594
19595   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
19596   if (*slot == NULL)
19597     *slot = ref_per_cu;
19598 }
19599
19600 /* Subroutine of dwarf2_mark to pass to htab_traverse.
19601    Set the mark field in every compilation unit in the
19602    cache that we must keep because we are keeping CU.  */
19603
19604 static int
19605 dwarf2_mark_helper (void **slot, void *data)
19606 {
19607   struct dwarf2_per_cu_data *per_cu;
19608
19609   per_cu = (struct dwarf2_per_cu_data *) *slot;
19610
19611   /* cu->dependencies references may not yet have been ever read if QUIT aborts
19612      reading of the chain.  As such dependencies remain valid it is not much
19613      useful to track and undo them during QUIT cleanups.  */
19614   if (per_cu->cu == NULL)
19615     return 1;
19616
19617   if (per_cu->cu->mark)
19618     return 1;
19619   per_cu->cu->mark = 1;
19620
19621   if (per_cu->cu->dependencies != NULL)
19622     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
19623
19624   return 1;
19625 }
19626
19627 /* Set the mark field in CU and in every other compilation unit in the
19628    cache that we must keep because we are keeping CU.  */
19629
19630 static void
19631 dwarf2_mark (struct dwarf2_cu *cu)
19632 {
19633   if (cu->mark)
19634     return;
19635   cu->mark = 1;
19636   if (cu->dependencies != NULL)
19637     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
19638 }
19639
19640 static void
19641 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
19642 {
19643   while (per_cu)
19644     {
19645       per_cu->cu->mark = 0;
19646       per_cu = per_cu->cu->read_in_chain;
19647     }
19648 }
19649
19650 /* Trivial hash function for partial_die_info: the hash value of a DIE
19651    is its offset in .debug_info for this objfile.  */
19652
19653 static hashval_t
19654 partial_die_hash (const void *item)
19655 {
19656   const struct partial_die_info *part_die = item;
19657
19658   return part_die->offset.sect_off;
19659 }
19660
19661 /* Trivial comparison function for partial_die_info structures: two DIEs
19662    are equal if they have the same offset.  */
19663
19664 static int
19665 partial_die_eq (const void *item_lhs, const void *item_rhs)
19666 {
19667   const struct partial_die_info *part_die_lhs = item_lhs;
19668   const struct partial_die_info *part_die_rhs = item_rhs;
19669
19670   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
19671 }
19672
19673 static struct cmd_list_element *set_dwarf2_cmdlist;
19674 static struct cmd_list_element *show_dwarf2_cmdlist;
19675
19676 static void
19677 set_dwarf2_cmd (char *args, int from_tty)
19678 {
19679   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
19680 }
19681
19682 static void
19683 show_dwarf2_cmd (char *args, int from_tty)
19684 {
19685   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
19686 }
19687
19688 /* Free data associated with OBJFILE, if necessary.  */
19689
19690 static void
19691 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
19692 {
19693   struct dwarf2_per_objfile *data = d;
19694   int ix;
19695
19696   for (ix = 0; ix < dwarf2_per_objfile->n_comp_units; ++ix)
19697     VEC_free (dwarf2_per_cu_ptr,
19698               dwarf2_per_objfile->all_comp_units[ix]->imported_symtabs);
19699
19700   for (ix = 0; ix < dwarf2_per_objfile->n_type_units; ++ix)
19701     VEC_free (dwarf2_per_cu_ptr,
19702               dwarf2_per_objfile->all_type_units[ix]->per_cu.imported_symtabs);
19703
19704   VEC_free (dwarf2_section_info_def, data->types);
19705
19706   if (data->dwo_files)
19707     free_dwo_files (data->dwo_files, objfile);
19708
19709   if (data->dwz_file && data->dwz_file->dwz_bfd)
19710     gdb_bfd_unref (data->dwz_file->dwz_bfd);
19711 }
19712
19713 \f
19714 /* The "save gdb-index" command.  */
19715
19716 /* The contents of the hash table we create when building the string
19717    table.  */
19718 struct strtab_entry
19719 {
19720   offset_type offset;
19721   const char *str;
19722 };
19723
19724 /* Hash function for a strtab_entry.
19725
19726    Function is used only during write_hash_table so no index format backward
19727    compatibility is needed.  */
19728
19729 static hashval_t
19730 hash_strtab_entry (const void *e)
19731 {
19732   const struct strtab_entry *entry = e;
19733   return mapped_index_string_hash (INT_MAX, entry->str);
19734 }
19735
19736 /* Equality function for a strtab_entry.  */
19737
19738 static int
19739 eq_strtab_entry (const void *a, const void *b)
19740 {
19741   const struct strtab_entry *ea = a;
19742   const struct strtab_entry *eb = b;
19743   return !strcmp (ea->str, eb->str);
19744 }
19745
19746 /* Create a strtab_entry hash table.  */
19747
19748 static htab_t
19749 create_strtab (void)
19750 {
19751   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
19752                             xfree, xcalloc, xfree);
19753 }
19754
19755 /* Add a string to the constant pool.  Return the string's offset in
19756    host order.  */
19757
19758 static offset_type
19759 add_string (htab_t table, struct obstack *cpool, const char *str)
19760 {
19761   void **slot;
19762   struct strtab_entry entry;
19763   struct strtab_entry *result;
19764
19765   entry.str = str;
19766   slot = htab_find_slot (table, &entry, INSERT);
19767   if (*slot)
19768     result = *slot;
19769   else
19770     {
19771       result = XNEW (struct strtab_entry);
19772       result->offset = obstack_object_size (cpool);
19773       result->str = str;
19774       obstack_grow_str0 (cpool, str);
19775       *slot = result;
19776     }
19777   return result->offset;
19778 }
19779
19780 /* An entry in the symbol table.  */
19781 struct symtab_index_entry
19782 {
19783   /* The name of the symbol.  */
19784   const char *name;
19785   /* The offset of the name in the constant pool.  */
19786   offset_type index_offset;
19787   /* A sorted vector of the indices of all the CUs that hold an object
19788      of this name.  */
19789   VEC (offset_type) *cu_indices;
19790 };
19791
19792 /* The symbol table.  This is a power-of-2-sized hash table.  */
19793 struct mapped_symtab
19794 {
19795   offset_type n_elements;
19796   offset_type size;
19797   struct symtab_index_entry **data;
19798 };
19799
19800 /* Hash function for a symtab_index_entry.  */
19801
19802 static hashval_t
19803 hash_symtab_entry (const void *e)
19804 {
19805   const struct symtab_index_entry *entry = e;
19806   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
19807                          sizeof (offset_type) * VEC_length (offset_type,
19808                                                             entry->cu_indices),
19809                          0);
19810 }
19811
19812 /* Equality function for a symtab_index_entry.  */
19813
19814 static int
19815 eq_symtab_entry (const void *a, const void *b)
19816 {
19817   const struct symtab_index_entry *ea = a;
19818   const struct symtab_index_entry *eb = b;
19819   int len = VEC_length (offset_type, ea->cu_indices);
19820   if (len != VEC_length (offset_type, eb->cu_indices))
19821     return 0;
19822   return !memcmp (VEC_address (offset_type, ea->cu_indices),
19823                   VEC_address (offset_type, eb->cu_indices),
19824                   sizeof (offset_type) * len);
19825 }
19826
19827 /* Destroy a symtab_index_entry.  */
19828
19829 static void
19830 delete_symtab_entry (void *p)
19831 {
19832   struct symtab_index_entry *entry = p;
19833   VEC_free (offset_type, entry->cu_indices);
19834   xfree (entry);
19835 }
19836
19837 /* Create a hash table holding symtab_index_entry objects.  */
19838
19839 static htab_t
19840 create_symbol_hash_table (void)
19841 {
19842   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
19843                             delete_symtab_entry, xcalloc, xfree);
19844 }
19845
19846 /* Create a new mapped symtab object.  */
19847
19848 static struct mapped_symtab *
19849 create_mapped_symtab (void)
19850 {
19851   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
19852   symtab->n_elements = 0;
19853   symtab->size = 1024;
19854   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19855   return symtab;
19856 }
19857
19858 /* Destroy a mapped_symtab.  */
19859
19860 static void
19861 cleanup_mapped_symtab (void *p)
19862 {
19863   struct mapped_symtab *symtab = p;
19864   /* The contents of the array are freed when the other hash table is
19865      destroyed.  */
19866   xfree (symtab->data);
19867   xfree (symtab);
19868 }
19869
19870 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
19871    the slot.
19872    
19873    Function is used only during write_hash_table so no index format backward
19874    compatibility is needed.  */
19875
19876 static struct symtab_index_entry **
19877 find_slot (struct mapped_symtab *symtab, const char *name)
19878 {
19879   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
19880
19881   index = hash & (symtab->size - 1);
19882   step = ((hash * 17) & (symtab->size - 1)) | 1;
19883
19884   for (;;)
19885     {
19886       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
19887         return &symtab->data[index];
19888       index = (index + step) & (symtab->size - 1);
19889     }
19890 }
19891
19892 /* Expand SYMTAB's hash table.  */
19893
19894 static void
19895 hash_expand (struct mapped_symtab *symtab)
19896 {
19897   offset_type old_size = symtab->size;
19898   offset_type i;
19899   struct symtab_index_entry **old_entries = symtab->data;
19900
19901   symtab->size *= 2;
19902   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
19903
19904   for (i = 0; i < old_size; ++i)
19905     {
19906       if (old_entries[i])
19907         {
19908           struct symtab_index_entry **slot = find_slot (symtab,
19909                                                         old_entries[i]->name);
19910           *slot = old_entries[i];
19911         }
19912     }
19913
19914   xfree (old_entries);
19915 }
19916
19917 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
19918    CU_INDEX is the index of the CU in which the symbol appears.
19919    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
19920
19921 static void
19922 add_index_entry (struct mapped_symtab *symtab, const char *name,
19923                  int is_static, gdb_index_symbol_kind kind,
19924                  offset_type cu_index)
19925 {
19926   struct symtab_index_entry **slot;
19927   offset_type cu_index_and_attrs;
19928
19929   ++symtab->n_elements;
19930   if (4 * symtab->n_elements / 3 >= symtab->size)
19931     hash_expand (symtab);
19932
19933   slot = find_slot (symtab, name);
19934   if (!*slot)
19935     {
19936       *slot = XNEW (struct symtab_index_entry);
19937       (*slot)->name = name;
19938       /* index_offset is set later.  */
19939       (*slot)->cu_indices = NULL;
19940     }
19941
19942   cu_index_and_attrs = 0;
19943   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
19944   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
19945   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
19946
19947   /* We don't want to record an index value twice as we want to avoid the
19948      duplication.
19949      We process all global symbols and then all static symbols
19950      (which would allow us to avoid the duplication by only having to check
19951      the last entry pushed), but a symbol could have multiple kinds in one CU.
19952      To keep things simple we don't worry about the duplication here and
19953      sort and uniqufy the list after we've processed all symbols.  */
19954   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
19955 }
19956
19957 /* qsort helper routine for uniquify_cu_indices.  */
19958
19959 static int
19960 offset_type_compare (const void *ap, const void *bp)
19961 {
19962   offset_type a = *(offset_type *) ap;
19963   offset_type b = *(offset_type *) bp;
19964
19965   return (a > b) - (b > a);
19966 }
19967
19968 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
19969
19970 static void
19971 uniquify_cu_indices (struct mapped_symtab *symtab)
19972 {
19973   int i;
19974
19975   for (i = 0; i < symtab->size; ++i)
19976     {
19977       struct symtab_index_entry *entry = symtab->data[i];
19978
19979       if (entry
19980           && entry->cu_indices != NULL)
19981         {
19982           unsigned int next_to_insert, next_to_check;
19983           offset_type last_value;
19984
19985           qsort (VEC_address (offset_type, entry->cu_indices),
19986                  VEC_length (offset_type, entry->cu_indices),
19987                  sizeof (offset_type), offset_type_compare);
19988
19989           last_value = VEC_index (offset_type, entry->cu_indices, 0);
19990           next_to_insert = 1;
19991           for (next_to_check = 1;
19992                next_to_check < VEC_length (offset_type, entry->cu_indices);
19993                ++next_to_check)
19994             {
19995               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
19996                   != last_value)
19997                 {
19998                   last_value = VEC_index (offset_type, entry->cu_indices,
19999                                           next_to_check);
20000                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
20001                                last_value);
20002                   ++next_to_insert;
20003                 }
20004             }
20005           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
20006         }
20007     }
20008 }
20009
20010 /* Add a vector of indices to the constant pool.  */
20011
20012 static offset_type
20013 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
20014                       struct symtab_index_entry *entry)
20015 {
20016   void **slot;
20017
20018   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
20019   if (!*slot)
20020     {
20021       offset_type len = VEC_length (offset_type, entry->cu_indices);
20022       offset_type val = MAYBE_SWAP (len);
20023       offset_type iter;
20024       int i;
20025
20026       *slot = entry;
20027       entry->index_offset = obstack_object_size (cpool);
20028
20029       obstack_grow (cpool, &val, sizeof (val));
20030       for (i = 0;
20031            VEC_iterate (offset_type, entry->cu_indices, i, iter);
20032            ++i)
20033         {
20034           val = MAYBE_SWAP (iter);
20035           obstack_grow (cpool, &val, sizeof (val));
20036         }
20037     }
20038   else
20039     {
20040       struct symtab_index_entry *old_entry = *slot;
20041       entry->index_offset = old_entry->index_offset;
20042       entry = old_entry;
20043     }
20044   return entry->index_offset;
20045 }
20046
20047 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
20048    constant pool entries going into the obstack CPOOL.  */
20049
20050 static void
20051 write_hash_table (struct mapped_symtab *symtab,
20052                   struct obstack *output, struct obstack *cpool)
20053 {
20054   offset_type i;
20055   htab_t symbol_hash_table;
20056   htab_t str_table;
20057
20058   symbol_hash_table = create_symbol_hash_table ();
20059   str_table = create_strtab ();
20060
20061   /* We add all the index vectors to the constant pool first, to
20062      ensure alignment is ok.  */
20063   for (i = 0; i < symtab->size; ++i)
20064     {
20065       if (symtab->data[i])
20066         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
20067     }
20068
20069   /* Now write out the hash table.  */
20070   for (i = 0; i < symtab->size; ++i)
20071     {
20072       offset_type str_off, vec_off;
20073
20074       if (symtab->data[i])
20075         {
20076           str_off = add_string (str_table, cpool, symtab->data[i]->name);
20077           vec_off = symtab->data[i]->index_offset;
20078         }
20079       else
20080         {
20081           /* While 0 is a valid constant pool index, it is not valid
20082              to have 0 for both offsets.  */
20083           str_off = 0;
20084           vec_off = 0;
20085         }
20086
20087       str_off = MAYBE_SWAP (str_off);
20088       vec_off = MAYBE_SWAP (vec_off);
20089
20090       obstack_grow (output, &str_off, sizeof (str_off));
20091       obstack_grow (output, &vec_off, sizeof (vec_off));
20092     }
20093
20094   htab_delete (str_table);
20095   htab_delete (symbol_hash_table);
20096 }
20097
20098 /* Struct to map psymtab to CU index in the index file.  */
20099 struct psymtab_cu_index_map
20100 {
20101   struct partial_symtab *psymtab;
20102   unsigned int cu_index;
20103 };
20104
20105 static hashval_t
20106 hash_psymtab_cu_index (const void *item)
20107 {
20108   const struct psymtab_cu_index_map *map = item;
20109
20110   return htab_hash_pointer (map->psymtab);
20111 }
20112
20113 static int
20114 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
20115 {
20116   const struct psymtab_cu_index_map *lhs = item_lhs;
20117   const struct psymtab_cu_index_map *rhs = item_rhs;
20118
20119   return lhs->psymtab == rhs->psymtab;
20120 }
20121
20122 /* Helper struct for building the address table.  */
20123 struct addrmap_index_data
20124 {
20125   struct objfile *objfile;
20126   struct obstack *addr_obstack;
20127   htab_t cu_index_htab;
20128
20129   /* Non-zero if the previous_* fields are valid.
20130      We can't write an entry until we see the next entry (since it is only then
20131      that we know the end of the entry).  */
20132   int previous_valid;
20133   /* Index of the CU in the table of all CUs in the index file.  */
20134   unsigned int previous_cu_index;
20135   /* Start address of the CU.  */
20136   CORE_ADDR previous_cu_start;
20137 };
20138
20139 /* Write an address entry to OBSTACK.  */
20140
20141 static void
20142 add_address_entry (struct objfile *objfile, struct obstack *obstack,
20143                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
20144 {
20145   offset_type cu_index_to_write;
20146   char addr[8];
20147   CORE_ADDR baseaddr;
20148
20149   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20150
20151   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
20152   obstack_grow (obstack, addr, 8);
20153   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
20154   obstack_grow (obstack, addr, 8);
20155   cu_index_to_write = MAYBE_SWAP (cu_index);
20156   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
20157 }
20158
20159 /* Worker function for traversing an addrmap to build the address table.  */
20160
20161 static int
20162 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
20163 {
20164   struct addrmap_index_data *data = datap;
20165   struct partial_symtab *pst = obj;
20166
20167   if (data->previous_valid)
20168     add_address_entry (data->objfile, data->addr_obstack,
20169                        data->previous_cu_start, start_addr,
20170                        data->previous_cu_index);
20171
20172   data->previous_cu_start = start_addr;
20173   if (pst != NULL)
20174     {
20175       struct psymtab_cu_index_map find_map, *map;
20176       find_map.psymtab = pst;
20177       map = htab_find (data->cu_index_htab, &find_map);
20178       gdb_assert (map != NULL);
20179       data->previous_cu_index = map->cu_index;
20180       data->previous_valid = 1;
20181     }
20182   else
20183       data->previous_valid = 0;
20184
20185   return 0;
20186 }
20187
20188 /* Write OBJFILE's address map to OBSTACK.
20189    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
20190    in the index file.  */
20191
20192 static void
20193 write_address_map (struct objfile *objfile, struct obstack *obstack,
20194                    htab_t cu_index_htab)
20195 {
20196   struct addrmap_index_data addrmap_index_data;
20197
20198   /* When writing the address table, we have to cope with the fact that
20199      the addrmap iterator only provides the start of a region; we have to
20200      wait until the next invocation to get the start of the next region.  */
20201
20202   addrmap_index_data.objfile = objfile;
20203   addrmap_index_data.addr_obstack = obstack;
20204   addrmap_index_data.cu_index_htab = cu_index_htab;
20205   addrmap_index_data.previous_valid = 0;
20206
20207   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
20208                    &addrmap_index_data);
20209
20210   /* It's highly unlikely the last entry (end address = 0xff...ff)
20211      is valid, but we should still handle it.
20212      The end address is recorded as the start of the next region, but that
20213      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
20214      anyway.  */
20215   if (addrmap_index_data.previous_valid)
20216     add_address_entry (objfile, obstack,
20217                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
20218                        addrmap_index_data.previous_cu_index);
20219 }
20220
20221 /* Return the symbol kind of PSYM.  */
20222
20223 static gdb_index_symbol_kind
20224 symbol_kind (struct partial_symbol *psym)
20225 {
20226   domain_enum domain = PSYMBOL_DOMAIN (psym);
20227   enum address_class aclass = PSYMBOL_CLASS (psym);
20228
20229   switch (domain)
20230     {
20231     case VAR_DOMAIN:
20232       switch (aclass)
20233         {
20234         case LOC_BLOCK:
20235           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
20236         case LOC_TYPEDEF:
20237           return GDB_INDEX_SYMBOL_KIND_TYPE;
20238         case LOC_COMPUTED:
20239         case LOC_CONST_BYTES:
20240         case LOC_OPTIMIZED_OUT:
20241         case LOC_STATIC:
20242           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20243         case LOC_CONST:
20244           /* Note: It's currently impossible to recognize psyms as enum values
20245              short of reading the type info.  For now punt.  */
20246           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
20247         default:
20248           /* There are other LOC_FOO values that one might want to classify
20249              as variables, but dwarf2read.c doesn't currently use them.  */
20250           return GDB_INDEX_SYMBOL_KIND_OTHER;
20251         }
20252     case STRUCT_DOMAIN:
20253       return GDB_INDEX_SYMBOL_KIND_TYPE;
20254     default:
20255       return GDB_INDEX_SYMBOL_KIND_OTHER;
20256     }
20257 }
20258
20259 /* Add a list of partial symbols to SYMTAB.  */
20260
20261 static void
20262 write_psymbols (struct mapped_symtab *symtab,
20263                 htab_t psyms_seen,
20264                 struct partial_symbol **psymp,
20265                 int count,
20266                 offset_type cu_index,
20267                 int is_static)
20268 {
20269   for (; count-- > 0; ++psymp)
20270     {
20271       struct partial_symbol *psym = *psymp;
20272       void **slot;
20273
20274       if (SYMBOL_LANGUAGE (psym) == language_ada)
20275         error (_("Ada is not currently supported by the index"));
20276
20277       /* Only add a given psymbol once.  */
20278       slot = htab_find_slot (psyms_seen, psym, INSERT);
20279       if (!*slot)
20280         {
20281           gdb_index_symbol_kind kind = symbol_kind (psym);
20282
20283           *slot = psym;
20284           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
20285                            is_static, kind, cu_index);
20286         }
20287     }
20288 }
20289
20290 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
20291    exception if there is an error.  */
20292
20293 static void
20294 write_obstack (FILE *file, struct obstack *obstack)
20295 {
20296   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
20297               file)
20298       != obstack_object_size (obstack))
20299     error (_("couldn't data write to file"));
20300 }
20301
20302 /* Unlink a file if the argument is not NULL.  */
20303
20304 static void
20305 unlink_if_set (void *p)
20306 {
20307   char **filename = p;
20308   if (*filename)
20309     unlink (*filename);
20310 }
20311
20312 /* A helper struct used when iterating over debug_types.  */
20313 struct signatured_type_index_data
20314 {
20315   struct objfile *objfile;
20316   struct mapped_symtab *symtab;
20317   struct obstack *types_list;
20318   htab_t psyms_seen;
20319   int cu_index;
20320 };
20321
20322 /* A helper function that writes a single signatured_type to an
20323    obstack.  */
20324
20325 static int
20326 write_one_signatured_type (void **slot, void *d)
20327 {
20328   struct signatured_type_index_data *info = d;
20329   struct signatured_type *entry = (struct signatured_type *) *slot;
20330   struct dwarf2_per_cu_data *per_cu = &entry->per_cu;
20331   struct partial_symtab *psymtab = per_cu->v.psymtab;
20332   gdb_byte val[8];
20333
20334   write_psymbols (info->symtab,
20335                   info->psyms_seen,
20336                   info->objfile->global_psymbols.list
20337                   + psymtab->globals_offset,
20338                   psymtab->n_global_syms, info->cu_index,
20339                   0);
20340   write_psymbols (info->symtab,
20341                   info->psyms_seen,
20342                   info->objfile->static_psymbols.list
20343                   + psymtab->statics_offset,
20344                   psymtab->n_static_syms, info->cu_index,
20345                   1);
20346
20347   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20348                           entry->per_cu.offset.sect_off);
20349   obstack_grow (info->types_list, val, 8);
20350   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20351                           entry->type_offset_in_tu.cu_off);
20352   obstack_grow (info->types_list, val, 8);
20353   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
20354   obstack_grow (info->types_list, val, 8);
20355
20356   ++info->cu_index;
20357
20358   return 1;
20359 }
20360
20361 /* Recurse into all "included" dependencies and write their symbols as
20362    if they appeared in this psymtab.  */
20363
20364 static void
20365 recursively_write_psymbols (struct objfile *objfile,
20366                             struct partial_symtab *psymtab,
20367                             struct mapped_symtab *symtab,
20368                             htab_t psyms_seen,
20369                             offset_type cu_index)
20370 {
20371   int i;
20372
20373   for (i = 0; i < psymtab->number_of_dependencies; ++i)
20374     if (psymtab->dependencies[i]->user != NULL)
20375       recursively_write_psymbols (objfile, psymtab->dependencies[i],
20376                                   symtab, psyms_seen, cu_index);
20377
20378   write_psymbols (symtab,
20379                   psyms_seen,
20380                   objfile->global_psymbols.list + psymtab->globals_offset,
20381                   psymtab->n_global_syms, cu_index,
20382                   0);
20383   write_psymbols (symtab,
20384                   psyms_seen,
20385                   objfile->static_psymbols.list + psymtab->statics_offset,
20386                   psymtab->n_static_syms, cu_index,
20387                   1);
20388 }
20389
20390 /* Create an index file for OBJFILE in the directory DIR.  */
20391
20392 static void
20393 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
20394 {
20395   struct cleanup *cleanup;
20396   char *filename, *cleanup_filename;
20397   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
20398   struct obstack cu_list, types_cu_list;
20399   int i;
20400   FILE *out_file;
20401   struct mapped_symtab *symtab;
20402   offset_type val, size_of_contents, total_len;
20403   struct stat st;
20404   htab_t psyms_seen;
20405   htab_t cu_index_htab;
20406   struct psymtab_cu_index_map *psymtab_cu_index_map;
20407
20408   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
20409     return;
20410
20411   if (dwarf2_per_objfile->using_index)
20412     error (_("Cannot use an index to create the index"));
20413
20414   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
20415     error (_("Cannot make an index when the file has multiple .debug_types sections"));
20416
20417   if (stat (objfile->name, &st) < 0)
20418     perror_with_name (objfile->name);
20419
20420   filename = concat (dir, SLASH_STRING, lbasename (objfile->name),
20421                      INDEX_SUFFIX, (char *) NULL);
20422   cleanup = make_cleanup (xfree, filename);
20423
20424   out_file = fopen (filename, "wb");
20425   if (!out_file)
20426     error (_("Can't open `%s' for writing"), filename);
20427
20428   cleanup_filename = filename;
20429   make_cleanup (unlink_if_set, &cleanup_filename);
20430
20431   symtab = create_mapped_symtab ();
20432   make_cleanup (cleanup_mapped_symtab, symtab);
20433
20434   obstack_init (&addr_obstack);
20435   make_cleanup_obstack_free (&addr_obstack);
20436
20437   obstack_init (&cu_list);
20438   make_cleanup_obstack_free (&cu_list);
20439
20440   obstack_init (&types_cu_list);
20441   make_cleanup_obstack_free (&types_cu_list);
20442
20443   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
20444                                   NULL, xcalloc, xfree);
20445   make_cleanup_htab_delete (psyms_seen);
20446
20447   /* While we're scanning CU's create a table that maps a psymtab pointer
20448      (which is what addrmap records) to its index (which is what is recorded
20449      in the index file).  This will later be needed to write the address
20450      table.  */
20451   cu_index_htab = htab_create_alloc (100,
20452                                      hash_psymtab_cu_index,
20453                                      eq_psymtab_cu_index,
20454                                      NULL, xcalloc, xfree);
20455   make_cleanup_htab_delete (cu_index_htab);
20456   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
20457     xmalloc (sizeof (struct psymtab_cu_index_map)
20458              * dwarf2_per_objfile->n_comp_units);
20459   make_cleanup (xfree, psymtab_cu_index_map);
20460
20461   /* The CU list is already sorted, so we don't need to do additional
20462      work here.  Also, the debug_types entries do not appear in
20463      all_comp_units, but only in their own hash table.  */
20464   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
20465     {
20466       struct dwarf2_per_cu_data *per_cu
20467         = dwarf2_per_objfile->all_comp_units[i];
20468       struct partial_symtab *psymtab = per_cu->v.psymtab;
20469       gdb_byte val[8];
20470       struct psymtab_cu_index_map *map;
20471       void **slot;
20472
20473       if (psymtab->user == NULL)
20474         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
20475
20476       map = &psymtab_cu_index_map[i];
20477       map->psymtab = psymtab;
20478       map->cu_index = i;
20479       slot = htab_find_slot (cu_index_htab, map, INSERT);
20480       gdb_assert (slot != NULL);
20481       gdb_assert (*slot == NULL);
20482       *slot = map;
20483
20484       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
20485                               per_cu->offset.sect_off);
20486       obstack_grow (&cu_list, val, 8);
20487       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
20488       obstack_grow (&cu_list, val, 8);
20489     }
20490
20491   /* Dump the address map.  */
20492   write_address_map (objfile, &addr_obstack, cu_index_htab);
20493
20494   /* Write out the .debug_type entries, if any.  */
20495   if (dwarf2_per_objfile->signatured_types)
20496     {
20497       struct signatured_type_index_data sig_data;
20498
20499       sig_data.objfile = objfile;
20500       sig_data.symtab = symtab;
20501       sig_data.types_list = &types_cu_list;
20502       sig_data.psyms_seen = psyms_seen;
20503       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
20504       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
20505                               write_one_signatured_type, &sig_data);
20506     }
20507
20508   /* Now that we've processed all symbols we can shrink their cu_indices
20509      lists.  */
20510   uniquify_cu_indices (symtab);
20511
20512   obstack_init (&constant_pool);
20513   make_cleanup_obstack_free (&constant_pool);
20514   obstack_init (&symtab_obstack);
20515   make_cleanup_obstack_free (&symtab_obstack);
20516   write_hash_table (symtab, &symtab_obstack, &constant_pool);
20517
20518   obstack_init (&contents);
20519   make_cleanup_obstack_free (&contents);
20520   size_of_contents = 6 * sizeof (offset_type);
20521   total_len = size_of_contents;
20522
20523   /* The version number.  */
20524   val = MAYBE_SWAP (8);
20525   obstack_grow (&contents, &val, sizeof (val));
20526
20527   /* The offset of the CU list from the start of the file.  */
20528   val = MAYBE_SWAP (total_len);
20529   obstack_grow (&contents, &val, sizeof (val));
20530   total_len += obstack_object_size (&cu_list);
20531
20532   /* The offset of the types CU list from the start of the file.  */
20533   val = MAYBE_SWAP (total_len);
20534   obstack_grow (&contents, &val, sizeof (val));
20535   total_len += obstack_object_size (&types_cu_list);
20536
20537   /* The offset of the address table from the start of the file.  */
20538   val = MAYBE_SWAP (total_len);
20539   obstack_grow (&contents, &val, sizeof (val));
20540   total_len += obstack_object_size (&addr_obstack);
20541
20542   /* The offset of the symbol table from the start of the file.  */
20543   val = MAYBE_SWAP (total_len);
20544   obstack_grow (&contents, &val, sizeof (val));
20545   total_len += obstack_object_size (&symtab_obstack);
20546
20547   /* The offset of the constant pool from the start of the file.  */
20548   val = MAYBE_SWAP (total_len);
20549   obstack_grow (&contents, &val, sizeof (val));
20550   total_len += obstack_object_size (&constant_pool);
20551
20552   gdb_assert (obstack_object_size (&contents) == size_of_contents);
20553
20554   write_obstack (out_file, &contents);
20555   write_obstack (out_file, &cu_list);
20556   write_obstack (out_file, &types_cu_list);
20557   write_obstack (out_file, &addr_obstack);
20558   write_obstack (out_file, &symtab_obstack);
20559   write_obstack (out_file, &constant_pool);
20560
20561   fclose (out_file);
20562
20563   /* We want to keep the file, so we set cleanup_filename to NULL
20564      here.  See unlink_if_set.  */
20565   cleanup_filename = NULL;
20566
20567   do_cleanups (cleanup);
20568 }
20569
20570 /* Implementation of the `save gdb-index' command.
20571    
20572    Note that the file format used by this command is documented in the
20573    GDB manual.  Any changes here must be documented there.  */
20574
20575 static void
20576 save_gdb_index_command (char *arg, int from_tty)
20577 {
20578   struct objfile *objfile;
20579
20580   if (!arg || !*arg)
20581     error (_("usage: save gdb-index DIRECTORY"));
20582
20583   ALL_OBJFILES (objfile)
20584   {
20585     struct stat st;
20586
20587     /* If the objfile does not correspond to an actual file, skip it.  */
20588     if (stat (objfile->name, &st) < 0)
20589       continue;
20590
20591     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
20592     if (dwarf2_per_objfile)
20593       {
20594         volatile struct gdb_exception except;
20595
20596         TRY_CATCH (except, RETURN_MASK_ERROR)
20597           {
20598             write_psymtabs_to_index (objfile, arg);
20599           }
20600         if (except.reason < 0)
20601           exception_fprintf (gdb_stderr, except,
20602                              _("Error while writing index for `%s': "),
20603                              objfile->name);
20604       }
20605   }
20606 }
20607
20608 \f
20609
20610 int dwarf2_always_disassemble;
20611
20612 static void
20613 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
20614                                 struct cmd_list_element *c, const char *value)
20615 {
20616   fprintf_filtered (file,
20617                     _("Whether to always disassemble "
20618                       "DWARF expressions is %s.\n"),
20619                     value);
20620 }
20621
20622 static void
20623 show_check_physname (struct ui_file *file, int from_tty,
20624                      struct cmd_list_element *c, const char *value)
20625 {
20626   fprintf_filtered (file,
20627                     _("Whether to check \"physname\" is %s.\n"),
20628                     value);
20629 }
20630
20631 void _initialize_dwarf2_read (void);
20632
20633 void
20634 _initialize_dwarf2_read (void)
20635 {
20636   struct cmd_list_element *c;
20637
20638   dwarf2_objfile_data_key
20639     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
20640
20641   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
20642 Set DWARF 2 specific variables.\n\
20643 Configure DWARF 2 variables such as the cache size"),
20644                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
20645                   0/*allow-unknown*/, &maintenance_set_cmdlist);
20646
20647   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
20648 Show DWARF 2 specific variables\n\
20649 Show DWARF 2 variables such as the cache size"),
20650                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
20651                   0/*allow-unknown*/, &maintenance_show_cmdlist);
20652
20653   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
20654                             &dwarf2_max_cache_age, _("\
20655 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
20656 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
20657 A higher limit means that cached compilation units will be stored\n\
20658 in memory longer, and more total memory will be used.  Zero disables\n\
20659 caching, which can slow down startup."),
20660                             NULL,
20661                             show_dwarf2_max_cache_age,
20662                             &set_dwarf2_cmdlist,
20663                             &show_dwarf2_cmdlist);
20664
20665   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
20666                            &dwarf2_always_disassemble, _("\
20667 Set whether `info address' always disassembles DWARF expressions."), _("\
20668 Show whether `info address' always disassembles DWARF expressions."), _("\
20669 When enabled, DWARF expressions are always printed in an assembly-like\n\
20670 syntax.  When disabled, expressions will be printed in a more\n\
20671 conversational style, when possible."),
20672                            NULL,
20673                            show_dwarf2_always_disassemble,
20674                            &set_dwarf2_cmdlist,
20675                            &show_dwarf2_cmdlist);
20676
20677   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
20678 Set debugging of the dwarf2 reader."), _("\
20679 Show debugging of the dwarf2 reader."), _("\
20680 When enabled, debugging messages are printed during dwarf2 reading\n\
20681 and symtab expansion."),
20682                             NULL,
20683                             NULL,
20684                             &setdebuglist, &showdebuglist);
20685
20686   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
20687 Set debugging of the dwarf2 DIE reader."), _("\
20688 Show debugging of the dwarf2 DIE reader."), _("\
20689 When enabled (non-zero), DIEs are dumped after they are read in.\n\
20690 The value is the maximum depth to print."),
20691                              NULL,
20692                              NULL,
20693                              &setdebuglist, &showdebuglist);
20694
20695   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
20696 Set cross-checking of \"physname\" code against demangler."), _("\
20697 Show cross-checking of \"physname\" code against demangler."), _("\
20698 When enabled, GDB's internal \"physname\" code is checked against\n\
20699 the demangler."),
20700                            NULL, show_check_physname,
20701                            &setdebuglist, &showdebuglist);
20702
20703   add_setshow_boolean_cmd ("use-deprecated-index-sections",
20704                            no_class, &use_deprecated_index_sections, _("\
20705 Set whether to use deprecated gdb_index sections."), _("\
20706 Show whether to use deprecated gdb_index sections."), _("\
20707 When enabled, deprecated .gdb_index sections are used anyway.\n\
20708 Normally they are ignored either because of a missing feature or\n\
20709 performance issue.\n\
20710 Warning: This option must be enabled before gdb reads the file."),
20711                            NULL,
20712                            NULL,
20713                            &setlist, &showlist);
20714
20715   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
20716                _("\
20717 Save a gdb-index file.\n\
20718 Usage: save gdb-index DIRECTORY"),
20719                &save_cmdlist);
20720   set_cmd_completer (c, filename_completer);
20721
20722   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
20723                                                         &dwarf2_locexpr_funcs);
20724   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
20725                                                         &dwarf2_loclist_funcs);
20726
20727   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
20728                                         &dwarf2_block_frame_base_locexpr_funcs);
20729   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
20730                                         &dwarf2_block_frame_base_loclist_funcs);
20731 }