bfd
[platform/upstream/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2013 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "jv-lang.h"
57 #include "psympriv.h"
58 #include "exceptions.h"
59 #include "gdb_stat.h"
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72 #include "build-id.h"
73
74 #include <fcntl.h>
75 #include "gdb_string.h"
76 #include "gdb_assert.h"
77 #include <sys/types.h>
78
79 typedef struct symbol *symbolp;
80 DEF_VEC_P (symbolp);
81
82 /* When non-zero, print basic high level tracing messages.
83    This is in contrast to the low level DIE reading of dwarf2_die_debug.  */
84 static int dwarf2_read_debug = 0;
85
86 /* When non-zero, dump DIEs after they are read in.  */
87 static unsigned int dwarf2_die_debug = 0;
88
89 /* When non-zero, cross-check physname against demangler.  */
90 static int check_physname = 0;
91
92 /* When non-zero, do not reject deprecated .gdb_index sections.  */
93 static int use_deprecated_index_sections = 0;
94
95 static const struct objfile_data *dwarf2_objfile_data_key;
96
97 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
98
99 static int dwarf2_locexpr_index;
100 static int dwarf2_loclist_index;
101 static int dwarf2_locexpr_block_index;
102 static int dwarf2_loclist_block_index;
103
104 /* A descriptor for dwarf sections.
105
106    S.ASECTION, SIZE are typically initialized when the objfile is first
107    scanned.  BUFFER, READIN are filled in later when the section is read.
108    If the section contained compressed data then SIZE is updated to record
109    the uncompressed size of the section.
110
111    DWP file format V2 introduces a wrinkle that is easiest to handle by
112    creating the concept of virtual sections contained within a real section.
113    In DWP V2 the sections of the input DWO files are concatenated together
114    into one section, but section offsets are kept relative to the original
115    input section.
116    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
117    the real section this "virtual" section is contained in, and BUFFER,SIZE
118    describe the virtual section.  */
119
120 struct dwarf2_section_info
121 {
122   union
123   {
124     /* If this is a real section, the bfd section.  */
125     asection *asection;
126     /* If this is a virtual section, pointer to the containing ("real")
127        section.  */
128     struct dwarf2_section_info *containing_section;
129   } s;
130   /* Pointer to section data, only valid if readin.  */
131   const gdb_byte *buffer;
132   /* The size of the section, real or virtual.  */
133   bfd_size_type size;
134   /* If this is a virtual section, the offset in the real section.
135      Only valid if is_virtual.  */
136   bfd_size_type virtual_offset;
137   /* True if we have tried to read this section.  */
138   char readin;
139   /* True if this is a virtual section, False otherwise.
140      This specifies which of s.asection and s.containing_section to use.  */
141   char is_virtual;
142 };
143
144 typedef struct dwarf2_section_info dwarf2_section_info_def;
145 DEF_VEC_O (dwarf2_section_info_def);
146
147 /* All offsets in the index are of this type.  It must be
148    architecture-independent.  */
149 typedef uint32_t offset_type;
150
151 DEF_VEC_I (offset_type);
152
153 /* Ensure only legit values are used.  */
154 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
155   do { \
156     gdb_assert ((unsigned int) (value) <= 1); \
157     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
158   } while (0)
159
160 /* Ensure only legit values are used.  */
161 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
162   do { \
163     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
164                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
165     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
166   } while (0)
167
168 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
169 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
172     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
173   } while (0)
174
175 /* A description of the mapped index.  The file format is described in
176    a comment by the code that writes the index.  */
177 struct mapped_index
178 {
179   /* Index data format version.  */
180   int version;
181
182   /* The total length of the buffer.  */
183   off_t total_size;
184
185   /* A pointer to the address table data.  */
186   const gdb_byte *address_table;
187
188   /* Size of the address table data in bytes.  */
189   offset_type address_table_size;
190
191   /* The symbol table, implemented as a hash table.  */
192   const offset_type *symbol_table;
193
194   /* Size in slots, each slot is 2 offset_types.  */
195   offset_type symbol_table_slots;
196
197   /* A pointer to the constant pool.  */
198   const char *constant_pool;
199 };
200
201 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
202 DEF_VEC_P (dwarf2_per_cu_ptr);
203
204 /* Collection of data recorded per objfile.
205    This hangs off of dwarf2_objfile_data_key.  */
206
207 struct dwarf2_per_objfile
208 {
209   struct dwarf2_section_info info;
210   struct dwarf2_section_info abbrev;
211   struct dwarf2_section_info line;
212   struct dwarf2_section_info loc;
213   struct dwarf2_section_info macinfo;
214   struct dwarf2_section_info macro;
215   struct dwarf2_section_info str;
216   struct dwarf2_section_info ranges;
217   struct dwarf2_section_info addr;
218   struct dwarf2_section_info frame;
219   struct dwarf2_section_info eh_frame;
220   struct dwarf2_section_info gdb_index;
221
222   VEC (dwarf2_section_info_def) *types;
223
224   /* Back link.  */
225   struct objfile *objfile;
226
227   /* Table of all the compilation units.  This is used to locate
228      the target compilation unit of a particular reference.  */
229   struct dwarf2_per_cu_data **all_comp_units;
230
231   /* The number of compilation units in ALL_COMP_UNITS.  */
232   int n_comp_units;
233
234   /* The number of .debug_types-related CUs.  */
235   int n_type_units;
236
237   /* The .debug_types-related CUs (TUs).
238      This is stored in malloc space because we may realloc it.  */
239   struct signatured_type **all_type_units;
240
241   /* The number of entries in all_type_unit_groups.  */
242   int n_type_unit_groups;
243
244   /* Table of type unit groups.
245      This exists to make it easy to iterate over all CUs and TU groups.  */
246   struct type_unit_group **all_type_unit_groups;
247
248   /* Table of struct type_unit_group objects.
249      The hash key is the DW_AT_stmt_list value.  */
250   htab_t type_unit_groups;
251
252   /* A table mapping .debug_types signatures to its signatured_type entry.
253      This is NULL if the .debug_types section hasn't been read in yet.  */
254   htab_t signatured_types;
255
256   /* Type unit statistics, to see how well the scaling improvements
257      are doing.  */
258   struct tu_stats
259   {
260     int nr_uniq_abbrev_tables;
261     int nr_symtabs;
262     int nr_symtab_sharers;
263     int nr_stmt_less_type_units;
264   } tu_stats;
265
266   /* A chain of compilation units that are currently read in, so that
267      they can be freed later.  */
268   struct dwarf2_per_cu_data *read_in_chain;
269
270   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
271      This is NULL if the table hasn't been allocated yet.  */
272   htab_t dwo_files;
273
274   /* Non-zero if we've check for whether there is a DWP file.  */
275   int dwp_checked;
276
277   /* The DWP file if there is one, or NULL.  */
278   struct dwp_file *dwp_file;
279
280   /* The shared '.dwz' file, if one exists.  This is used when the
281      original data was compressed using 'dwz -m'.  */
282   struct dwz_file *dwz_file;
283
284   /* A flag indicating wether this objfile has a section loaded at a
285      VMA of 0.  */
286   int has_section_at_zero;
287
288   /* True if we are using the mapped index,
289      or we are faking it for OBJF_READNOW's sake.  */
290   unsigned char using_index;
291
292   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
293   struct mapped_index *index_table;
294
295   /* When using index_table, this keeps track of all quick_file_names entries.
296      TUs typically share line table entries with a CU, so we maintain a
297      separate table of all line table entries to support the sharing.
298      Note that while there can be way more TUs than CUs, we've already
299      sorted all the TUs into "type unit groups", grouped by their
300      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
301      CU and its associated TU group if there is one.  */
302   htab_t quick_file_names_table;
303
304   /* Set during partial symbol reading, to prevent queueing of full
305      symbols.  */
306   int reading_partial_symbols;
307
308   /* Table mapping type DIEs to their struct type *.
309      This is NULL if not allocated yet.
310      The mapping is done via (CU/TU + DIE offset) -> type.  */
311   htab_t die_type_hash;
312
313   /* The CUs we recently read.  */
314   VEC (dwarf2_per_cu_ptr) *just_read_cus;
315 };
316
317 static struct dwarf2_per_objfile *dwarf2_per_objfile;
318
319 /* Default names of the debugging sections.  */
320
321 /* Note that if the debugging section has been compressed, it might
322    have a name like .zdebug_info.  */
323
324 static const struct dwarf2_debug_sections dwarf2_elf_names =
325 {
326   { ".debug_info", ".zdebug_info" },
327   { ".debug_abbrev", ".zdebug_abbrev" },
328   { ".debug_line", ".zdebug_line" },
329   { ".debug_loc", ".zdebug_loc" },
330   { ".debug_macinfo", ".zdebug_macinfo" },
331   { ".debug_macro", ".zdebug_macro" },
332   { ".debug_str", ".zdebug_str" },
333   { ".debug_ranges", ".zdebug_ranges" },
334   { ".debug_types", ".zdebug_types" },
335   { ".debug_addr", ".zdebug_addr" },
336   { ".debug_frame", ".zdebug_frame" },
337   { ".eh_frame", NULL },
338   { ".gdb_index", ".zgdb_index" },
339   23
340 };
341
342 /* List of DWO/DWP sections.  */
343
344 static const struct dwop_section_names
345 {
346   struct dwarf2_section_names abbrev_dwo;
347   struct dwarf2_section_names info_dwo;
348   struct dwarf2_section_names line_dwo;
349   struct dwarf2_section_names loc_dwo;
350   struct dwarf2_section_names macinfo_dwo;
351   struct dwarf2_section_names macro_dwo;
352   struct dwarf2_section_names str_dwo;
353   struct dwarf2_section_names str_offsets_dwo;
354   struct dwarf2_section_names types_dwo;
355   struct dwarf2_section_names cu_index;
356   struct dwarf2_section_names tu_index;
357 }
358 dwop_section_names =
359 {
360   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
361   { ".debug_info.dwo", ".zdebug_info.dwo" },
362   { ".debug_line.dwo", ".zdebug_line.dwo" },
363   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
364   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
365   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
366   { ".debug_str.dwo", ".zdebug_str.dwo" },
367   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
368   { ".debug_types.dwo", ".zdebug_types.dwo" },
369   { ".debug_cu_index", ".zdebug_cu_index" },
370   { ".debug_tu_index", ".zdebug_tu_index" },
371 };
372
373 /* local data types */
374
375 /* The data in a compilation unit header, after target2host
376    translation, looks like this.  */
377 struct comp_unit_head
378 {
379   unsigned int length;
380   short version;
381   unsigned char addr_size;
382   unsigned char signed_addr_p;
383   sect_offset abbrev_offset;
384
385   /* Size of file offsets; either 4 or 8.  */
386   unsigned int offset_size;
387
388   /* Size of the length field; either 4 or 12.  */
389   unsigned int initial_length_size;
390
391   /* Offset to the first byte of this compilation unit header in the
392      .debug_info section, for resolving relative reference dies.  */
393   sect_offset offset;
394
395   /* Offset to first die in this cu from the start of the cu.
396      This will be the first byte following the compilation unit header.  */
397   cu_offset first_die_offset;
398 };
399
400 /* Type used for delaying computation of method physnames.
401    See comments for compute_delayed_physnames.  */
402 struct delayed_method_info
403 {
404   /* The type to which the method is attached, i.e., its parent class.  */
405   struct type *type;
406
407   /* The index of the method in the type's function fieldlists.  */
408   int fnfield_index;
409
410   /* The index of the method in the fieldlist.  */
411   int index;
412
413   /* The name of the DIE.  */
414   const char *name;
415
416   /*  The DIE associated with this method.  */
417   struct die_info *die;
418 };
419
420 typedef struct delayed_method_info delayed_method_info;
421 DEF_VEC_O (delayed_method_info);
422
423 /* Internal state when decoding a particular compilation unit.  */
424 struct dwarf2_cu
425 {
426   /* The objfile containing this compilation unit.  */
427   struct objfile *objfile;
428
429   /* The header of the compilation unit.  */
430   struct comp_unit_head header;
431
432   /* Base address of this compilation unit.  */
433   CORE_ADDR base_address;
434
435   /* Non-zero if base_address has been set.  */
436   int base_known;
437
438   /* The language we are debugging.  */
439   enum language language;
440   const struct language_defn *language_defn;
441
442   const char *producer;
443
444   /* The generic symbol table building routines have separate lists for
445      file scope symbols and all all other scopes (local scopes).  So
446      we need to select the right one to pass to add_symbol_to_list().
447      We do it by keeping a pointer to the correct list in list_in_scope.
448
449      FIXME: The original dwarf code just treated the file scope as the
450      first local scope, and all other local scopes as nested local
451      scopes, and worked fine.  Check to see if we really need to
452      distinguish these in buildsym.c.  */
453   struct pending **list_in_scope;
454
455   /* The abbrev table for this CU.
456      Normally this points to the abbrev table in the objfile.
457      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
458   struct abbrev_table *abbrev_table;
459
460   /* Hash table holding all the loaded partial DIEs
461      with partial_die->offset.SECT_OFF as hash.  */
462   htab_t partial_dies;
463
464   /* Storage for things with the same lifetime as this read-in compilation
465      unit, including partial DIEs.  */
466   struct obstack comp_unit_obstack;
467
468   /* When multiple dwarf2_cu structures are living in memory, this field
469      chains them all together, so that they can be released efficiently.
470      We will probably also want a generation counter so that most-recently-used
471      compilation units are cached...  */
472   struct dwarf2_per_cu_data *read_in_chain;
473
474   /* Backlink to our per_cu entry.  */
475   struct dwarf2_per_cu_data *per_cu;
476
477   /* How many compilation units ago was this CU last referenced?  */
478   int last_used;
479
480   /* A hash table of DIE cu_offset for following references with
481      die_info->offset.sect_off as hash.  */
482   htab_t die_hash;
483
484   /* Full DIEs if read in.  */
485   struct die_info *dies;
486
487   /* A set of pointers to dwarf2_per_cu_data objects for compilation
488      units referenced by this one.  Only set during full symbol processing;
489      partial symbol tables do not have dependencies.  */
490   htab_t dependencies;
491
492   /* Header data from the line table, during full symbol processing.  */
493   struct line_header *line_header;
494
495   /* A list of methods which need to have physnames computed
496      after all type information has been read.  */
497   VEC (delayed_method_info) *method_list;
498
499   /* To be copied to symtab->call_site_htab.  */
500   htab_t call_site_htab;
501
502   /* Non-NULL if this CU came from a DWO file.
503      There is an invariant here that is important to remember:
504      Except for attributes copied from the top level DIE in the "main"
505      (or "stub") file in preparation for reading the DWO file
506      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
507      Either there isn't a DWO file (in which case this is NULL and the point
508      is moot), or there is and either we're not going to read it (in which
509      case this is NULL) or there is and we are reading it (in which case this
510      is non-NULL).  */
511   struct dwo_unit *dwo_unit;
512
513   /* The DW_AT_addr_base attribute if present, zero otherwise
514      (zero is a valid value though).
515      Note this value comes from the stub CU/TU's DIE.  */
516   ULONGEST addr_base;
517
518   /* The DW_AT_ranges_base attribute if present, zero otherwise
519      (zero is a valid value though).
520      Note this value comes from the stub CU/TU's DIE.
521      Also note that the value is zero in the non-DWO case so this value can
522      be used without needing to know whether DWO files are in use or not.
523      N.B. This does not apply to DW_AT_ranges appearing in
524      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
525      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
526      DW_AT_ranges_base *would* have to be applied, and we'd have to care
527      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
528   ULONGEST ranges_base;
529
530   /* Mark used when releasing cached dies.  */
531   unsigned int mark : 1;
532
533   /* This CU references .debug_loc.  See the symtab->locations_valid field.
534      This test is imperfect as there may exist optimized debug code not using
535      any location list and still facing inlining issues if handled as
536      unoptimized code.  For a future better test see GCC PR other/32998.  */
537   unsigned int has_loclist : 1;
538
539   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
540      if all the producer_is_* fields are valid.  This information is cached
541      because profiling CU expansion showed excessive time spent in
542      producer_is_gxx_lt_4_6.  */
543   unsigned int checked_producer : 1;
544   unsigned int producer_is_gxx_lt_4_6 : 1;
545   unsigned int producer_is_gcc_lt_4_3 : 1;
546   unsigned int producer_is_icc : 1;
547
548   /* When set, the file that we're processing is known to have
549      debugging info for C++ namespaces.  GCC 3.3.x did not produce
550      this information, but later versions do.  */
551
552   unsigned int processing_has_namespace_info : 1;
553 };
554
555 /* Persistent data held for a compilation unit, even when not
556    processing it.  We put a pointer to this structure in the
557    read_symtab_private field of the psymtab.  */
558
559 struct dwarf2_per_cu_data
560 {
561   /* The start offset and length of this compilation unit.
562      NOTE: Unlike comp_unit_head.length, this length includes
563      initial_length_size.
564      If the DIE refers to a DWO file, this is always of the original die,
565      not the DWO file.  */
566   sect_offset offset;
567   unsigned int length;
568
569   /* Flag indicating this compilation unit will be read in before
570      any of the current compilation units are processed.  */
571   unsigned int queued : 1;
572
573   /* This flag will be set when reading partial DIEs if we need to load
574      absolutely all DIEs for this compilation unit, instead of just the ones
575      we think are interesting.  It gets set if we look for a DIE in the
576      hash table and don't find it.  */
577   unsigned int load_all_dies : 1;
578
579   /* Non-zero if this CU is from .debug_types.
580      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
581      this is non-zero.  */
582   unsigned int is_debug_types : 1;
583
584   /* Non-zero if this CU is from the .dwz file.  */
585   unsigned int is_dwz : 1;
586
587   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
588      This flag is only valid if is_debug_types is true.
589      We can't read a CU directly from a DWO file: There are required
590      attributes in the stub.  */
591   unsigned int reading_dwo_directly : 1;
592
593   /* Non-zero if the TU has been read.
594      This is used to assist the "Stay in DWO Optimization" for Fission:
595      When reading a DWO, it's faster to read TUs from the DWO instead of
596      fetching them from random other DWOs (due to comdat folding).
597      If the TU has already been read, the optimization is unnecessary
598      (and unwise - we don't want to change where gdb thinks the TU lives
599      "midflight").
600      This flag is only valid if is_debug_types is true.  */
601   unsigned int tu_read : 1;
602
603   /* The section this CU/TU lives in.
604      If the DIE refers to a DWO file, this is always the original die,
605      not the DWO file.  */
606   struct dwarf2_section_info *section;
607
608   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
609      of the CU cache it gets reset to NULL again.  */
610   struct dwarf2_cu *cu;
611
612   /* The corresponding objfile.
613      Normally we can get the objfile from dwarf2_per_objfile.
614      However we can enter this file with just a "per_cu" handle.  */
615   struct objfile *objfile;
616
617   /* When using partial symbol tables, the 'psymtab' field is active.
618      Otherwise the 'quick' field is active.  */
619   union
620   {
621     /* The partial symbol table associated with this compilation unit,
622        or NULL for unread partial units.  */
623     struct partial_symtab *psymtab;
624
625     /* Data needed by the "quick" functions.  */
626     struct dwarf2_per_cu_quick_data *quick;
627   } v;
628
629   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
630      while reading psymtabs, used to compute the psymtab dependencies,
631      and then cleared.  Then it is filled in again while reading full
632      symbols, and only deleted when the objfile is destroyed.
633
634      This is also used to work around a difference between the way gold
635      generates .gdb_index version <=7 and the way gdb does.  Arguably this
636      is a gold bug.  For symbols coming from TUs, gold records in the index
637      the CU that includes the TU instead of the TU itself.  This breaks
638      dw2_lookup_symbol: It assumes that if the index says symbol X lives
639      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
640      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
641      we need to look in TU Z to find X.  Fortunately, this is akin to
642      DW_TAG_imported_unit, so we just use the same mechanism: For
643      .gdb_index version <=7 this also records the TUs that the CU referred
644      to.  Concurrently with this change gdb was modified to emit version 8
645      indices so we only pay a price for gold generated indices.
646      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
647   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
648 };
649
650 /* Entry in the signatured_types hash table.  */
651
652 struct signatured_type
653 {
654   /* The "per_cu" object of this type.
655      This struct is used iff per_cu.is_debug_types.
656      N.B.: This is the first member so that it's easy to convert pointers
657      between them.  */
658   struct dwarf2_per_cu_data per_cu;
659
660   /* The type's signature.  */
661   ULONGEST signature;
662
663   /* Offset in the TU of the type's DIE, as read from the TU header.
664      If this TU is a DWO stub and the definition lives in a DWO file
665      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
666   cu_offset type_offset_in_tu;
667
668   /* Offset in the section of the type's DIE.
669      If the definition lives in a DWO file, this is the offset in the
670      .debug_types.dwo section.
671      The value is zero until the actual value is known.
672      Zero is otherwise not a valid section offset.  */
673   sect_offset type_offset_in_section;
674
675   /* Type units are grouped by their DW_AT_stmt_list entry so that they
676      can share them.  This points to the containing symtab.  */
677   struct type_unit_group *type_unit_group;
678
679   /* The type.
680      The first time we encounter this type we fully read it in and install it
681      in the symbol tables.  Subsequent times we only need the type.  */
682   struct type *type;
683
684   /* Containing DWO unit.
685      This field is valid iff per_cu.reading_dwo_directly.  */
686   struct dwo_unit *dwo_unit;
687 };
688
689 typedef struct signatured_type *sig_type_ptr;
690 DEF_VEC_P (sig_type_ptr);
691
692 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
693    This includes type_unit_group and quick_file_names.  */
694
695 struct stmt_list_hash
696 {
697   /* The DWO unit this table is from or NULL if there is none.  */
698   struct dwo_unit *dwo_unit;
699
700   /* Offset in .debug_line or .debug_line.dwo.  */
701   sect_offset line_offset;
702 };
703
704 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
705    an object of this type.  */
706
707 struct type_unit_group
708 {
709   /* dwarf2read.c's main "handle" on a TU symtab.
710      To simplify things we create an artificial CU that "includes" all the
711      type units using this stmt_list so that the rest of the code still has
712      a "per_cu" handle on the symtab.
713      This PER_CU is recognized by having no section.  */
714 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
715   struct dwarf2_per_cu_data per_cu;
716
717   /* The TUs that share this DW_AT_stmt_list entry.
718      This is added to while parsing type units to build partial symtabs,
719      and is deleted afterwards and not used again.  */
720   VEC (sig_type_ptr) *tus;
721
722   /* The primary symtab.
723      Type units in a group needn't all be defined in the same source file,
724      so we create an essentially anonymous symtab as the primary symtab.  */
725   struct symtab *primary_symtab;
726
727   /* The data used to construct the hash key.  */
728   struct stmt_list_hash hash;
729
730   /* The number of symtabs from the line header.
731      The value here must match line_header.num_file_names.  */
732   unsigned int num_symtabs;
733
734   /* The symbol tables for this TU (obtained from the files listed in
735      DW_AT_stmt_list).
736      WARNING: The order of entries here must match the order of entries
737      in the line header.  After the first TU using this type_unit_group, the
738      line header for the subsequent TUs is recreated from this.  This is done
739      because we need to use the same symtabs for each TU using the same
740      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
741      there's no guarantee the line header doesn't have duplicate entries.  */
742   struct symtab **symtabs;
743 };
744
745 /* These sections are what may appear in a (real or virtual) DWO file.  */
746
747 struct dwo_sections
748 {
749   struct dwarf2_section_info abbrev;
750   struct dwarf2_section_info line;
751   struct dwarf2_section_info loc;
752   struct dwarf2_section_info macinfo;
753   struct dwarf2_section_info macro;
754   struct dwarf2_section_info str;
755   struct dwarf2_section_info str_offsets;
756   /* In the case of a virtual DWO file, these two are unused.  */
757   struct dwarf2_section_info info;
758   VEC (dwarf2_section_info_def) *types;
759 };
760
761 /* CUs/TUs in DWP/DWO files.  */
762
763 struct dwo_unit
764 {
765   /* Backlink to the containing struct dwo_file.  */
766   struct dwo_file *dwo_file;
767
768   /* The "id" that distinguishes this CU/TU.
769      .debug_info calls this "dwo_id", .debug_types calls this "signature".
770      Since signatures came first, we stick with it for consistency.  */
771   ULONGEST signature;
772
773   /* The section this CU/TU lives in, in the DWO file.  */
774   struct dwarf2_section_info *section;
775
776   /* Same as dwarf2_per_cu_data:{offset,length} but in the DWO section.  */
777   sect_offset offset;
778   unsigned int length;
779
780   /* For types, offset in the type's DIE of the type defined by this TU.  */
781   cu_offset type_offset_in_tu;
782 };
783
784 /* include/dwarf2.h defines the DWP section codes.
785    It defines a max value but it doesn't define a min value, which we
786    use for error checking, so provide one.  */
787
788 enum dwp_v2_section_ids
789 {
790   DW_SECT_MIN = 1
791 };
792
793 /* Data for one DWO file.
794
795    This includes virtual DWO files (a virtual DWO file is a DWO file as it
796    appears in a DWP file).  DWP files don't really have DWO files per se -
797    comdat folding of types "loses" the DWO file they came from, and from
798    a high level view DWP files appear to contain a mass of random types.
799    However, to maintain consistency with the non-DWP case we pretend DWP
800    files contain virtual DWO files, and we assign each TU with one virtual
801    DWO file (generally based on the line and abbrev section offsets -
802    a heuristic that seems to work in practice).  */
803
804 struct dwo_file
805 {
806   /* The DW_AT_GNU_dwo_name attribute.
807      For virtual DWO files the name is constructed from the section offsets
808      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
809      from related CU+TUs.  */
810   const char *dwo_name;
811
812   /* The DW_AT_comp_dir attribute.  */
813   const char *comp_dir;
814
815   /* The bfd, when the file is open.  Otherwise this is NULL.
816      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
817   bfd *dbfd;
818
819   /* The sections that make up this DWO file.
820      Remember that for virtual DWO files in DWP V2, these are virtual
821      sections (for lack of a better name).  */
822   struct dwo_sections sections;
823
824   /* The CU in the file.
825      We only support one because having more than one requires hacking the
826      dwo_name of each to match, which is highly unlikely to happen.
827      Doing this means all TUs can share comp_dir: We also assume that
828      DW_AT_comp_dir across all TUs in a DWO file will be identical.  */
829   struct dwo_unit *cu;
830
831   /* Table of TUs in the file.
832      Each element is a struct dwo_unit.  */
833   htab_t tus;
834 };
835
836 /* These sections are what may appear in a DWP file.  */
837
838 struct dwp_sections
839 {
840   /* These are used by both DWP version 1 and 2.  */
841   struct dwarf2_section_info str;
842   struct dwarf2_section_info cu_index;
843   struct dwarf2_section_info tu_index;
844
845   /* These are only used by DWP version 2 files.
846      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
847      sections are referenced by section number, and are not recorded here.
848      In DWP version 2 there is at most one copy of all these sections, each
849      section being (effectively) comprised of the concatenation of all of the
850      individual sections that exist in the version 1 format.
851      To keep the code simple we treat each of these concatenated pieces as a
852      section itself (a virtual section?).  */
853   struct dwarf2_section_info abbrev;
854   struct dwarf2_section_info info;
855   struct dwarf2_section_info line;
856   struct dwarf2_section_info loc;
857   struct dwarf2_section_info macinfo;
858   struct dwarf2_section_info macro;
859   struct dwarf2_section_info str_offsets;
860   struct dwarf2_section_info types;
861 };
862
863 /* These sections are what may appear in a virtual DWO file in DWP version 1.
864    A virtual DWO file is a DWO file as it appears in a DWP file.  */
865
866 struct virtual_v1_dwo_sections
867 {
868   struct dwarf2_section_info abbrev;
869   struct dwarf2_section_info line;
870   struct dwarf2_section_info loc;
871   struct dwarf2_section_info macinfo;
872   struct dwarf2_section_info macro;
873   struct dwarf2_section_info str_offsets;
874   /* Each DWP hash table entry records one CU or one TU.
875      That is recorded here, and copied to dwo_unit.section.  */
876   struct dwarf2_section_info info_or_types;
877 };
878
879 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
880    In version 2, the sections of the DWO files are concatenated together
881    and stored in one section of that name.  Thus each ELF section contains
882    several "virtual" sections.  */
883
884 struct virtual_v2_dwo_sections
885 {
886   bfd_size_type abbrev_offset;
887   bfd_size_type abbrev_size;
888
889   bfd_size_type line_offset;
890   bfd_size_type line_size;
891
892   bfd_size_type loc_offset;
893   bfd_size_type loc_size;
894
895   bfd_size_type macinfo_offset;
896   bfd_size_type macinfo_size;
897
898   bfd_size_type macro_offset;
899   bfd_size_type macro_size;
900
901   bfd_size_type str_offsets_offset;
902   bfd_size_type str_offsets_size;
903
904   /* Each DWP hash table entry records one CU or one TU.
905      That is recorded here, and copied to dwo_unit.section.  */
906   bfd_size_type info_or_types_offset;
907   bfd_size_type info_or_types_size;
908 };
909
910 /* Contents of DWP hash tables.  */
911
912 struct dwp_hash_table
913 {
914   uint32_t version, nr_columns;
915   uint32_t nr_units, nr_slots;
916   const gdb_byte *hash_table, *unit_table;
917   union
918   {
919     struct
920     {
921       const gdb_byte *indices;
922     } v1;
923     struct
924     {
925       /* This is indexed by column number and gives the id of the section
926          in that column.  */
927 #define MAX_NR_V2_DWO_SECTIONS \
928   (1 /* .debug_info or .debug_types */ \
929    + 1 /* .debug_abbrev */ \
930    + 1 /* .debug_line */ \
931    + 1 /* .debug_loc */ \
932    + 1 /* .debug_str_offsets */ \
933    + 1 /* .debug_macro or .debug_macinfo */)
934       int section_ids[MAX_NR_V2_DWO_SECTIONS];
935       const gdb_byte *offsets;
936       const gdb_byte *sizes;
937     } v2;
938   } section_pool;
939 };
940
941 /* Data for one DWP file.  */
942
943 struct dwp_file
944 {
945   /* Name of the file.  */
946   const char *name;
947
948   /* File format version.  */
949   int version;
950
951   /* The bfd.  */
952   bfd *dbfd;
953
954   /* Section info for this file.  */
955   struct dwp_sections sections;
956
957   /* Table of CUs in the file.  */
958   const struct dwp_hash_table *cus;
959
960   /* Table of TUs in the file.  */
961   const struct dwp_hash_table *tus;
962
963   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
964   htab_t loaded_cus;
965   htab_t loaded_tus;
966
967   /* Table to map ELF section numbers to their sections.
968      This is only needed for the DWP V1 file format.  */
969   unsigned int num_sections;
970   asection **elf_sections;
971 };
972
973 /* This represents a '.dwz' file.  */
974
975 struct dwz_file
976 {
977   /* A dwz file can only contain a few sections.  */
978   struct dwarf2_section_info abbrev;
979   struct dwarf2_section_info info;
980   struct dwarf2_section_info str;
981   struct dwarf2_section_info line;
982   struct dwarf2_section_info macro;
983   struct dwarf2_section_info gdb_index;
984
985   /* The dwz's BFD.  */
986   bfd *dwz_bfd;
987 };
988
989 /* Struct used to pass misc. parameters to read_die_and_children, et
990    al.  which are used for both .debug_info and .debug_types dies.
991    All parameters here are unchanging for the life of the call.  This
992    struct exists to abstract away the constant parameters of die reading.  */
993
994 struct die_reader_specs
995 {
996   /* The bfd of die_section.  */
997   bfd* abfd;
998
999   /* The CU of the DIE we are parsing.  */
1000   struct dwarf2_cu *cu;
1001
1002   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1003   struct dwo_file *dwo_file;
1004
1005   /* The section the die comes from.
1006      This is either .debug_info or .debug_types, or the .dwo variants.  */
1007   struct dwarf2_section_info *die_section;
1008
1009   /* die_section->buffer.  */
1010   const gdb_byte *buffer;
1011
1012   /* The end of the buffer.  */
1013   const gdb_byte *buffer_end;
1014
1015   /* The value of the DW_AT_comp_dir attribute.  */
1016   const char *comp_dir;
1017 };
1018
1019 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1020 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1021                                       const gdb_byte *info_ptr,
1022                                       struct die_info *comp_unit_die,
1023                                       int has_children,
1024                                       void *data);
1025
1026 /* The line number information for a compilation unit (found in the
1027    .debug_line section) begins with a "statement program header",
1028    which contains the following information.  */
1029 struct line_header
1030 {
1031   unsigned int total_length;
1032   unsigned short version;
1033   unsigned int header_length;
1034   unsigned char minimum_instruction_length;
1035   unsigned char maximum_ops_per_instruction;
1036   unsigned char default_is_stmt;
1037   int line_base;
1038   unsigned char line_range;
1039   unsigned char opcode_base;
1040
1041   /* standard_opcode_lengths[i] is the number of operands for the
1042      standard opcode whose value is i.  This means that
1043      standard_opcode_lengths[0] is unused, and the last meaningful
1044      element is standard_opcode_lengths[opcode_base - 1].  */
1045   unsigned char *standard_opcode_lengths;
1046
1047   /* The include_directories table.  NOTE!  These strings are not
1048      allocated with xmalloc; instead, they are pointers into
1049      debug_line_buffer.  If you try to free them, `free' will get
1050      indigestion.  */
1051   unsigned int num_include_dirs, include_dirs_size;
1052   const char **include_dirs;
1053
1054   /* The file_names table.  NOTE!  These strings are not allocated
1055      with xmalloc; instead, they are pointers into debug_line_buffer.
1056      Don't try to free them directly.  */
1057   unsigned int num_file_names, file_names_size;
1058   struct file_entry
1059   {
1060     const char *name;
1061     unsigned int dir_index;
1062     unsigned int mod_time;
1063     unsigned int length;
1064     int included_p; /* Non-zero if referenced by the Line Number Program.  */
1065     struct symtab *symtab; /* The associated symbol table, if any.  */
1066   } *file_names;
1067
1068   /* The start and end of the statement program following this
1069      header.  These point into dwarf2_per_objfile->line_buffer.  */
1070   const gdb_byte *statement_program_start, *statement_program_end;
1071 };
1072
1073 /* When we construct a partial symbol table entry we only
1074    need this much information.  */
1075 struct partial_die_info
1076   {
1077     /* Offset of this DIE.  */
1078     sect_offset offset;
1079
1080     /* DWARF-2 tag for this DIE.  */
1081     ENUM_BITFIELD(dwarf_tag) tag : 16;
1082
1083     /* Assorted flags describing the data found in this DIE.  */
1084     unsigned int has_children : 1;
1085     unsigned int is_external : 1;
1086     unsigned int is_declaration : 1;
1087     unsigned int has_type : 1;
1088     unsigned int has_specification : 1;
1089     unsigned int has_pc_info : 1;
1090     unsigned int may_be_inlined : 1;
1091
1092     /* Flag set if the SCOPE field of this structure has been
1093        computed.  */
1094     unsigned int scope_set : 1;
1095
1096     /* Flag set if the DIE has a byte_size attribute.  */
1097     unsigned int has_byte_size : 1;
1098
1099     /* Flag set if any of the DIE's children are template arguments.  */
1100     unsigned int has_template_arguments : 1;
1101
1102     /* Flag set if fixup_partial_die has been called on this die.  */
1103     unsigned int fixup_called : 1;
1104
1105     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1106     unsigned int is_dwz : 1;
1107
1108     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1109     unsigned int spec_is_dwz : 1;
1110
1111     /* The name of this DIE.  Normally the value of DW_AT_name, but
1112        sometimes a default name for unnamed DIEs.  */
1113     const char *name;
1114
1115     /* The linkage name, if present.  */
1116     const char *linkage_name;
1117
1118     /* The scope to prepend to our children.  This is generally
1119        allocated on the comp_unit_obstack, so will disappear
1120        when this compilation unit leaves the cache.  */
1121     const char *scope;
1122
1123     /* Some data associated with the partial DIE.  The tag determines
1124        which field is live.  */
1125     union
1126     {
1127       /* The location description associated with this DIE, if any.  */
1128       struct dwarf_block *locdesc;
1129       /* The offset of an import, for DW_TAG_imported_unit.  */
1130       sect_offset offset;
1131     } d;
1132
1133     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1134     CORE_ADDR lowpc;
1135     CORE_ADDR highpc;
1136
1137     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1138        DW_AT_sibling, if any.  */
1139     /* NOTE: This member isn't strictly necessary, read_partial_die could
1140        return DW_AT_sibling values to its caller load_partial_dies.  */
1141     const gdb_byte *sibling;
1142
1143     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1144        DW_AT_specification (or DW_AT_abstract_origin or
1145        DW_AT_extension).  */
1146     sect_offset spec_offset;
1147
1148     /* Pointers to this DIE's parent, first child, and next sibling,
1149        if any.  */
1150     struct partial_die_info *die_parent, *die_child, *die_sibling;
1151   };
1152
1153 /* This data structure holds the information of an abbrev.  */
1154 struct abbrev_info
1155   {
1156     unsigned int number;        /* number identifying abbrev */
1157     enum dwarf_tag tag;         /* dwarf tag */
1158     unsigned short has_children;                /* boolean */
1159     unsigned short num_attrs;   /* number of attributes */
1160     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1161     struct abbrev_info *next;   /* next in chain */
1162   };
1163
1164 struct attr_abbrev
1165   {
1166     ENUM_BITFIELD(dwarf_attribute) name : 16;
1167     ENUM_BITFIELD(dwarf_form) form : 16;
1168   };
1169
1170 /* Size of abbrev_table.abbrev_hash_table.  */
1171 #define ABBREV_HASH_SIZE 121
1172
1173 /* Top level data structure to contain an abbreviation table.  */
1174
1175 struct abbrev_table
1176 {
1177   /* Where the abbrev table came from.
1178      This is used as a sanity check when the table is used.  */
1179   sect_offset offset;
1180
1181   /* Storage for the abbrev table.  */
1182   struct obstack abbrev_obstack;
1183
1184   /* Hash table of abbrevs.
1185      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1186      It could be statically allocated, but the previous code didn't so we
1187      don't either.  */
1188   struct abbrev_info **abbrevs;
1189 };
1190
1191 /* Attributes have a name and a value.  */
1192 struct attribute
1193   {
1194     ENUM_BITFIELD(dwarf_attribute) name : 16;
1195     ENUM_BITFIELD(dwarf_form) form : 15;
1196
1197     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1198        field should be in u.str (existing only for DW_STRING) but it is kept
1199        here for better struct attribute alignment.  */
1200     unsigned int string_is_canonical : 1;
1201
1202     union
1203       {
1204         const char *str;
1205         struct dwarf_block *blk;
1206         ULONGEST unsnd;
1207         LONGEST snd;
1208         CORE_ADDR addr;
1209         ULONGEST signature;
1210       }
1211     u;
1212   };
1213
1214 /* This data structure holds a complete die structure.  */
1215 struct die_info
1216   {
1217     /* DWARF-2 tag for this DIE.  */
1218     ENUM_BITFIELD(dwarf_tag) tag : 16;
1219
1220     /* Number of attributes */
1221     unsigned char num_attrs;
1222
1223     /* True if we're presently building the full type name for the
1224        type derived from this DIE.  */
1225     unsigned char building_fullname : 1;
1226
1227     /* Abbrev number */
1228     unsigned int abbrev;
1229
1230     /* Offset in .debug_info or .debug_types section.  */
1231     sect_offset offset;
1232
1233     /* The dies in a compilation unit form an n-ary tree.  PARENT
1234        points to this die's parent; CHILD points to the first child of
1235        this node; and all the children of a given node are chained
1236        together via their SIBLING fields.  */
1237     struct die_info *child;     /* Its first child, if any.  */
1238     struct die_info *sibling;   /* Its next sibling, if any.  */
1239     struct die_info *parent;    /* Its parent, if any.  */
1240
1241     /* An array of attributes, with NUM_ATTRS elements.  There may be
1242        zero, but it's not common and zero-sized arrays are not
1243        sufficiently portable C.  */
1244     struct attribute attrs[1];
1245   };
1246
1247 /* Get at parts of an attribute structure.  */
1248
1249 #define DW_STRING(attr)    ((attr)->u.str)
1250 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1251 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1252 #define DW_BLOCK(attr)     ((attr)->u.blk)
1253 #define DW_SND(attr)       ((attr)->u.snd)
1254 #define DW_ADDR(attr)      ((attr)->u.addr)
1255 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1256
1257 /* Blocks are a bunch of untyped bytes.  */
1258 struct dwarf_block
1259   {
1260     size_t size;
1261
1262     /* Valid only if SIZE is not zero.  */
1263     const gdb_byte *data;
1264   };
1265
1266 #ifndef ATTR_ALLOC_CHUNK
1267 #define ATTR_ALLOC_CHUNK 4
1268 #endif
1269
1270 /* Allocate fields for structs, unions and enums in this size.  */
1271 #ifndef DW_FIELD_ALLOC_CHUNK
1272 #define DW_FIELD_ALLOC_CHUNK 4
1273 #endif
1274
1275 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1276    but this would require a corresponding change in unpack_field_as_long
1277    and friends.  */
1278 static int bits_per_byte = 8;
1279
1280 /* The routines that read and process dies for a C struct or C++ class
1281    pass lists of data member fields and lists of member function fields
1282    in an instance of a field_info structure, as defined below.  */
1283 struct field_info
1284   {
1285     /* List of data member and baseclasses fields.  */
1286     struct nextfield
1287       {
1288         struct nextfield *next;
1289         int accessibility;
1290         int virtuality;
1291         struct field field;
1292       }
1293      *fields, *baseclasses;
1294
1295     /* Number of fields (including baseclasses).  */
1296     int nfields;
1297
1298     /* Number of baseclasses.  */
1299     int nbaseclasses;
1300
1301     /* Set if the accesibility of one of the fields is not public.  */
1302     int non_public_fields;
1303
1304     /* Member function fields array, entries are allocated in the order they
1305        are encountered in the object file.  */
1306     struct nextfnfield
1307       {
1308         struct nextfnfield *next;
1309         struct fn_field fnfield;
1310       }
1311      *fnfields;
1312
1313     /* Member function fieldlist array, contains name of possibly overloaded
1314        member function, number of overloaded member functions and a pointer
1315        to the head of the member function field chain.  */
1316     struct fnfieldlist
1317       {
1318         const char *name;
1319         int length;
1320         struct nextfnfield *head;
1321       }
1322      *fnfieldlists;
1323
1324     /* Number of entries in the fnfieldlists array.  */
1325     int nfnfields;
1326
1327     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1328        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1329     struct typedef_field_list
1330       {
1331         struct typedef_field field;
1332         struct typedef_field_list *next;
1333       }
1334     *typedef_field_list;
1335     unsigned typedef_field_list_count;
1336   };
1337
1338 /* One item on the queue of compilation units to read in full symbols
1339    for.  */
1340 struct dwarf2_queue_item
1341 {
1342   struct dwarf2_per_cu_data *per_cu;
1343   enum language pretend_language;
1344   struct dwarf2_queue_item *next;
1345 };
1346
1347 /* The current queue.  */
1348 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1349
1350 /* Loaded secondary compilation units are kept in memory until they
1351    have not been referenced for the processing of this many
1352    compilation units.  Set this to zero to disable caching.  Cache
1353    sizes of up to at least twenty will improve startup time for
1354    typical inter-CU-reference binaries, at an obvious memory cost.  */
1355 static int dwarf2_max_cache_age = 5;
1356 static void
1357 show_dwarf2_max_cache_age (struct ui_file *file, int from_tty,
1358                            struct cmd_list_element *c, const char *value)
1359 {
1360   fprintf_filtered (file, _("The upper bound on the age of cached "
1361                             "dwarf2 compilation units is %s.\n"),
1362                     value);
1363 }
1364 \f
1365 /* local function prototypes */
1366
1367 static const char *get_section_name (const struct dwarf2_section_info *);
1368
1369 static const char *get_section_file_name (const struct dwarf2_section_info *);
1370
1371 static void dwarf2_locate_sections (bfd *, asection *, void *);
1372
1373 static void dwarf2_find_base_address (struct die_info *die,
1374                                       struct dwarf2_cu *cu);
1375
1376 static struct partial_symtab *create_partial_symtab
1377   (struct dwarf2_per_cu_data *per_cu, const char *name);
1378
1379 static void dwarf2_build_psymtabs_hard (struct objfile *);
1380
1381 static void scan_partial_symbols (struct partial_die_info *,
1382                                   CORE_ADDR *, CORE_ADDR *,
1383                                   int, struct dwarf2_cu *);
1384
1385 static void add_partial_symbol (struct partial_die_info *,
1386                                 struct dwarf2_cu *);
1387
1388 static void add_partial_namespace (struct partial_die_info *pdi,
1389                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1390                                    int need_pc, struct dwarf2_cu *cu);
1391
1392 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1393                                 CORE_ADDR *highpc, int need_pc,
1394                                 struct dwarf2_cu *cu);
1395
1396 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1397                                      struct dwarf2_cu *cu);
1398
1399 static void add_partial_subprogram (struct partial_die_info *pdi,
1400                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1401                                     int need_pc, struct dwarf2_cu *cu);
1402
1403 static void dwarf2_read_symtab (struct partial_symtab *,
1404                                 struct objfile *);
1405
1406 static void psymtab_to_symtab_1 (struct partial_symtab *);
1407
1408 static struct abbrev_info *abbrev_table_lookup_abbrev
1409   (const struct abbrev_table *, unsigned int);
1410
1411 static struct abbrev_table *abbrev_table_read_table
1412   (struct dwarf2_section_info *, sect_offset);
1413
1414 static void abbrev_table_free (struct abbrev_table *);
1415
1416 static void abbrev_table_free_cleanup (void *);
1417
1418 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1419                                  struct dwarf2_section_info *);
1420
1421 static void dwarf2_free_abbrev_table (void *);
1422
1423 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1424
1425 static struct partial_die_info *load_partial_dies
1426   (const struct die_reader_specs *, const gdb_byte *, int);
1427
1428 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1429                                          struct partial_die_info *,
1430                                          struct abbrev_info *,
1431                                          unsigned int,
1432                                          const gdb_byte *);
1433
1434 static struct partial_die_info *find_partial_die (sect_offset, int,
1435                                                   struct dwarf2_cu *);
1436
1437 static void fixup_partial_die (struct partial_die_info *,
1438                                struct dwarf2_cu *);
1439
1440 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1441                                        struct attribute *, struct attr_abbrev *,
1442                                        const gdb_byte *);
1443
1444 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1445
1446 static int read_1_signed_byte (bfd *, const gdb_byte *);
1447
1448 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1449
1450 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1451
1452 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1453
1454 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1455                                unsigned int *);
1456
1457 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1458
1459 static LONGEST read_checked_initial_length_and_offset
1460   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1461    unsigned int *, unsigned int *);
1462
1463 static LONGEST read_offset (bfd *, const gdb_byte *,
1464                             const struct comp_unit_head *,
1465                             unsigned int *);
1466
1467 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1468
1469 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1470                                        sect_offset);
1471
1472 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1473
1474 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1475
1476 static const char *read_indirect_string (bfd *, const gdb_byte *,
1477                                          const struct comp_unit_head *,
1478                                          unsigned int *);
1479
1480 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1481
1482 static ULONGEST read_unsigned_leb128 (bfd *, const gdb_byte *, unsigned int *);
1483
1484 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1485
1486 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1487                                               const gdb_byte *,
1488                                               unsigned int *);
1489
1490 static const char *read_str_index (const struct die_reader_specs *reader,
1491                                    struct dwarf2_cu *cu, ULONGEST str_index);
1492
1493 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1494
1495 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1496                                       struct dwarf2_cu *);
1497
1498 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1499                                                 unsigned int);
1500
1501 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1502                                struct dwarf2_cu *cu);
1503
1504 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1505
1506 static struct die_info *die_specification (struct die_info *die,
1507                                            struct dwarf2_cu **);
1508
1509 static void free_line_header (struct line_header *lh);
1510
1511 static struct line_header *dwarf_decode_line_header (unsigned int offset,
1512                                                      struct dwarf2_cu *cu);
1513
1514 static void dwarf_decode_lines (struct line_header *, const char *,
1515                                 struct dwarf2_cu *, struct partial_symtab *,
1516                                 int);
1517
1518 static void dwarf2_start_subfile (const char *, const char *, const char *);
1519
1520 static void dwarf2_start_symtab (struct dwarf2_cu *,
1521                                  const char *, const char *, CORE_ADDR);
1522
1523 static struct symbol *new_symbol (struct die_info *, struct type *,
1524                                   struct dwarf2_cu *);
1525
1526 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1527                                        struct dwarf2_cu *, struct symbol *);
1528
1529 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1530                                 struct dwarf2_cu *);
1531
1532 static void dwarf2_const_value_attr (const struct attribute *attr,
1533                                      struct type *type,
1534                                      const char *name,
1535                                      struct obstack *obstack,
1536                                      struct dwarf2_cu *cu, LONGEST *value,
1537                                      const gdb_byte **bytes,
1538                                      struct dwarf2_locexpr_baton **baton);
1539
1540 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1541
1542 static int need_gnat_info (struct dwarf2_cu *);
1543
1544 static struct type *die_descriptive_type (struct die_info *,
1545                                           struct dwarf2_cu *);
1546
1547 static void set_descriptive_type (struct type *, struct die_info *,
1548                                   struct dwarf2_cu *);
1549
1550 static struct type *die_containing_type (struct die_info *,
1551                                          struct dwarf2_cu *);
1552
1553 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1554                                      struct dwarf2_cu *);
1555
1556 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1557
1558 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1559
1560 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1561
1562 static char *typename_concat (struct obstack *obs, const char *prefix,
1563                               const char *suffix, int physname,
1564                               struct dwarf2_cu *cu);
1565
1566 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1567
1568 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1569
1570 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1571
1572 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1573
1574 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1575
1576 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1577                                struct dwarf2_cu *, struct partial_symtab *);
1578
1579 static int dwarf2_get_pc_bounds (struct die_info *,
1580                                  CORE_ADDR *, CORE_ADDR *, struct dwarf2_cu *,
1581                                  struct partial_symtab *);
1582
1583 static void get_scope_pc_bounds (struct die_info *,
1584                                  CORE_ADDR *, CORE_ADDR *,
1585                                  struct dwarf2_cu *);
1586
1587 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1588                                         CORE_ADDR, struct dwarf2_cu *);
1589
1590 static void dwarf2_add_field (struct field_info *, struct die_info *,
1591                               struct dwarf2_cu *);
1592
1593 static void dwarf2_attach_fields_to_type (struct field_info *,
1594                                           struct type *, struct dwarf2_cu *);
1595
1596 static void dwarf2_add_member_fn (struct field_info *,
1597                                   struct die_info *, struct type *,
1598                                   struct dwarf2_cu *);
1599
1600 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1601                                              struct type *,
1602                                              struct dwarf2_cu *);
1603
1604 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1605
1606 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1607
1608 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1609
1610 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1611
1612 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1613
1614 static struct type *read_module_type (struct die_info *die,
1615                                       struct dwarf2_cu *cu);
1616
1617 static const char *namespace_name (struct die_info *die,
1618                                    int *is_anonymous, struct dwarf2_cu *);
1619
1620 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1621
1622 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1623
1624 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1625                                                        struct dwarf2_cu *);
1626
1627 static struct die_info *read_die_and_siblings_1
1628   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1629    struct die_info *);
1630
1631 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1632                                                const gdb_byte *info_ptr,
1633                                                const gdb_byte **new_info_ptr,
1634                                                struct die_info *parent);
1635
1636 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1637                                         struct die_info **, const gdb_byte *,
1638                                         int *, int);
1639
1640 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1641                                       struct die_info **, const gdb_byte *,
1642                                       int *);
1643
1644 static void process_die (struct die_info *, struct dwarf2_cu *);
1645
1646 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1647                                              struct obstack *);
1648
1649 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1650
1651 static const char *dwarf2_full_name (const char *name,
1652                                      struct die_info *die,
1653                                      struct dwarf2_cu *cu);
1654
1655 static const char *dwarf2_physname (const char *name, struct die_info *die,
1656                                     struct dwarf2_cu *cu);
1657
1658 static struct die_info *dwarf2_extension (struct die_info *die,
1659                                           struct dwarf2_cu **);
1660
1661 static const char *dwarf_tag_name (unsigned int);
1662
1663 static const char *dwarf_attr_name (unsigned int);
1664
1665 static const char *dwarf_form_name (unsigned int);
1666
1667 static char *dwarf_bool_name (unsigned int);
1668
1669 static const char *dwarf_type_encoding_name (unsigned int);
1670
1671 static struct die_info *sibling_die (struct die_info *);
1672
1673 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1674
1675 static void dump_die_for_error (struct die_info *);
1676
1677 static void dump_die_1 (struct ui_file *, int level, int max_level,
1678                         struct die_info *);
1679
1680 /*static*/ void dump_die (struct die_info *, int max_level);
1681
1682 static void store_in_ref_table (struct die_info *,
1683                                 struct dwarf2_cu *);
1684
1685 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1686
1687 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1688
1689 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1690                                                const struct attribute *,
1691                                                struct dwarf2_cu **);
1692
1693 static struct die_info *follow_die_ref (struct die_info *,
1694                                         const struct attribute *,
1695                                         struct dwarf2_cu **);
1696
1697 static struct die_info *follow_die_sig (struct die_info *,
1698                                         const struct attribute *,
1699                                         struct dwarf2_cu **);
1700
1701 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1702                                          struct dwarf2_cu *);
1703
1704 static struct type *get_DW_AT_signature_type (struct die_info *,
1705                                               const struct attribute *,
1706                                               struct dwarf2_cu *);
1707
1708 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1709
1710 static void read_signatured_type (struct signatured_type *);
1711
1712 static struct type_unit_group *get_type_unit_group
1713     (struct dwarf2_cu *, const struct attribute *);
1714
1715 static void build_type_unit_groups (die_reader_func_ftype *, void *);
1716
1717 /* memory allocation interface */
1718
1719 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1720
1721 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1722
1723 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int,
1724                                  const char *, int);
1725
1726 static int attr_form_is_block (const struct attribute *);
1727
1728 static int attr_form_is_section_offset (const struct attribute *);
1729
1730 static int attr_form_is_constant (const struct attribute *);
1731
1732 static int attr_form_is_ref (const struct attribute *);
1733
1734 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1735                                    struct dwarf2_loclist_baton *baton,
1736                                    const struct attribute *attr);
1737
1738 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1739                                          struct symbol *sym,
1740                                          struct dwarf2_cu *cu,
1741                                          int is_block);
1742
1743 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1744                                      const gdb_byte *info_ptr,
1745                                      struct abbrev_info *abbrev);
1746
1747 static void free_stack_comp_unit (void *);
1748
1749 static hashval_t partial_die_hash (const void *item);
1750
1751 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1752
1753 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1754   (sect_offset offset, unsigned int offset_in_dwz, struct objfile *objfile);
1755
1756 static void init_one_comp_unit (struct dwarf2_cu *cu,
1757                                 struct dwarf2_per_cu_data *per_cu);
1758
1759 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1760                                    struct die_info *comp_unit_die,
1761                                    enum language pretend_language);
1762
1763 static void free_heap_comp_unit (void *);
1764
1765 static void free_cached_comp_units (void *);
1766
1767 static void age_cached_comp_units (void);
1768
1769 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1770
1771 static struct type *set_die_type (struct die_info *, struct type *,
1772                                   struct dwarf2_cu *);
1773
1774 static void create_all_comp_units (struct objfile *);
1775
1776 static int create_all_type_units (struct objfile *);
1777
1778 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1779                                  enum language);
1780
1781 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1782                                     enum language);
1783
1784 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1785                                     enum language);
1786
1787 static void dwarf2_add_dependence (struct dwarf2_cu *,
1788                                    struct dwarf2_per_cu_data *);
1789
1790 static void dwarf2_mark (struct dwarf2_cu *);
1791
1792 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1793
1794 static struct type *get_die_type_at_offset (sect_offset,
1795                                             struct dwarf2_per_cu_data *);
1796
1797 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1798
1799 static void dwarf2_release_queue (void *dummy);
1800
1801 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1802                              enum language pretend_language);
1803
1804 static void process_queue (void);
1805
1806 static void find_file_and_directory (struct die_info *die,
1807                                      struct dwarf2_cu *cu,
1808                                      const char **name, const char **comp_dir);
1809
1810 static char *file_full_name (int file, struct line_header *lh,
1811                              const char *comp_dir);
1812
1813 static const gdb_byte *read_and_check_comp_unit_head
1814   (struct comp_unit_head *header,
1815    struct dwarf2_section_info *section,
1816    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1817    int is_debug_types_section);
1818
1819 static void init_cutu_and_read_dies
1820   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1821    int use_existing_cu, int keep,
1822    die_reader_func_ftype *die_reader_func, void *data);
1823
1824 static void init_cutu_and_read_dies_simple
1825   (struct dwarf2_per_cu_data *this_cu,
1826    die_reader_func_ftype *die_reader_func, void *data);
1827
1828 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1829
1830 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1831
1832 static struct dwo_unit *lookup_dwo_unit_in_dwp
1833   (struct dwp_file *dwp_file, const char *comp_dir,
1834    ULONGEST signature, int is_debug_types);
1835
1836 static struct dwp_file *get_dwp_file (void);
1837
1838 static struct dwo_unit *lookup_dwo_comp_unit
1839   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1840
1841 static struct dwo_unit *lookup_dwo_type_unit
1842   (struct signatured_type *, const char *, const char *);
1843
1844 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1845
1846 static void free_dwo_file_cleanup (void *);
1847
1848 static void process_cu_includes (void);
1849
1850 static void check_producer (struct dwarf2_cu *cu);
1851 \f
1852 /* Various complaints about symbol reading that don't abort the process.  */
1853
1854 static void
1855 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1856 {
1857   complaint (&symfile_complaints,
1858              _("statement list doesn't fit in .debug_line section"));
1859 }
1860
1861 static void
1862 dwarf2_debug_line_missing_file_complaint (void)
1863 {
1864   complaint (&symfile_complaints,
1865              _(".debug_line section has line data without a file"));
1866 }
1867
1868 static void
1869 dwarf2_debug_line_missing_end_sequence_complaint (void)
1870 {
1871   complaint (&symfile_complaints,
1872              _(".debug_line section has line "
1873                "program sequence without an end"));
1874 }
1875
1876 static void
1877 dwarf2_complex_location_expr_complaint (void)
1878 {
1879   complaint (&symfile_complaints, _("location expression too complex"));
1880 }
1881
1882 static void
1883 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
1884                                               int arg3)
1885 {
1886   complaint (&symfile_complaints,
1887              _("const value length mismatch for '%s', got %d, expected %d"),
1888              arg1, arg2, arg3);
1889 }
1890
1891 static void
1892 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
1893 {
1894   complaint (&symfile_complaints,
1895              _("debug info runs off end of %s section"
1896                " [in module %s]"),
1897              get_section_name (section),
1898              get_section_file_name (section));
1899 }
1900
1901 static void
1902 dwarf2_macro_malformed_definition_complaint (const char *arg1)
1903 {
1904   complaint (&symfile_complaints,
1905              _("macro debug info contains a "
1906                "malformed macro definition:\n`%s'"),
1907              arg1);
1908 }
1909
1910 static void
1911 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
1912 {
1913   complaint (&symfile_complaints,
1914              _("invalid attribute class or form for '%s' in '%s'"),
1915              arg1, arg2);
1916 }
1917 \f
1918 #if WORDS_BIGENDIAN
1919
1920 /* Convert VALUE between big- and little-endian.  */
1921 static offset_type
1922 byte_swap (offset_type value)
1923 {
1924   offset_type result;
1925
1926   result = (value & 0xff) << 24;
1927   result |= (value & 0xff00) << 8;
1928   result |= (value & 0xff0000) >> 8;
1929   result |= (value & 0xff000000) >> 24;
1930   return result;
1931 }
1932
1933 #define MAYBE_SWAP(V)  byte_swap (V)
1934
1935 #else
1936 #define MAYBE_SWAP(V) (V)
1937 #endif /* WORDS_BIGENDIAN */
1938
1939 /* The suffix for an index file.  */
1940 #define INDEX_SUFFIX ".gdb-index"
1941
1942 /* Try to locate the sections we need for DWARF 2 debugging
1943    information and return true if we have enough to do something.
1944    NAMES points to the dwarf2 section names, or is NULL if the standard
1945    ELF names are used.  */
1946
1947 int
1948 dwarf2_has_info (struct objfile *objfile,
1949                  const struct dwarf2_debug_sections *names)
1950 {
1951   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
1952   if (!dwarf2_per_objfile)
1953     {
1954       /* Initialize per-objfile state.  */
1955       struct dwarf2_per_objfile *data
1956         = obstack_alloc (&objfile->objfile_obstack, sizeof (*data));
1957
1958       memset (data, 0, sizeof (*data));
1959       set_objfile_data (objfile, dwarf2_objfile_data_key, data);
1960       dwarf2_per_objfile = data;
1961
1962       bfd_map_over_sections (objfile->obfd, dwarf2_locate_sections,
1963                              (void *) names);
1964       dwarf2_per_objfile->objfile = objfile;
1965     }
1966   return (!dwarf2_per_objfile->info.is_virtual
1967           && dwarf2_per_objfile->info.s.asection != NULL
1968           && !dwarf2_per_objfile->abbrev.is_virtual
1969           && dwarf2_per_objfile->abbrev.s.asection != NULL);
1970 }
1971
1972 /* Return the containing section of virtual section SECTION.  */
1973
1974 static struct dwarf2_section_info *
1975 get_containing_section (const struct dwarf2_section_info *section)
1976 {
1977   gdb_assert (section->is_virtual);
1978   return section->s.containing_section;
1979 }
1980
1981 /* Return the bfd owner of SECTION.  */
1982
1983 static struct bfd *
1984 get_section_bfd_owner (const struct dwarf2_section_info *section)
1985 {
1986   if (section->is_virtual)
1987     {
1988       section = get_containing_section (section);
1989       gdb_assert (!section->is_virtual);
1990     }
1991   return section->s.asection->owner;
1992 }
1993
1994 /* Return the bfd section of SECTION.
1995    Returns NULL if the section is not present.  */
1996
1997 static asection *
1998 get_section_bfd_section (const struct dwarf2_section_info *section)
1999 {
2000   if (section->is_virtual)
2001     {
2002       section = get_containing_section (section);
2003       gdb_assert (!section->is_virtual);
2004     }
2005   return section->s.asection;
2006 }
2007
2008 /* Return the name of SECTION.  */
2009
2010 static const char *
2011 get_section_name (const struct dwarf2_section_info *section)
2012 {
2013   asection *sectp = get_section_bfd_section (section);
2014
2015   gdb_assert (sectp != NULL);
2016   return bfd_section_name (get_section_bfd_owner (section), sectp);
2017 }
2018
2019 /* Return the name of the file SECTION is in.  */
2020
2021 static const char *
2022 get_section_file_name (const struct dwarf2_section_info *section)
2023 {
2024   bfd *abfd = get_section_bfd_owner (section);
2025
2026   return bfd_get_filename (abfd);
2027 }
2028
2029 /* Return the id of SECTION.
2030    Returns 0 if SECTION doesn't exist.  */
2031
2032 static int
2033 get_section_id (const struct dwarf2_section_info *section)
2034 {
2035   asection *sectp = get_section_bfd_section (section);
2036
2037   if (sectp == NULL)
2038     return 0;
2039   return sectp->id;
2040 }
2041
2042 /* Return the flags of SECTION.
2043    SECTION (or containing section if this is a virtual section) must exist.  */
2044
2045 static int
2046 get_section_flags (const struct dwarf2_section_info *section)
2047 {
2048   asection *sectp = get_section_bfd_section (section);
2049
2050   gdb_assert (sectp != NULL);
2051   return bfd_get_section_flags (sectp->owner, sectp);
2052 }
2053
2054 /* When loading sections, we look either for uncompressed section or for
2055    compressed section names.  */
2056
2057 static int
2058 section_is_p (const char *section_name,
2059               const struct dwarf2_section_names *names)
2060 {
2061   if (names->normal != NULL
2062       && strcmp (section_name, names->normal) == 0)
2063     return 1;
2064   if (names->compressed != NULL
2065       && strcmp (section_name, names->compressed) == 0)
2066     return 1;
2067   return 0;
2068 }
2069
2070 /* This function is mapped across the sections and remembers the
2071    offset and size of each of the debugging sections we are interested
2072    in.  */
2073
2074 static void
2075 dwarf2_locate_sections (bfd *abfd, asection *sectp, void *vnames)
2076 {
2077   const struct dwarf2_debug_sections *names;
2078   flagword aflag = bfd_get_section_flags (abfd, sectp);
2079
2080   if (vnames == NULL)
2081     names = &dwarf2_elf_names;
2082   else
2083     names = (const struct dwarf2_debug_sections *) vnames;
2084
2085   if ((aflag & SEC_HAS_CONTENTS) == 0)
2086     {
2087     }
2088   else if (section_is_p (sectp->name, &names->info))
2089     {
2090       dwarf2_per_objfile->info.s.asection = sectp;
2091       dwarf2_per_objfile->info.size = bfd_get_section_size (sectp);
2092     }
2093   else if (section_is_p (sectp->name, &names->abbrev))
2094     {
2095       dwarf2_per_objfile->abbrev.s.asection = sectp;
2096       dwarf2_per_objfile->abbrev.size = bfd_get_section_size (sectp);
2097     }
2098   else if (section_is_p (sectp->name, &names->line))
2099     {
2100       dwarf2_per_objfile->line.s.asection = sectp;
2101       dwarf2_per_objfile->line.size = bfd_get_section_size (sectp);
2102     }
2103   else if (section_is_p (sectp->name, &names->loc))
2104     {
2105       dwarf2_per_objfile->loc.s.asection = sectp;
2106       dwarf2_per_objfile->loc.size = bfd_get_section_size (sectp);
2107     }
2108   else if (section_is_p (sectp->name, &names->macinfo))
2109     {
2110       dwarf2_per_objfile->macinfo.s.asection = sectp;
2111       dwarf2_per_objfile->macinfo.size = bfd_get_section_size (sectp);
2112     }
2113   else if (section_is_p (sectp->name, &names->macro))
2114     {
2115       dwarf2_per_objfile->macro.s.asection = sectp;
2116       dwarf2_per_objfile->macro.size = bfd_get_section_size (sectp);
2117     }
2118   else if (section_is_p (sectp->name, &names->str))
2119     {
2120       dwarf2_per_objfile->str.s.asection = sectp;
2121       dwarf2_per_objfile->str.size = bfd_get_section_size (sectp);
2122     }
2123   else if (section_is_p (sectp->name, &names->addr))
2124     {
2125       dwarf2_per_objfile->addr.s.asection = sectp;
2126       dwarf2_per_objfile->addr.size = bfd_get_section_size (sectp);
2127     }
2128   else if (section_is_p (sectp->name, &names->frame))
2129     {
2130       dwarf2_per_objfile->frame.s.asection = sectp;
2131       dwarf2_per_objfile->frame.size = bfd_get_section_size (sectp);
2132     }
2133   else if (section_is_p (sectp->name, &names->eh_frame))
2134     {
2135       dwarf2_per_objfile->eh_frame.s.asection = sectp;
2136       dwarf2_per_objfile->eh_frame.size = bfd_get_section_size (sectp);
2137     }
2138   else if (section_is_p (sectp->name, &names->ranges))
2139     {
2140       dwarf2_per_objfile->ranges.s.asection = sectp;
2141       dwarf2_per_objfile->ranges.size = bfd_get_section_size (sectp);
2142     }
2143   else if (section_is_p (sectp->name, &names->types))
2144     {
2145       struct dwarf2_section_info type_section;
2146
2147       memset (&type_section, 0, sizeof (type_section));
2148       type_section.s.asection = sectp;
2149       type_section.size = bfd_get_section_size (sectp);
2150
2151       VEC_safe_push (dwarf2_section_info_def, dwarf2_per_objfile->types,
2152                      &type_section);
2153     }
2154   else if (section_is_p (sectp->name, &names->gdb_index))
2155     {
2156       dwarf2_per_objfile->gdb_index.s.asection = sectp;
2157       dwarf2_per_objfile->gdb_index.size = bfd_get_section_size (sectp);
2158     }
2159
2160   if ((bfd_get_section_flags (abfd, sectp) & SEC_LOAD)
2161       && bfd_section_vma (abfd, sectp) == 0)
2162     dwarf2_per_objfile->has_section_at_zero = 1;
2163 }
2164
2165 /* A helper function that decides whether a section is empty,
2166    or not present.  */
2167
2168 static int
2169 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2170 {
2171   if (section->is_virtual)
2172     return section->size == 0;
2173   return section->s.asection == NULL || section->size == 0;
2174 }
2175
2176 /* Read the contents of the section INFO.
2177    OBJFILE is the main object file, but not necessarily the file where
2178    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2179    of the DWO file.
2180    If the section is compressed, uncompress it before returning.  */
2181
2182 static void
2183 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2184 {
2185   asection *sectp;
2186   bfd *abfd;
2187   gdb_byte *buf, *retbuf;
2188
2189   if (info->readin)
2190     return;
2191   info->buffer = NULL;
2192   info->readin = 1;
2193
2194   if (dwarf2_section_empty_p (info))
2195     return;
2196
2197   sectp = get_section_bfd_section (info);
2198
2199   /* If this is a virtual section we need to read in the real one first.  */
2200   if (info->is_virtual)
2201     {
2202       struct dwarf2_section_info *containing_section =
2203         get_containing_section (info);
2204
2205       gdb_assert (sectp != NULL);
2206       if ((sectp->flags & SEC_RELOC) != 0)
2207         {
2208           error (_("Dwarf Error: DWP format V2 with relocations is not"
2209                    " supported in section %s [in module %s]"),
2210                  get_section_name (info), get_section_file_name (info));
2211         }
2212       dwarf2_read_section (objfile, containing_section);
2213       /* Other code should have already caught virtual sections that don't
2214          fit.  */
2215       gdb_assert (info->virtual_offset + info->size
2216                   <= containing_section->size);
2217       /* If the real section is empty or there was a problem reading the
2218          section we shouldn't get here.  */
2219       gdb_assert (containing_section->buffer != NULL);
2220       info->buffer = containing_section->buffer + info->virtual_offset;
2221       return;
2222     }
2223
2224   /* If the section has relocations, we must read it ourselves.
2225      Otherwise we attach it to the BFD.  */
2226   if ((sectp->flags & SEC_RELOC) == 0)
2227     {
2228       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2229       return;
2230     }
2231
2232   buf = obstack_alloc (&objfile->objfile_obstack, info->size);
2233   info->buffer = buf;
2234
2235   /* When debugging .o files, we may need to apply relocations; see
2236      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2237      We never compress sections in .o files, so we only need to
2238      try this when the section is not compressed.  */
2239   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2240   if (retbuf != NULL)
2241     {
2242       info->buffer = retbuf;
2243       return;
2244     }
2245
2246   abfd = get_section_bfd_owner (info);
2247   gdb_assert (abfd != NULL);
2248
2249   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2250       || bfd_bread (buf, info->size, abfd) != info->size)
2251     {
2252       error (_("Dwarf Error: Can't read DWARF data"
2253                " in section %s [in module %s]"),
2254              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2255     }
2256 }
2257
2258 /* A helper function that returns the size of a section in a safe way.
2259    If you are positive that the section has been read before using the
2260    size, then it is safe to refer to the dwarf2_section_info object's
2261    "size" field directly.  In other cases, you must call this
2262    function, because for compressed sections the size field is not set
2263    correctly until the section has been read.  */
2264
2265 static bfd_size_type
2266 dwarf2_section_size (struct objfile *objfile,
2267                      struct dwarf2_section_info *info)
2268 {
2269   if (!info->readin)
2270     dwarf2_read_section (objfile, info);
2271   return info->size;
2272 }
2273
2274 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2275    SECTION_NAME.  */
2276
2277 void
2278 dwarf2_get_section_info (struct objfile *objfile,
2279                          enum dwarf2_section_enum sect,
2280                          asection **sectp, const gdb_byte **bufp,
2281                          bfd_size_type *sizep)
2282 {
2283   struct dwarf2_per_objfile *data
2284     = objfile_data (objfile, dwarf2_objfile_data_key);
2285   struct dwarf2_section_info *info;
2286
2287   /* We may see an objfile without any DWARF, in which case we just
2288      return nothing.  */
2289   if (data == NULL)
2290     {
2291       *sectp = NULL;
2292       *bufp = NULL;
2293       *sizep = 0;
2294       return;
2295     }
2296   switch (sect)
2297     {
2298     case DWARF2_DEBUG_FRAME:
2299       info = &data->frame;
2300       break;
2301     case DWARF2_EH_FRAME:
2302       info = &data->eh_frame;
2303       break;
2304     default:
2305       gdb_assert_not_reached ("unexpected section");
2306     }
2307
2308   dwarf2_read_section (objfile, info);
2309
2310   *sectp = get_section_bfd_section (info);
2311   *bufp = info->buffer;
2312   *sizep = info->size;
2313 }
2314
2315 /* A helper function to find the sections for a .dwz file.  */
2316
2317 static void
2318 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2319 {
2320   struct dwz_file *dwz_file = arg;
2321
2322   /* Note that we only support the standard ELF names, because .dwz
2323      is ELF-only (at the time of writing).  */
2324   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2325     {
2326       dwz_file->abbrev.s.asection = sectp;
2327       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2328     }
2329   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2330     {
2331       dwz_file->info.s.asection = sectp;
2332       dwz_file->info.size = bfd_get_section_size (sectp);
2333     }
2334   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2335     {
2336       dwz_file->str.s.asection = sectp;
2337       dwz_file->str.size = bfd_get_section_size (sectp);
2338     }
2339   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2340     {
2341       dwz_file->line.s.asection = sectp;
2342       dwz_file->line.size = bfd_get_section_size (sectp);
2343     }
2344   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2345     {
2346       dwz_file->macro.s.asection = sectp;
2347       dwz_file->macro.size = bfd_get_section_size (sectp);
2348     }
2349   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2350     {
2351       dwz_file->gdb_index.s.asection = sectp;
2352       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2353     }
2354 }
2355
2356 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2357    there is no .gnu_debugaltlink section in the file.  Error if there
2358    is such a section but the file cannot be found.  */
2359
2360 static struct dwz_file *
2361 dwarf2_get_dwz_file (void)
2362 {
2363   bfd *dwz_bfd;
2364   char *data;
2365   struct cleanup *cleanup;
2366   const char *filename;
2367   struct dwz_file *result;
2368   bfd_size_type buildid_len_arg;
2369   size_t buildid_len;
2370   bfd_byte *buildid;
2371
2372   if (dwarf2_per_objfile->dwz_file != NULL)
2373     return dwarf2_per_objfile->dwz_file;
2374
2375   bfd_set_error (bfd_error_no_error);
2376   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2377                                       &buildid_len_arg, &buildid);
2378   if (data == NULL)
2379     {
2380       if (bfd_get_error () == bfd_error_no_error)
2381         return NULL;
2382       error (_("could not read '.gnu_debugaltlink' section: %s"),
2383              bfd_errmsg (bfd_get_error ()));
2384     }
2385   cleanup = make_cleanup (xfree, data);
2386   make_cleanup (xfree, buildid);
2387
2388   buildid_len = (size_t) buildid_len_arg;
2389
2390   filename = (const char *) data;
2391   if (!IS_ABSOLUTE_PATH (filename))
2392     {
2393       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2394       char *rel;
2395
2396       make_cleanup (xfree, abs);
2397       abs = ldirname (abs);
2398       make_cleanup (xfree, abs);
2399
2400       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2401       make_cleanup (xfree, rel);
2402       filename = rel;
2403     }
2404
2405   /* First try the file name given in the section.  If that doesn't
2406      work, try to use the build-id instead.  */
2407   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2408   if (dwz_bfd != NULL)
2409     {
2410       if (!build_id_verify (dwz_bfd, buildid_len, buildid))
2411         {
2412           gdb_bfd_unref (dwz_bfd);
2413           dwz_bfd = NULL;
2414         }
2415     }
2416
2417   if (dwz_bfd == NULL)
2418     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2419
2420   if (dwz_bfd == NULL)
2421     error (_("could not find '.gnu_debugaltlink' file for %s"),
2422            objfile_name (dwarf2_per_objfile->objfile));
2423
2424   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2425                            struct dwz_file);
2426   result->dwz_bfd = dwz_bfd;
2427
2428   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2429
2430   do_cleanups (cleanup);
2431
2432   dwarf2_per_objfile->dwz_file = result;
2433   return result;
2434 }
2435 \f
2436 /* DWARF quick_symbols_functions support.  */
2437
2438 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2439    unique line tables, so we maintain a separate table of all .debug_line
2440    derived entries to support the sharing.
2441    All the quick functions need is the list of file names.  We discard the
2442    line_header when we're done and don't need to record it here.  */
2443 struct quick_file_names
2444 {
2445   /* The data used to construct the hash key.  */
2446   struct stmt_list_hash hash;
2447
2448   /* The number of entries in file_names, real_names.  */
2449   unsigned int num_file_names;
2450
2451   /* The file names from the line table, after being run through
2452      file_full_name.  */
2453   const char **file_names;
2454
2455   /* The file names from the line table after being run through
2456      gdb_realpath.  These are computed lazily.  */
2457   const char **real_names;
2458 };
2459
2460 /* When using the index (and thus not using psymtabs), each CU has an
2461    object of this type.  This is used to hold information needed by
2462    the various "quick" methods.  */
2463 struct dwarf2_per_cu_quick_data
2464 {
2465   /* The file table.  This can be NULL if there was no file table
2466      or it's currently not read in.
2467      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2468   struct quick_file_names *file_names;
2469
2470   /* The corresponding symbol table.  This is NULL if symbols for this
2471      CU have not yet been read.  */
2472   struct symtab *symtab;
2473
2474   /* A temporary mark bit used when iterating over all CUs in
2475      expand_symtabs_matching.  */
2476   unsigned int mark : 1;
2477
2478   /* True if we've tried to read the file table and found there isn't one.
2479      There will be no point in trying to read it again next time.  */
2480   unsigned int no_file_data : 1;
2481 };
2482
2483 /* Utility hash function for a stmt_list_hash.  */
2484
2485 static hashval_t
2486 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2487 {
2488   hashval_t v = 0;
2489
2490   if (stmt_list_hash->dwo_unit != NULL)
2491     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2492   v += stmt_list_hash->line_offset.sect_off;
2493   return v;
2494 }
2495
2496 /* Utility equality function for a stmt_list_hash.  */
2497
2498 static int
2499 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2500                     const struct stmt_list_hash *rhs)
2501 {
2502   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2503     return 0;
2504   if (lhs->dwo_unit != NULL
2505       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2506     return 0;
2507
2508   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2509 }
2510
2511 /* Hash function for a quick_file_names.  */
2512
2513 static hashval_t
2514 hash_file_name_entry (const void *e)
2515 {
2516   const struct quick_file_names *file_data = e;
2517
2518   return hash_stmt_list_entry (&file_data->hash);
2519 }
2520
2521 /* Equality function for a quick_file_names.  */
2522
2523 static int
2524 eq_file_name_entry (const void *a, const void *b)
2525 {
2526   const struct quick_file_names *ea = a;
2527   const struct quick_file_names *eb = b;
2528
2529   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2530 }
2531
2532 /* Delete function for a quick_file_names.  */
2533
2534 static void
2535 delete_file_name_entry (void *e)
2536 {
2537   struct quick_file_names *file_data = e;
2538   int i;
2539
2540   for (i = 0; i < file_data->num_file_names; ++i)
2541     {
2542       xfree ((void*) file_data->file_names[i]);
2543       if (file_data->real_names)
2544         xfree ((void*) file_data->real_names[i]);
2545     }
2546
2547   /* The space for the struct itself lives on objfile_obstack,
2548      so we don't free it here.  */
2549 }
2550
2551 /* Create a quick_file_names hash table.  */
2552
2553 static htab_t
2554 create_quick_file_names_table (unsigned int nr_initial_entries)
2555 {
2556   return htab_create_alloc (nr_initial_entries,
2557                             hash_file_name_entry, eq_file_name_entry,
2558                             delete_file_name_entry, xcalloc, xfree);
2559 }
2560
2561 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2562    have to be created afterwards.  You should call age_cached_comp_units after
2563    processing PER_CU->CU.  dw2_setup must have been already called.  */
2564
2565 static void
2566 load_cu (struct dwarf2_per_cu_data *per_cu)
2567 {
2568   if (per_cu->is_debug_types)
2569     load_full_type_unit (per_cu);
2570   else
2571     load_full_comp_unit (per_cu, language_minimal);
2572
2573   gdb_assert (per_cu->cu != NULL);
2574
2575   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2576 }
2577
2578 /* Read in the symbols for PER_CU.  */
2579
2580 static void
2581 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2582 {
2583   struct cleanup *back_to;
2584
2585   /* Skip type_unit_groups, reading the type units they contain
2586      is handled elsewhere.  */
2587   if (IS_TYPE_UNIT_GROUP (per_cu))
2588     return;
2589
2590   back_to = make_cleanup (dwarf2_release_queue, NULL);
2591
2592   if (dwarf2_per_objfile->using_index
2593       ? per_cu->v.quick->symtab == NULL
2594       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2595     {
2596       queue_comp_unit (per_cu, language_minimal);
2597       load_cu (per_cu);
2598
2599       /* If we just loaded a CU from a DWO, and we're working with an index
2600          that may badly handle TUs, load all the TUs in that DWO as well.
2601          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2602       if (!per_cu->is_debug_types
2603           && per_cu->cu->dwo_unit != NULL
2604           && dwarf2_per_objfile->index_table != NULL
2605           && dwarf2_per_objfile->index_table->version <= 7
2606           /* DWP files aren't supported yet.  */
2607           && get_dwp_file () == NULL)
2608         queue_and_load_all_dwo_tus (per_cu);
2609     }
2610
2611   process_queue ();
2612
2613   /* Age the cache, releasing compilation units that have not
2614      been used recently.  */
2615   age_cached_comp_units ();
2616
2617   do_cleanups (back_to);
2618 }
2619
2620 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2621    the objfile from which this CU came.  Returns the resulting symbol
2622    table.  */
2623
2624 static struct symtab *
2625 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2626 {
2627   gdb_assert (dwarf2_per_objfile->using_index);
2628   if (!per_cu->v.quick->symtab)
2629     {
2630       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2631       increment_reading_symtab ();
2632       dw2_do_instantiate_symtab (per_cu);
2633       process_cu_includes ();
2634       do_cleanups (back_to);
2635     }
2636   return per_cu->v.quick->symtab;
2637 }
2638
2639 /* Return the CU given its index.
2640
2641    This is intended for loops like:
2642
2643    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2644                     + dwarf2_per_objfile->n_type_units); ++i)
2645      {
2646        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2647
2648        ...;
2649      }
2650 */
2651
2652 static struct dwarf2_per_cu_data *
2653 dw2_get_cu (int index)
2654 {
2655   if (index >= dwarf2_per_objfile->n_comp_units)
2656     {
2657       index -= dwarf2_per_objfile->n_comp_units;
2658       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2659       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2660     }
2661
2662   return dwarf2_per_objfile->all_comp_units[index];
2663 }
2664
2665 /* Return the primary CU given its index.
2666    The difference between this function and dw2_get_cu is in the handling
2667    of type units (TUs).  Here we return the type_unit_group object.
2668
2669    This is intended for loops like:
2670
2671    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2672                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2673      {
2674        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2675
2676        ...;
2677      }
2678 */
2679
2680 static struct dwarf2_per_cu_data *
2681 dw2_get_primary_cu (int index)
2682 {
2683   if (index >= dwarf2_per_objfile->n_comp_units)
2684     {
2685       index -= dwarf2_per_objfile->n_comp_units;
2686       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2687       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2688     }
2689
2690   return dwarf2_per_objfile->all_comp_units[index];
2691 }
2692
2693 /* A helper for create_cus_from_index that handles a given list of
2694    CUs.  */
2695
2696 static void
2697 create_cus_from_index_list (struct objfile *objfile,
2698                             const gdb_byte *cu_list, offset_type n_elements,
2699                             struct dwarf2_section_info *section,
2700                             int is_dwz,
2701                             int base_offset)
2702 {
2703   offset_type i;
2704
2705   for (i = 0; i < n_elements; i += 2)
2706     {
2707       struct dwarf2_per_cu_data *the_cu;
2708       ULONGEST offset, length;
2709
2710       gdb_static_assert (sizeof (ULONGEST) >= 8);
2711       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2712       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2713       cu_list += 2 * 8;
2714
2715       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2716                                struct dwarf2_per_cu_data);
2717       the_cu->offset.sect_off = offset;
2718       the_cu->length = length;
2719       the_cu->objfile = objfile;
2720       the_cu->section = section;
2721       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2722                                         struct dwarf2_per_cu_quick_data);
2723       the_cu->is_dwz = is_dwz;
2724       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2725     }
2726 }
2727
2728 /* Read the CU list from the mapped index, and use it to create all
2729    the CU objects for this objfile.  */
2730
2731 static void
2732 create_cus_from_index (struct objfile *objfile,
2733                        const gdb_byte *cu_list, offset_type cu_list_elements,
2734                        const gdb_byte *dwz_list, offset_type dwz_elements)
2735 {
2736   struct dwz_file *dwz;
2737
2738   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2739   dwarf2_per_objfile->all_comp_units
2740     = obstack_alloc (&objfile->objfile_obstack,
2741                      dwarf2_per_objfile->n_comp_units
2742                      * sizeof (struct dwarf2_per_cu_data *));
2743
2744   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2745                               &dwarf2_per_objfile->info, 0, 0);
2746
2747   if (dwz_elements == 0)
2748     return;
2749
2750   dwz = dwarf2_get_dwz_file ();
2751   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2752                               cu_list_elements / 2);
2753 }
2754
2755 /* Create the signatured type hash table from the index.  */
2756
2757 static void
2758 create_signatured_type_table_from_index (struct objfile *objfile,
2759                                          struct dwarf2_section_info *section,
2760                                          const gdb_byte *bytes,
2761                                          offset_type elements)
2762 {
2763   offset_type i;
2764   htab_t sig_types_hash;
2765
2766   dwarf2_per_objfile->n_type_units = elements / 3;
2767   dwarf2_per_objfile->all_type_units
2768     = xmalloc (dwarf2_per_objfile->n_type_units
2769                * sizeof (struct signatured_type *));
2770
2771   sig_types_hash = allocate_signatured_type_table (objfile);
2772
2773   for (i = 0; i < elements; i += 3)
2774     {
2775       struct signatured_type *sig_type;
2776       ULONGEST offset, type_offset_in_tu, signature;
2777       void **slot;
2778
2779       gdb_static_assert (sizeof (ULONGEST) >= 8);
2780       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2781       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2782                                                     BFD_ENDIAN_LITTLE);
2783       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2784       bytes += 3 * 8;
2785
2786       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2787                                  struct signatured_type);
2788       sig_type->signature = signature;
2789       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2790       sig_type->per_cu.is_debug_types = 1;
2791       sig_type->per_cu.section = section;
2792       sig_type->per_cu.offset.sect_off = offset;
2793       sig_type->per_cu.objfile = objfile;
2794       sig_type->per_cu.v.quick
2795         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2796                           struct dwarf2_per_cu_quick_data);
2797
2798       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2799       *slot = sig_type;
2800
2801       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2802     }
2803
2804   dwarf2_per_objfile->signatured_types = sig_types_hash;
2805 }
2806
2807 /* Read the address map data from the mapped index, and use it to
2808    populate the objfile's psymtabs_addrmap.  */
2809
2810 static void
2811 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2812 {
2813   const gdb_byte *iter, *end;
2814   struct obstack temp_obstack;
2815   struct addrmap *mutable_map;
2816   struct cleanup *cleanup;
2817   CORE_ADDR baseaddr;
2818
2819   obstack_init (&temp_obstack);
2820   cleanup = make_cleanup_obstack_free (&temp_obstack);
2821   mutable_map = addrmap_create_mutable (&temp_obstack);
2822
2823   iter = index->address_table;
2824   end = iter + index->address_table_size;
2825
2826   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2827
2828   while (iter < end)
2829     {
2830       ULONGEST hi, lo, cu_index;
2831       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2832       iter += 8;
2833       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2834       iter += 8;
2835       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2836       iter += 4;
2837
2838       if (lo > hi)
2839         {
2840           complaint (&symfile_complaints,
2841                      _(".gdb_index address table has invalid range (%s - %s)"),
2842                      hex_string (lo), hex_string (hi));
2843           continue;
2844         }
2845
2846       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2847         {
2848           complaint (&symfile_complaints,
2849                      _(".gdb_index address table has invalid CU number %u"),
2850                      (unsigned) cu_index);
2851           continue;
2852         }
2853
2854       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2855                          dw2_get_cu (cu_index));
2856     }
2857
2858   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2859                                                     &objfile->objfile_obstack);
2860   do_cleanups (cleanup);
2861 }
2862
2863 /* The hash function for strings in the mapped index.  This is the same as
2864    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2865    implementation.  This is necessary because the hash function is tied to the
2866    format of the mapped index file.  The hash values do not have to match with
2867    SYMBOL_HASH_NEXT.
2868    
2869    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2870
2871 static hashval_t
2872 mapped_index_string_hash (int index_version, const void *p)
2873 {
2874   const unsigned char *str = (const unsigned char *) p;
2875   hashval_t r = 0;
2876   unsigned char c;
2877
2878   while ((c = *str++) != 0)
2879     {
2880       if (index_version >= 5)
2881         c = tolower (c);
2882       r = r * 67 + c - 113;
2883     }
2884
2885   return r;
2886 }
2887
2888 /* Find a slot in the mapped index INDEX for the object named NAME.
2889    If NAME is found, set *VEC_OUT to point to the CU vector in the
2890    constant pool and return 1.  If NAME cannot be found, return 0.  */
2891
2892 static int
2893 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2894                           offset_type **vec_out)
2895 {
2896   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2897   offset_type hash;
2898   offset_type slot, step;
2899   int (*cmp) (const char *, const char *);
2900
2901   if (current_language->la_language == language_cplus
2902       || current_language->la_language == language_java
2903       || current_language->la_language == language_fortran)
2904     {
2905       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2906          not contain any.  */
2907       const char *paren = strchr (name, '(');
2908
2909       if (paren)
2910         {
2911           char *dup;
2912
2913           dup = xmalloc (paren - name + 1);
2914           memcpy (dup, name, paren - name);
2915           dup[paren - name] = 0;
2916
2917           make_cleanup (xfree, dup);
2918           name = dup;
2919         }
2920     }
2921
2922   /* Index version 4 did not support case insensitive searches.  But the
2923      indices for case insensitive languages are built in lowercase, therefore
2924      simulate our NAME being searched is also lowercased.  */
2925   hash = mapped_index_string_hash ((index->version == 4
2926                                     && case_sensitivity == case_sensitive_off
2927                                     ? 5 : index->version),
2928                                    name);
2929
2930   slot = hash & (index->symbol_table_slots - 1);
2931   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2932   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2933
2934   for (;;)
2935     {
2936       /* Convert a slot number to an offset into the table.  */
2937       offset_type i = 2 * slot;
2938       const char *str;
2939       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2940         {
2941           do_cleanups (back_to);
2942           return 0;
2943         }
2944
2945       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2946       if (!cmp (name, str))
2947         {
2948           *vec_out = (offset_type *) (index->constant_pool
2949                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2950           do_cleanups (back_to);
2951           return 1;
2952         }
2953
2954       slot = (slot + step) & (index->symbol_table_slots - 1);
2955     }
2956 }
2957
2958 /* A helper function that reads the .gdb_index from SECTION and fills
2959    in MAP.  FILENAME is the name of the file containing the section;
2960    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2961    ok to use deprecated sections.
2962
2963    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2964    out parameters that are filled in with information about the CU and
2965    TU lists in the section.
2966
2967    Returns 1 if all went well, 0 otherwise.  */
2968
2969 static int
2970 read_index_from_section (struct objfile *objfile,
2971                          const char *filename,
2972                          int deprecated_ok,
2973                          struct dwarf2_section_info *section,
2974                          struct mapped_index *map,
2975                          const gdb_byte **cu_list,
2976                          offset_type *cu_list_elements,
2977                          const gdb_byte **types_list,
2978                          offset_type *types_list_elements)
2979 {
2980   const gdb_byte *addr;
2981   offset_type version;
2982   offset_type *metadata;
2983   int i;
2984
2985   if (dwarf2_section_empty_p (section))
2986     return 0;
2987
2988   /* Older elfutils strip versions could keep the section in the main
2989      executable while splitting it for the separate debug info file.  */
2990   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
2991     return 0;
2992
2993   dwarf2_read_section (objfile, section);
2994
2995   addr = section->buffer;
2996   /* Version check.  */
2997   version = MAYBE_SWAP (*(offset_type *) addr);
2998   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2999      causes the index to behave very poorly for certain requests.  Version 3
3000      contained incomplete addrmap.  So, it seems better to just ignore such
3001      indices.  */
3002   if (version < 4)
3003     {
3004       static int warning_printed = 0;
3005       if (!warning_printed)
3006         {
3007           warning (_("Skipping obsolete .gdb_index section in %s."),
3008                    filename);
3009           warning_printed = 1;
3010         }
3011       return 0;
3012     }
3013   /* Index version 4 uses a different hash function than index version
3014      5 and later.
3015
3016      Versions earlier than 6 did not emit psymbols for inlined
3017      functions.  Using these files will cause GDB not to be able to
3018      set breakpoints on inlined functions by name, so we ignore these
3019      indices unless the user has done
3020      "set use-deprecated-index-sections on".  */
3021   if (version < 6 && !deprecated_ok)
3022     {
3023       static int warning_printed = 0;
3024       if (!warning_printed)
3025         {
3026           warning (_("\
3027 Skipping deprecated .gdb_index section in %s.\n\
3028 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3029 to use the section anyway."),
3030                    filename);
3031           warning_printed = 1;
3032         }
3033       return 0;
3034     }
3035   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3036      of the TU (for symbols coming from TUs).  It's just a performance bug, and
3037      we can't distinguish gdb-generated indices from gold-generated ones, so
3038      nothing to do here.  */
3039
3040   /* Indexes with higher version than the one supported by GDB may be no
3041      longer backward compatible.  */
3042   if (version > 8)
3043     return 0;
3044
3045   map->version = version;
3046   map->total_size = section->size;
3047
3048   metadata = (offset_type *) (addr + sizeof (offset_type));
3049
3050   i = 0;
3051   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3052   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3053                        / 8);
3054   ++i;
3055
3056   *types_list = addr + MAYBE_SWAP (metadata[i]);
3057   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3058                            - MAYBE_SWAP (metadata[i]))
3059                           / 8);
3060   ++i;
3061
3062   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3063   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3064                              - MAYBE_SWAP (metadata[i]));
3065   ++i;
3066
3067   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3068   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3069                               - MAYBE_SWAP (metadata[i]))
3070                              / (2 * sizeof (offset_type)));
3071   ++i;
3072
3073   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3074
3075   return 1;
3076 }
3077
3078
3079 /* Read the index file.  If everything went ok, initialize the "quick"
3080    elements of all the CUs and return 1.  Otherwise, return 0.  */
3081
3082 static int
3083 dwarf2_read_index (struct objfile *objfile)
3084 {
3085   struct mapped_index local_map, *map;
3086   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3087   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3088   struct dwz_file *dwz;
3089
3090   if (!read_index_from_section (objfile, objfile_name (objfile),
3091                                 use_deprecated_index_sections,
3092                                 &dwarf2_per_objfile->gdb_index, &local_map,
3093                                 &cu_list, &cu_list_elements,
3094                                 &types_list, &types_list_elements))
3095     return 0;
3096
3097   /* Don't use the index if it's empty.  */
3098   if (local_map.symbol_table_slots == 0)
3099     return 0;
3100
3101   /* If there is a .dwz file, read it so we can get its CU list as
3102      well.  */
3103   dwz = dwarf2_get_dwz_file ();
3104   if (dwz != NULL)
3105     {
3106       struct mapped_index dwz_map;
3107       const gdb_byte *dwz_types_ignore;
3108       offset_type dwz_types_elements_ignore;
3109
3110       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3111                                     1,
3112                                     &dwz->gdb_index, &dwz_map,
3113                                     &dwz_list, &dwz_list_elements,
3114                                     &dwz_types_ignore,
3115                                     &dwz_types_elements_ignore))
3116         {
3117           warning (_("could not read '.gdb_index' section from %s; skipping"),
3118                    bfd_get_filename (dwz->dwz_bfd));
3119           return 0;
3120         }
3121     }
3122
3123   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3124                          dwz_list_elements);
3125
3126   if (types_list_elements)
3127     {
3128       struct dwarf2_section_info *section;
3129
3130       /* We can only handle a single .debug_types when we have an
3131          index.  */
3132       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3133         return 0;
3134
3135       section = VEC_index (dwarf2_section_info_def,
3136                            dwarf2_per_objfile->types, 0);
3137
3138       create_signatured_type_table_from_index (objfile, section, types_list,
3139                                                types_list_elements);
3140     }
3141
3142   create_addrmap_from_index (objfile, &local_map);
3143
3144   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
3145   *map = local_map;
3146
3147   dwarf2_per_objfile->index_table = map;
3148   dwarf2_per_objfile->using_index = 1;
3149   dwarf2_per_objfile->quick_file_names_table =
3150     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3151
3152   return 1;
3153 }
3154
3155 /* A helper for the "quick" functions which sets the global
3156    dwarf2_per_objfile according to OBJFILE.  */
3157
3158 static void
3159 dw2_setup (struct objfile *objfile)
3160 {
3161   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
3162   gdb_assert (dwarf2_per_objfile);
3163 }
3164
3165 /* die_reader_func for dw2_get_file_names.  */
3166
3167 static void
3168 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3169                            const gdb_byte *info_ptr,
3170                            struct die_info *comp_unit_die,
3171                            int has_children,
3172                            void *data)
3173 {
3174   struct dwarf2_cu *cu = reader->cu;
3175   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3176   struct objfile *objfile = dwarf2_per_objfile->objfile;
3177   struct dwarf2_per_cu_data *lh_cu;
3178   struct line_header *lh;
3179   struct attribute *attr;
3180   int i;
3181   const char *name, *comp_dir;
3182   void **slot;
3183   struct quick_file_names *qfn;
3184   unsigned int line_offset;
3185
3186   gdb_assert (! this_cu->is_debug_types);
3187
3188   /* Our callers never want to match partial units -- instead they
3189      will match the enclosing full CU.  */
3190   if (comp_unit_die->tag == DW_TAG_partial_unit)
3191     {
3192       this_cu->v.quick->no_file_data = 1;
3193       return;
3194     }
3195
3196   lh_cu = this_cu;
3197   lh = NULL;
3198   slot = NULL;
3199   line_offset = 0;
3200
3201   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3202   if (attr)
3203     {
3204       struct quick_file_names find_entry;
3205
3206       line_offset = DW_UNSND (attr);
3207
3208       /* We may have already read in this line header (TU line header sharing).
3209          If we have we're done.  */
3210       find_entry.hash.dwo_unit = cu->dwo_unit;
3211       find_entry.hash.line_offset.sect_off = line_offset;
3212       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3213                              &find_entry, INSERT);
3214       if (*slot != NULL)
3215         {
3216           lh_cu->v.quick->file_names = *slot;
3217           return;
3218         }
3219
3220       lh = dwarf_decode_line_header (line_offset, cu);
3221     }
3222   if (lh == NULL)
3223     {
3224       lh_cu->v.quick->no_file_data = 1;
3225       return;
3226     }
3227
3228   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
3229   qfn->hash.dwo_unit = cu->dwo_unit;
3230   qfn->hash.line_offset.sect_off = line_offset;
3231   gdb_assert (slot != NULL);
3232   *slot = qfn;
3233
3234   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
3235
3236   qfn->num_file_names = lh->num_file_names;
3237   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
3238                                    lh->num_file_names * sizeof (char *));
3239   for (i = 0; i < lh->num_file_names; ++i)
3240     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
3241   qfn->real_names = NULL;
3242
3243   free_line_header (lh);
3244
3245   lh_cu->v.quick->file_names = qfn;
3246 }
3247
3248 /* A helper for the "quick" functions which attempts to read the line
3249    table for THIS_CU.  */
3250
3251 static struct quick_file_names *
3252 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3253 {
3254   /* This should never be called for TUs.  */
3255   gdb_assert (! this_cu->is_debug_types);
3256   /* Nor type unit groups.  */
3257   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3258
3259   if (this_cu->v.quick->file_names != NULL)
3260     return this_cu->v.quick->file_names;
3261   /* If we know there is no line data, no point in looking again.  */
3262   if (this_cu->v.quick->no_file_data)
3263     return NULL;
3264
3265   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3266
3267   if (this_cu->v.quick->no_file_data)
3268     return NULL;
3269   return this_cu->v.quick->file_names;
3270 }
3271
3272 /* A helper for the "quick" functions which computes and caches the
3273    real path for a given file name from the line table.  */
3274
3275 static const char *
3276 dw2_get_real_path (struct objfile *objfile,
3277                    struct quick_file_names *qfn, int index)
3278 {
3279   if (qfn->real_names == NULL)
3280     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3281                                       qfn->num_file_names, sizeof (char *));
3282
3283   if (qfn->real_names[index] == NULL)
3284     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3285
3286   return qfn->real_names[index];
3287 }
3288
3289 static struct symtab *
3290 dw2_find_last_source_symtab (struct objfile *objfile)
3291 {
3292   int index;
3293
3294   dw2_setup (objfile);
3295   index = dwarf2_per_objfile->n_comp_units - 1;
3296   return dw2_instantiate_symtab (dw2_get_cu (index));
3297 }
3298
3299 /* Traversal function for dw2_forget_cached_source_info.  */
3300
3301 static int
3302 dw2_free_cached_file_names (void **slot, void *info)
3303 {
3304   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3305
3306   if (file_data->real_names)
3307     {
3308       int i;
3309
3310       for (i = 0; i < file_data->num_file_names; ++i)
3311         {
3312           xfree ((void*) file_data->real_names[i]);
3313           file_data->real_names[i] = NULL;
3314         }
3315     }
3316
3317   return 1;
3318 }
3319
3320 static void
3321 dw2_forget_cached_source_info (struct objfile *objfile)
3322 {
3323   dw2_setup (objfile);
3324
3325   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3326                           dw2_free_cached_file_names, NULL);
3327 }
3328
3329 /* Helper function for dw2_map_symtabs_matching_filename that expands
3330    the symtabs and calls the iterator.  */
3331
3332 static int
3333 dw2_map_expand_apply (struct objfile *objfile,
3334                       struct dwarf2_per_cu_data *per_cu,
3335                       const char *name, const char *real_path,
3336                       int (*callback) (struct symtab *, void *),
3337                       void *data)
3338 {
3339   struct symtab *last_made = objfile->symtabs;
3340
3341   /* Don't visit already-expanded CUs.  */
3342   if (per_cu->v.quick->symtab)
3343     return 0;
3344
3345   /* This may expand more than one symtab, and we want to iterate over
3346      all of them.  */
3347   dw2_instantiate_symtab (per_cu);
3348
3349   return iterate_over_some_symtabs (name, real_path, callback, data,
3350                                     objfile->symtabs, last_made);
3351 }
3352
3353 /* Implementation of the map_symtabs_matching_filename method.  */
3354
3355 static int
3356 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3357                                    const char *real_path,
3358                                    int (*callback) (struct symtab *, void *),
3359                                    void *data)
3360 {
3361   int i;
3362   const char *name_basename = lbasename (name);
3363
3364   dw2_setup (objfile);
3365
3366   /* The rule is CUs specify all the files, including those used by
3367      any TU, so there's no need to scan TUs here.  */
3368
3369   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3370     {
3371       int j;
3372       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3373       struct quick_file_names *file_data;
3374
3375       /* We only need to look at symtabs not already expanded.  */
3376       if (per_cu->v.quick->symtab)
3377         continue;
3378
3379       file_data = dw2_get_file_names (per_cu);
3380       if (file_data == NULL)
3381         continue;
3382
3383       for (j = 0; j < file_data->num_file_names; ++j)
3384         {
3385           const char *this_name = file_data->file_names[j];
3386           const char *this_real_name;
3387
3388           if (compare_filenames_for_search (this_name, name))
3389             {
3390               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3391                                         callback, data))
3392                 return 1;
3393               continue;
3394             }
3395
3396           /* Before we invoke realpath, which can get expensive when many
3397              files are involved, do a quick comparison of the basenames.  */
3398           if (! basenames_may_differ
3399               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3400             continue;
3401
3402           this_real_name = dw2_get_real_path (objfile, file_data, j);
3403           if (compare_filenames_for_search (this_real_name, name))
3404             {
3405               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3406                                         callback, data))
3407                 return 1;
3408               continue;
3409             }
3410
3411           if (real_path != NULL)
3412             {
3413               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3414               gdb_assert (IS_ABSOLUTE_PATH (name));
3415               if (this_real_name != NULL
3416                   && FILENAME_CMP (real_path, this_real_name) == 0)
3417                 {
3418                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3419                                             callback, data))
3420                     return 1;
3421                   continue;
3422                 }
3423             }
3424         }
3425     }
3426
3427   return 0;
3428 }
3429
3430 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3431
3432 struct dw2_symtab_iterator
3433 {
3434   /* The internalized form of .gdb_index.  */
3435   struct mapped_index *index;
3436   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3437   int want_specific_block;
3438   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3439      Unused if !WANT_SPECIFIC_BLOCK.  */
3440   int block_index;
3441   /* The kind of symbol we're looking for.  */
3442   domain_enum domain;
3443   /* The list of CUs from the index entry of the symbol,
3444      or NULL if not found.  */
3445   offset_type *vec;
3446   /* The next element in VEC to look at.  */
3447   int next;
3448   /* The number of elements in VEC, or zero if there is no match.  */
3449   int length;
3450 };
3451
3452 /* Initialize the index symtab iterator ITER.
3453    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3454    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3455
3456 static void
3457 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3458                       struct mapped_index *index,
3459                       int want_specific_block,
3460                       int block_index,
3461                       domain_enum domain,
3462                       const char *name)
3463 {
3464   iter->index = index;
3465   iter->want_specific_block = want_specific_block;
3466   iter->block_index = block_index;
3467   iter->domain = domain;
3468   iter->next = 0;
3469
3470   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3471     iter->length = MAYBE_SWAP (*iter->vec);
3472   else
3473     {
3474       iter->vec = NULL;
3475       iter->length = 0;
3476     }
3477 }
3478
3479 /* Return the next matching CU or NULL if there are no more.  */
3480
3481 static struct dwarf2_per_cu_data *
3482 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3483 {
3484   for ( ; iter->next < iter->length; ++iter->next)
3485     {
3486       offset_type cu_index_and_attrs =
3487         MAYBE_SWAP (iter->vec[iter->next + 1]);
3488       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3489       struct dwarf2_per_cu_data *per_cu;
3490       int want_static = iter->block_index != GLOBAL_BLOCK;
3491       /* This value is only valid for index versions >= 7.  */
3492       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3493       gdb_index_symbol_kind symbol_kind =
3494         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3495       /* Only check the symbol attributes if they're present.
3496          Indices prior to version 7 don't record them,
3497          and indices >= 7 may elide them for certain symbols
3498          (gold does this).  */
3499       int attrs_valid =
3500         (iter->index->version >= 7
3501          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3502
3503       /* Don't crash on bad data.  */
3504       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3505                        + dwarf2_per_objfile->n_type_units))
3506         {
3507           complaint (&symfile_complaints,
3508                      _(".gdb_index entry has bad CU index"
3509                        " [in module %s]"),
3510                      objfile_name (dwarf2_per_objfile->objfile));
3511           continue;
3512         }
3513
3514       per_cu = dw2_get_cu (cu_index);
3515
3516       /* Skip if already read in.  */
3517       if (per_cu->v.quick->symtab)
3518         continue;
3519
3520       if (attrs_valid
3521           && iter->want_specific_block
3522           && want_static != is_static)
3523         continue;
3524
3525       /* Only check the symbol's kind if it has one.  */
3526       if (attrs_valid)
3527         {
3528           switch (iter->domain)
3529             {
3530             case VAR_DOMAIN:
3531               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3532                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3533                   /* Some types are also in VAR_DOMAIN.  */
3534                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3535                 continue;
3536               break;
3537             case STRUCT_DOMAIN:
3538               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3539                 continue;
3540               break;
3541             case LABEL_DOMAIN:
3542               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3543                 continue;
3544               break;
3545             default:
3546               break;
3547             }
3548         }
3549
3550       ++iter->next;
3551       return per_cu;
3552     }
3553
3554   return NULL;
3555 }
3556
3557 static struct symtab *
3558 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3559                    const char *name, domain_enum domain)
3560 {
3561   struct symtab *stab_best = NULL;
3562   struct mapped_index *index;
3563
3564   dw2_setup (objfile);
3565
3566   index = dwarf2_per_objfile->index_table;
3567
3568   /* index is NULL if OBJF_READNOW.  */
3569   if (index)
3570     {
3571       struct dw2_symtab_iterator iter;
3572       struct dwarf2_per_cu_data *per_cu;
3573
3574       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3575
3576       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3577         {
3578           struct symbol *sym = NULL;
3579           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3580
3581           /* Some caution must be observed with overloaded functions
3582              and methods, since the index will not contain any overload
3583              information (but NAME might contain it).  */
3584           if (stab->primary)
3585             {
3586               struct blockvector *bv = BLOCKVECTOR (stab);
3587               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3588
3589               sym = lookup_block_symbol (block, name, domain);
3590             }
3591
3592           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3593             {
3594               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3595                 return stab;
3596
3597               stab_best = stab;
3598             }
3599
3600           /* Keep looking through other CUs.  */
3601         }
3602     }
3603
3604   return stab_best;
3605 }
3606
3607 static void
3608 dw2_print_stats (struct objfile *objfile)
3609 {
3610   int i, total, count;
3611
3612   dw2_setup (objfile);
3613   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3614   count = 0;
3615   for (i = 0; i < total; ++i)
3616     {
3617       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3618
3619       if (!per_cu->v.quick->symtab)
3620         ++count;
3621     }
3622   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3623   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3624 }
3625
3626 /* This dumps minimal information about the index.
3627    It is called via "mt print objfiles".
3628    One use is to verify .gdb_index has been loaded by the
3629    gdb.dwarf2/gdb-index.exp testcase.  */
3630
3631 static void
3632 dw2_dump (struct objfile *objfile)
3633 {
3634   dw2_setup (objfile);
3635   gdb_assert (dwarf2_per_objfile->using_index);
3636   printf_filtered (".gdb_index:");
3637   if (dwarf2_per_objfile->index_table != NULL)
3638     {
3639       printf_filtered (" version %d\n",
3640                        dwarf2_per_objfile->index_table->version);
3641     }
3642   else
3643     printf_filtered (" faked for \"readnow\"\n");
3644   printf_filtered ("\n");
3645 }
3646
3647 static void
3648 dw2_relocate (struct objfile *objfile,
3649               const struct section_offsets *new_offsets,
3650               const struct section_offsets *delta)
3651 {
3652   /* There's nothing to relocate here.  */
3653 }
3654
3655 static void
3656 dw2_expand_symtabs_for_function (struct objfile *objfile,
3657                                  const char *func_name)
3658 {
3659   struct mapped_index *index;
3660
3661   dw2_setup (objfile);
3662
3663   index = dwarf2_per_objfile->index_table;
3664
3665   /* index is NULL if OBJF_READNOW.  */
3666   if (index)
3667     {
3668       struct dw2_symtab_iterator iter;
3669       struct dwarf2_per_cu_data *per_cu;
3670
3671       /* Note: It doesn't matter what we pass for block_index here.  */
3672       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3673                             func_name);
3674
3675       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3676         dw2_instantiate_symtab (per_cu);
3677     }
3678 }
3679
3680 static void
3681 dw2_expand_all_symtabs (struct objfile *objfile)
3682 {
3683   int i;
3684
3685   dw2_setup (objfile);
3686
3687   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3688                    + dwarf2_per_objfile->n_type_units); ++i)
3689     {
3690       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3691
3692       dw2_instantiate_symtab (per_cu);
3693     }
3694 }
3695
3696 static void
3697 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3698                                   const char *fullname)
3699 {
3700   int i;
3701
3702   dw2_setup (objfile);
3703
3704   /* We don't need to consider type units here.
3705      This is only called for examining code, e.g. expand_line_sal.
3706      There can be an order of magnitude (or more) more type units
3707      than comp units, and we avoid them if we can.  */
3708
3709   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3710     {
3711       int j;
3712       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3713       struct quick_file_names *file_data;
3714
3715       /* We only need to look at symtabs not already expanded.  */
3716       if (per_cu->v.quick->symtab)
3717         continue;
3718
3719       file_data = dw2_get_file_names (per_cu);
3720       if (file_data == NULL)
3721         continue;
3722
3723       for (j = 0; j < file_data->num_file_names; ++j)
3724         {
3725           const char *this_fullname = file_data->file_names[j];
3726
3727           if (filename_cmp (this_fullname, fullname) == 0)
3728             {
3729               dw2_instantiate_symtab (per_cu);
3730               break;
3731             }
3732         }
3733     }
3734 }
3735
3736 static void
3737 dw2_map_matching_symbols (struct objfile *objfile,
3738                           const char * name, domain_enum namespace,
3739                           int global,
3740                           int (*callback) (struct block *,
3741                                            struct symbol *, void *),
3742                           void *data, symbol_compare_ftype *match,
3743                           symbol_compare_ftype *ordered_compare)
3744 {
3745   /* Currently unimplemented; used for Ada.  The function can be called if the
3746      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3747      does not look for non-Ada symbols this function should just return.  */
3748 }
3749
3750 static void
3751 dw2_expand_symtabs_matching
3752   (struct objfile *objfile,
3753    int (*file_matcher) (const char *, void *, int basenames),
3754    int (*name_matcher) (const char *, void *),
3755    enum search_domain kind,
3756    void *data)
3757 {
3758   int i;
3759   offset_type iter;
3760   struct mapped_index *index;
3761
3762   dw2_setup (objfile);
3763
3764   /* index_table is NULL if OBJF_READNOW.  */
3765   if (!dwarf2_per_objfile->index_table)
3766     return;
3767   index = dwarf2_per_objfile->index_table;
3768
3769   if (file_matcher != NULL)
3770     {
3771       struct cleanup *cleanup;
3772       htab_t visited_found, visited_not_found;
3773
3774       visited_found = htab_create_alloc (10,
3775                                          htab_hash_pointer, htab_eq_pointer,
3776                                          NULL, xcalloc, xfree);
3777       cleanup = make_cleanup_htab_delete (visited_found);
3778       visited_not_found = htab_create_alloc (10,
3779                                              htab_hash_pointer, htab_eq_pointer,
3780                                              NULL, xcalloc, xfree);
3781       make_cleanup_htab_delete (visited_not_found);
3782
3783       /* The rule is CUs specify all the files, including those used by
3784          any TU, so there's no need to scan TUs here.  */
3785
3786       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3787         {
3788           int j;
3789           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3790           struct quick_file_names *file_data;
3791           void **slot;
3792
3793           per_cu->v.quick->mark = 0;
3794
3795           /* We only need to look at symtabs not already expanded.  */
3796           if (per_cu->v.quick->symtab)
3797             continue;
3798
3799           file_data = dw2_get_file_names (per_cu);
3800           if (file_data == NULL)
3801             continue;
3802
3803           if (htab_find (visited_not_found, file_data) != NULL)
3804             continue;
3805           else if (htab_find (visited_found, file_data) != NULL)
3806             {
3807               per_cu->v.quick->mark = 1;
3808               continue;
3809             }
3810
3811           for (j = 0; j < file_data->num_file_names; ++j)
3812             {
3813               const char *this_real_name;
3814
3815               if (file_matcher (file_data->file_names[j], data, 0))
3816                 {
3817                   per_cu->v.quick->mark = 1;
3818                   break;
3819                 }
3820
3821               /* Before we invoke realpath, which can get expensive when many
3822                  files are involved, do a quick comparison of the basenames.  */
3823               if (!basenames_may_differ
3824                   && !file_matcher (lbasename (file_data->file_names[j]),
3825                                     data, 1))
3826                 continue;
3827
3828               this_real_name = dw2_get_real_path (objfile, file_data, j);
3829               if (file_matcher (this_real_name, data, 0))
3830                 {
3831                   per_cu->v.quick->mark = 1;
3832                   break;
3833                 }
3834             }
3835
3836           slot = htab_find_slot (per_cu->v.quick->mark
3837                                  ? visited_found
3838                                  : visited_not_found,
3839                                  file_data, INSERT);
3840           *slot = file_data;
3841         }
3842
3843       do_cleanups (cleanup);
3844     }
3845
3846   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3847     {
3848       offset_type idx = 2 * iter;
3849       const char *name;
3850       offset_type *vec, vec_len, vec_idx;
3851
3852       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3853         continue;
3854
3855       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3856
3857       if (! (*name_matcher) (name, data))
3858         continue;
3859
3860       /* The name was matched, now expand corresponding CUs that were
3861          marked.  */
3862       vec = (offset_type *) (index->constant_pool
3863                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3864       vec_len = MAYBE_SWAP (vec[0]);
3865       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3866         {
3867           struct dwarf2_per_cu_data *per_cu;
3868           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3869           gdb_index_symbol_kind symbol_kind =
3870             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3871           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3872           /* Only check the symbol attributes if they're present.
3873              Indices prior to version 7 don't record them,
3874              and indices >= 7 may elide them for certain symbols
3875              (gold does this).  */
3876           int attrs_valid =
3877             (index->version >= 7
3878              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3879
3880           /* Only check the symbol's kind if it has one.  */
3881           if (attrs_valid)
3882             {
3883               switch (kind)
3884                 {
3885                 case VARIABLES_DOMAIN:
3886                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3887                     continue;
3888                   break;
3889                 case FUNCTIONS_DOMAIN:
3890                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3891                     continue;
3892                   break;
3893                 case TYPES_DOMAIN:
3894                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3895                     continue;
3896                   break;
3897                 default:
3898                   break;
3899                 }
3900             }
3901
3902           /* Don't crash on bad data.  */
3903           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3904                            + dwarf2_per_objfile->n_type_units))
3905             {
3906               complaint (&symfile_complaints,
3907                          _(".gdb_index entry has bad CU index"
3908                            " [in module %s]"), objfile_name (objfile));
3909               continue;
3910             }
3911
3912           per_cu = dw2_get_cu (cu_index);
3913           if (file_matcher == NULL || per_cu->v.quick->mark)
3914             dw2_instantiate_symtab (per_cu);
3915         }
3916     }
3917 }
3918
3919 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3920    symtab.  */
3921
3922 static struct symtab *
3923 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3924 {
3925   int i;
3926
3927   if (BLOCKVECTOR (symtab) != NULL
3928       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3929     return symtab;
3930
3931   if (symtab->includes == NULL)
3932     return NULL;
3933
3934   for (i = 0; symtab->includes[i]; ++i)
3935     {
3936       struct symtab *s = symtab->includes[i];
3937
3938       s = recursively_find_pc_sect_symtab (s, pc);
3939       if (s != NULL)
3940         return s;
3941     }
3942
3943   return NULL;
3944 }
3945
3946 static struct symtab *
3947 dw2_find_pc_sect_symtab (struct objfile *objfile,
3948                          struct minimal_symbol *msymbol,
3949                          CORE_ADDR pc,
3950                          struct obj_section *section,
3951                          int warn_if_readin)
3952 {
3953   struct dwarf2_per_cu_data *data;
3954   struct symtab *result;
3955
3956   dw2_setup (objfile);
3957
3958   if (!objfile->psymtabs_addrmap)
3959     return NULL;
3960
3961   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3962   if (!data)
3963     return NULL;
3964
3965   if (warn_if_readin && data->v.quick->symtab)
3966     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3967              paddress (get_objfile_arch (objfile), pc));
3968
3969   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3970   gdb_assert (result != NULL);
3971   return result;
3972 }
3973
3974 static void
3975 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3976                           void *data, int need_fullname)
3977 {
3978   int i;
3979   struct cleanup *cleanup;
3980   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3981                                       NULL, xcalloc, xfree);
3982
3983   cleanup = make_cleanup_htab_delete (visited);
3984   dw2_setup (objfile);
3985
3986   /* The rule is CUs specify all the files, including those used by
3987      any TU, so there's no need to scan TUs here.
3988      We can ignore file names coming from already-expanded CUs.  */
3989
3990   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3991     {
3992       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3993
3994       if (per_cu->v.quick->symtab)
3995         {
3996           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3997                                         INSERT);
3998
3999           *slot = per_cu->v.quick->file_names;
4000         }
4001     }
4002
4003   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4004     {
4005       int j;
4006       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
4007       struct quick_file_names *file_data;
4008       void **slot;
4009
4010       /* We only need to look at symtabs not already expanded.  */
4011       if (per_cu->v.quick->symtab)
4012         continue;
4013
4014       file_data = dw2_get_file_names (per_cu);
4015       if (file_data == NULL)
4016         continue;
4017
4018       slot = htab_find_slot (visited, file_data, INSERT);
4019       if (*slot)
4020         {
4021           /* Already visited.  */
4022           continue;
4023         }
4024       *slot = file_data;
4025
4026       for (j = 0; j < file_data->num_file_names; ++j)
4027         {
4028           const char *this_real_name;
4029
4030           if (need_fullname)
4031             this_real_name = dw2_get_real_path (objfile, file_data, j);
4032           else
4033             this_real_name = NULL;
4034           (*fun) (file_data->file_names[j], this_real_name, data);
4035         }
4036     }
4037
4038   do_cleanups (cleanup);
4039 }
4040
4041 static int
4042 dw2_has_symbols (struct objfile *objfile)
4043 {
4044   return 1;
4045 }
4046
4047 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4048 {
4049   dw2_has_symbols,
4050   dw2_find_last_source_symtab,
4051   dw2_forget_cached_source_info,
4052   dw2_map_symtabs_matching_filename,
4053   dw2_lookup_symbol,
4054   dw2_print_stats,
4055   dw2_dump,
4056   dw2_relocate,
4057   dw2_expand_symtabs_for_function,
4058   dw2_expand_all_symtabs,
4059   dw2_expand_symtabs_with_fullname,
4060   dw2_map_matching_symbols,
4061   dw2_expand_symtabs_matching,
4062   dw2_find_pc_sect_symtab,
4063   dw2_map_symbol_filenames
4064 };
4065
4066 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4067    file will use psymtabs, or 1 if using the GNU index.  */
4068
4069 int
4070 dwarf2_initialize_objfile (struct objfile *objfile)
4071 {
4072   /* If we're about to read full symbols, don't bother with the
4073      indices.  In this case we also don't care if some other debug
4074      format is making psymtabs, because they are all about to be
4075      expanded anyway.  */
4076   if ((objfile->flags & OBJF_READNOW))
4077     {
4078       int i;
4079
4080       dwarf2_per_objfile->using_index = 1;
4081       create_all_comp_units (objfile);
4082       create_all_type_units (objfile);
4083       dwarf2_per_objfile->quick_file_names_table =
4084         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4085
4086       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4087                        + dwarf2_per_objfile->n_type_units); ++i)
4088         {
4089           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4090
4091           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4092                                             struct dwarf2_per_cu_quick_data);
4093         }
4094
4095       /* Return 1 so that gdb sees the "quick" functions.  However,
4096          these functions will be no-ops because we will have expanded
4097          all symtabs.  */
4098       return 1;
4099     }
4100
4101   if (dwarf2_read_index (objfile))
4102     return 1;
4103
4104   return 0;
4105 }
4106
4107 \f
4108
4109 /* Build a partial symbol table.  */
4110
4111 void
4112 dwarf2_build_psymtabs (struct objfile *objfile)
4113 {
4114   volatile struct gdb_exception except;
4115
4116   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4117     {
4118       init_psymbol_list (objfile, 1024);
4119     }
4120
4121   TRY_CATCH (except, RETURN_MASK_ERROR)
4122     {
4123       /* This isn't really ideal: all the data we allocate on the
4124          objfile's obstack is still uselessly kept around.  However,
4125          freeing it seems unsafe.  */
4126       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
4127
4128       dwarf2_build_psymtabs_hard (objfile);
4129       discard_cleanups (cleanups);
4130     }
4131   if (except.reason < 0)
4132     exception_print (gdb_stderr, except);
4133 }
4134
4135 /* Return the total length of the CU described by HEADER.  */
4136
4137 static unsigned int
4138 get_cu_length (const struct comp_unit_head *header)
4139 {
4140   return header->initial_length_size + header->length;
4141 }
4142
4143 /* Return TRUE if OFFSET is within CU_HEADER.  */
4144
4145 static inline int
4146 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
4147 {
4148   sect_offset bottom = { cu_header->offset.sect_off };
4149   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
4150
4151   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
4152 }
4153
4154 /* Find the base address of the compilation unit for range lists and
4155    location lists.  It will normally be specified by DW_AT_low_pc.
4156    In DWARF-3 draft 4, the base address could be overridden by
4157    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4158    compilation units with discontinuous ranges.  */
4159
4160 static void
4161 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4162 {
4163   struct attribute *attr;
4164
4165   cu->base_known = 0;
4166   cu->base_address = 0;
4167
4168   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4169   if (attr)
4170     {
4171       cu->base_address = DW_ADDR (attr);
4172       cu->base_known = 1;
4173     }
4174   else
4175     {
4176       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4177       if (attr)
4178         {
4179           cu->base_address = DW_ADDR (attr);
4180           cu->base_known = 1;
4181         }
4182     }
4183 }
4184
4185 /* Read in the comp unit header information from the debug_info at info_ptr.
4186    NOTE: This leaves members offset, first_die_offset to be filled in
4187    by the caller.  */
4188
4189 static const gdb_byte *
4190 read_comp_unit_head (struct comp_unit_head *cu_header,
4191                      const gdb_byte *info_ptr, bfd *abfd)
4192 {
4193   int signed_addr;
4194   unsigned int bytes_read;
4195
4196   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4197   cu_header->initial_length_size = bytes_read;
4198   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4199   info_ptr += bytes_read;
4200   cu_header->version = read_2_bytes (abfd, info_ptr);
4201   info_ptr += 2;
4202   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4203                                              &bytes_read);
4204   info_ptr += bytes_read;
4205   cu_header->addr_size = read_1_byte (abfd, info_ptr);
4206   info_ptr += 1;
4207   signed_addr = bfd_get_sign_extend_vma (abfd);
4208   if (signed_addr < 0)
4209     internal_error (__FILE__, __LINE__,
4210                     _("read_comp_unit_head: dwarf from non elf file"));
4211   cu_header->signed_addr_p = signed_addr;
4212
4213   return info_ptr;
4214 }
4215
4216 /* Helper function that returns the proper abbrev section for
4217    THIS_CU.  */
4218
4219 static struct dwarf2_section_info *
4220 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4221 {
4222   struct dwarf2_section_info *abbrev;
4223
4224   if (this_cu->is_dwz)
4225     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4226   else
4227     abbrev = &dwarf2_per_objfile->abbrev;
4228
4229   return abbrev;
4230 }
4231
4232 /* Subroutine of read_and_check_comp_unit_head and
4233    read_and_check_type_unit_head to simplify them.
4234    Perform various error checking on the header.  */
4235
4236 static void
4237 error_check_comp_unit_head (struct comp_unit_head *header,
4238                             struct dwarf2_section_info *section,
4239                             struct dwarf2_section_info *abbrev_section)
4240 {
4241   bfd *abfd = get_section_bfd_owner (section);
4242   const char *filename = get_section_file_name (section);
4243
4244   if (header->version != 2 && header->version != 3 && header->version != 4)
4245     error (_("Dwarf Error: wrong version in compilation unit header "
4246            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4247            filename);
4248
4249   if (header->abbrev_offset.sect_off
4250       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4251     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4252            "(offset 0x%lx + 6) [in module %s]"),
4253            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4254            filename);
4255
4256   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4257      avoid potential 32-bit overflow.  */
4258   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4259       > section->size)
4260     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4261            "(offset 0x%lx + 0) [in module %s]"),
4262            (long) header->length, (long) header->offset.sect_off,
4263            filename);
4264 }
4265
4266 /* Read in a CU/TU header and perform some basic error checking.
4267    The contents of the header are stored in HEADER.
4268    The result is a pointer to the start of the first DIE.  */
4269
4270 static const gdb_byte *
4271 read_and_check_comp_unit_head (struct comp_unit_head *header,
4272                                struct dwarf2_section_info *section,
4273                                struct dwarf2_section_info *abbrev_section,
4274                                const gdb_byte *info_ptr,
4275                                int is_debug_types_section)
4276 {
4277   const gdb_byte *beg_of_comp_unit = info_ptr;
4278   bfd *abfd = get_section_bfd_owner (section);
4279
4280   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4281
4282   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4283
4284   /* If we're reading a type unit, skip over the signature and
4285      type_offset fields.  */
4286   if (is_debug_types_section)
4287     info_ptr += 8 /*signature*/ + header->offset_size;
4288
4289   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4290
4291   error_check_comp_unit_head (header, section, abbrev_section);
4292
4293   return info_ptr;
4294 }
4295
4296 /* Read in the types comp unit header information from .debug_types entry at
4297    types_ptr.  The result is a pointer to one past the end of the header.  */
4298
4299 static const gdb_byte *
4300 read_and_check_type_unit_head (struct comp_unit_head *header,
4301                                struct dwarf2_section_info *section,
4302                                struct dwarf2_section_info *abbrev_section,
4303                                const gdb_byte *info_ptr,
4304                                ULONGEST *signature,
4305                                cu_offset *type_offset_in_tu)
4306 {
4307   const gdb_byte *beg_of_comp_unit = info_ptr;
4308   bfd *abfd = get_section_bfd_owner (section);
4309
4310   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4311
4312   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4313
4314   /* If we're reading a type unit, skip over the signature and
4315      type_offset fields.  */
4316   if (signature != NULL)
4317     *signature = read_8_bytes (abfd, info_ptr);
4318   info_ptr += 8;
4319   if (type_offset_in_tu != NULL)
4320     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4321                                                header->offset_size);
4322   info_ptr += header->offset_size;
4323
4324   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4325
4326   error_check_comp_unit_head (header, section, abbrev_section);
4327
4328   return info_ptr;
4329 }
4330
4331 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4332
4333 static sect_offset
4334 read_abbrev_offset (struct dwarf2_section_info *section,
4335                     sect_offset offset)
4336 {
4337   bfd *abfd = get_section_bfd_owner (section);
4338   const gdb_byte *info_ptr;
4339   unsigned int length, initial_length_size, offset_size;
4340   sect_offset abbrev_offset;
4341
4342   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4343   info_ptr = section->buffer + offset.sect_off;
4344   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4345   offset_size = initial_length_size == 4 ? 4 : 8;
4346   info_ptr += initial_length_size + 2 /*version*/;
4347   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4348   return abbrev_offset;
4349 }
4350
4351 /* Allocate a new partial symtab for file named NAME and mark this new
4352    partial symtab as being an include of PST.  */
4353
4354 static void
4355 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4356                                struct objfile *objfile)
4357 {
4358   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4359
4360   if (!IS_ABSOLUTE_PATH (subpst->filename))
4361     {
4362       /* It shares objfile->objfile_obstack.  */
4363       subpst->dirname = pst->dirname;
4364     }
4365
4366   subpst->section_offsets = pst->section_offsets;
4367   subpst->textlow = 0;
4368   subpst->texthigh = 0;
4369
4370   subpst->dependencies = (struct partial_symtab **)
4371     obstack_alloc (&objfile->objfile_obstack,
4372                    sizeof (struct partial_symtab *));
4373   subpst->dependencies[0] = pst;
4374   subpst->number_of_dependencies = 1;
4375
4376   subpst->globals_offset = 0;
4377   subpst->n_global_syms = 0;
4378   subpst->statics_offset = 0;
4379   subpst->n_static_syms = 0;
4380   subpst->symtab = NULL;
4381   subpst->read_symtab = pst->read_symtab;
4382   subpst->readin = 0;
4383
4384   /* No private part is necessary for include psymtabs.  This property
4385      can be used to differentiate between such include psymtabs and
4386      the regular ones.  */
4387   subpst->read_symtab_private = NULL;
4388 }
4389
4390 /* Read the Line Number Program data and extract the list of files
4391    included by the source file represented by PST.  Build an include
4392    partial symtab for each of these included files.  */
4393
4394 static void
4395 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4396                                struct die_info *die,
4397                                struct partial_symtab *pst)
4398 {
4399   struct line_header *lh = NULL;
4400   struct attribute *attr;
4401
4402   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4403   if (attr)
4404     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4405   if (lh == NULL)
4406     return;  /* No linetable, so no includes.  */
4407
4408   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4409   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4410
4411   free_line_header (lh);
4412 }
4413
4414 static hashval_t
4415 hash_signatured_type (const void *item)
4416 {
4417   const struct signatured_type *sig_type = item;
4418
4419   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4420   return sig_type->signature;
4421 }
4422
4423 static int
4424 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4425 {
4426   const struct signatured_type *lhs = item_lhs;
4427   const struct signatured_type *rhs = item_rhs;
4428
4429   return lhs->signature == rhs->signature;
4430 }
4431
4432 /* Allocate a hash table for signatured types.  */
4433
4434 static htab_t
4435 allocate_signatured_type_table (struct objfile *objfile)
4436 {
4437   return htab_create_alloc_ex (41,
4438                                hash_signatured_type,
4439                                eq_signatured_type,
4440                                NULL,
4441                                &objfile->objfile_obstack,
4442                                hashtab_obstack_allocate,
4443                                dummy_obstack_deallocate);
4444 }
4445
4446 /* A helper function to add a signatured type CU to a table.  */
4447
4448 static int
4449 add_signatured_type_cu_to_table (void **slot, void *datum)
4450 {
4451   struct signatured_type *sigt = *slot;
4452   struct signatured_type ***datap = datum;
4453
4454   **datap = sigt;
4455   ++*datap;
4456
4457   return 1;
4458 }
4459
4460 /* Create the hash table of all entries in the .debug_types
4461    (or .debug_types.dwo) section(s).
4462    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4463    otherwise it is NULL.
4464
4465    The result is a pointer to the hash table or NULL if there are no types.
4466
4467    Note: This function processes DWO files only, not DWP files.  */
4468
4469 static htab_t
4470 create_debug_types_hash_table (struct dwo_file *dwo_file,
4471                                VEC (dwarf2_section_info_def) *types)
4472 {
4473   struct objfile *objfile = dwarf2_per_objfile->objfile;
4474   htab_t types_htab = NULL;
4475   int ix;
4476   struct dwarf2_section_info *section;
4477   struct dwarf2_section_info *abbrev_section;
4478
4479   if (VEC_empty (dwarf2_section_info_def, types))
4480     return NULL;
4481
4482   abbrev_section = (dwo_file != NULL
4483                     ? &dwo_file->sections.abbrev
4484                     : &dwarf2_per_objfile->abbrev);
4485
4486   if (dwarf2_read_debug)
4487     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4488                         dwo_file ? ".dwo" : "",
4489                         get_section_file_name (abbrev_section));
4490
4491   for (ix = 0;
4492        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4493        ++ix)
4494     {
4495       bfd *abfd;
4496       const gdb_byte *info_ptr, *end_ptr;
4497
4498       dwarf2_read_section (objfile, section);
4499       info_ptr = section->buffer;
4500
4501       if (info_ptr == NULL)
4502         continue;
4503
4504       /* We can't set abfd until now because the section may be empty or
4505          not present, in which case the bfd is unknown.  */
4506       abfd = get_section_bfd_owner (section);
4507
4508       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4509          because we don't need to read any dies: the signature is in the
4510          header.  */
4511
4512       end_ptr = info_ptr + section->size;
4513       while (info_ptr < end_ptr)
4514         {
4515           sect_offset offset;
4516           cu_offset type_offset_in_tu;
4517           ULONGEST signature;
4518           struct signatured_type *sig_type;
4519           struct dwo_unit *dwo_tu;
4520           void **slot;
4521           const gdb_byte *ptr = info_ptr;
4522           struct comp_unit_head header;
4523           unsigned int length;
4524
4525           offset.sect_off = ptr - section->buffer;
4526
4527           /* We need to read the type's signature in order to build the hash
4528              table, but we don't need anything else just yet.  */
4529
4530           ptr = read_and_check_type_unit_head (&header, section,
4531                                                abbrev_section, ptr,
4532                                                &signature, &type_offset_in_tu);
4533
4534           length = get_cu_length (&header);
4535
4536           /* Skip dummy type units.  */
4537           if (ptr >= info_ptr + length
4538               || peek_abbrev_code (abfd, ptr) == 0)
4539             {
4540               info_ptr += length;
4541               continue;
4542             }
4543
4544           if (types_htab == NULL)
4545             {
4546               if (dwo_file)
4547                 types_htab = allocate_dwo_unit_table (objfile);
4548               else
4549                 types_htab = allocate_signatured_type_table (objfile);
4550             }
4551
4552           if (dwo_file)
4553             {
4554               sig_type = NULL;
4555               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4556                                        struct dwo_unit);
4557               dwo_tu->dwo_file = dwo_file;
4558               dwo_tu->signature = signature;
4559               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4560               dwo_tu->section = section;
4561               dwo_tu->offset = offset;
4562               dwo_tu->length = length;
4563             }
4564           else
4565             {
4566               /* N.B.: type_offset is not usable if this type uses a DWO file.
4567                  The real type_offset is in the DWO file.  */
4568               dwo_tu = NULL;
4569               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4570                                          struct signatured_type);
4571               sig_type->signature = signature;
4572               sig_type->type_offset_in_tu = type_offset_in_tu;
4573               sig_type->per_cu.objfile = objfile;
4574               sig_type->per_cu.is_debug_types = 1;
4575               sig_type->per_cu.section = section;
4576               sig_type->per_cu.offset = offset;
4577               sig_type->per_cu.length = length;
4578             }
4579
4580           slot = htab_find_slot (types_htab,
4581                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4582                                  INSERT);
4583           gdb_assert (slot != NULL);
4584           if (*slot != NULL)
4585             {
4586               sect_offset dup_offset;
4587
4588               if (dwo_file)
4589                 {
4590                   const struct dwo_unit *dup_tu = *slot;
4591
4592                   dup_offset = dup_tu->offset;
4593                 }
4594               else
4595                 {
4596                   const struct signatured_type *dup_tu = *slot;
4597
4598                   dup_offset = dup_tu->per_cu.offset;
4599                 }
4600
4601               complaint (&symfile_complaints,
4602                          _("debug type entry at offset 0x%x is duplicate to"
4603                            " the entry at offset 0x%x, signature %s"),
4604                          offset.sect_off, dup_offset.sect_off,
4605                          hex_string (signature));
4606             }
4607           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4608
4609           if (dwarf2_read_debug)
4610             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4611                                 offset.sect_off,
4612                                 hex_string (signature));
4613
4614           info_ptr += length;
4615         }
4616     }
4617
4618   return types_htab;
4619 }
4620
4621 /* Create the hash table of all entries in the .debug_types section,
4622    and initialize all_type_units.
4623    The result is zero if there is an error (e.g. missing .debug_types section),
4624    otherwise non-zero.  */
4625
4626 static int
4627 create_all_type_units (struct objfile *objfile)
4628 {
4629   htab_t types_htab;
4630   struct signatured_type **iter;
4631
4632   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4633   if (types_htab == NULL)
4634     {
4635       dwarf2_per_objfile->signatured_types = NULL;
4636       return 0;
4637     }
4638
4639   dwarf2_per_objfile->signatured_types = types_htab;
4640
4641   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4642   dwarf2_per_objfile->all_type_units
4643     = xmalloc (dwarf2_per_objfile->n_type_units
4644                * sizeof (struct signatured_type *));
4645   iter = &dwarf2_per_objfile->all_type_units[0];
4646   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4647   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4648               == dwarf2_per_objfile->n_type_units);
4649
4650   return 1;
4651 }
4652
4653 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4654    Fill in SIG_ENTRY with DWO_ENTRY.  */
4655
4656 static void
4657 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4658                                   struct signatured_type *sig_entry,
4659                                   struct dwo_unit *dwo_entry)
4660 {
4661   /* Make sure we're not clobbering something we don't expect to.  */
4662   gdb_assert (! sig_entry->per_cu.queued);
4663   gdb_assert (sig_entry->per_cu.cu == NULL);
4664   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4665   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4666   gdb_assert (sig_entry->signature == dwo_entry->signature);
4667   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4668   gdb_assert (sig_entry->type_unit_group == NULL);
4669   gdb_assert (sig_entry->dwo_unit == NULL);
4670
4671   sig_entry->per_cu.section = dwo_entry->section;
4672   sig_entry->per_cu.offset = dwo_entry->offset;
4673   sig_entry->per_cu.length = dwo_entry->length;
4674   sig_entry->per_cu.reading_dwo_directly = 1;
4675   sig_entry->per_cu.objfile = objfile;
4676   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4677   sig_entry->dwo_unit = dwo_entry;
4678 }
4679
4680 /* Subroutine of lookup_signatured_type.
4681    If we haven't read the TU yet, create the signatured_type data structure
4682    for a TU to be read in directly from a DWO file, bypassing the stub.
4683    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4684    using .gdb_index, then when reading a CU we want to stay in the DWO file
4685    containing that CU.  Otherwise we could end up reading several other DWO
4686    files (due to comdat folding) to process the transitive closure of all the
4687    mentioned TUs, and that can be slow.  The current DWO file will have every
4688    type signature that it needs.
4689    We only do this for .gdb_index because in the psymtab case we already have
4690    to read all the DWOs to build the type unit groups.  */
4691
4692 static struct signatured_type *
4693 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4694 {
4695   struct objfile *objfile = dwarf2_per_objfile->objfile;
4696   struct dwo_file *dwo_file;
4697   struct dwo_unit find_dwo_entry, *dwo_entry;
4698   struct signatured_type find_sig_entry, *sig_entry;
4699
4700   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4701
4702   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4703      dwo_unit of the TU itself.  */
4704   dwo_file = cu->dwo_unit->dwo_file;
4705
4706   /* We only ever need to read in one copy of a signatured type.
4707      Just use the global signatured_types array.  If this is the first time
4708      we're reading this type, replace the recorded data from .gdb_index with
4709      this TU.  */
4710
4711   if (dwarf2_per_objfile->signatured_types == NULL)
4712     return NULL;
4713   find_sig_entry.signature = sig;
4714   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4715   if (sig_entry == NULL)
4716     return NULL;
4717
4718   /* We can get here with the TU already read, *or* in the process of being
4719      read.  Don't reassign it if that's the case.  Also note that if the TU is
4720      already being read, it may not have come from a DWO, the program may be
4721      a mix of Fission-compiled code and non-Fission-compiled code.  */
4722   /* Have we already tried to read this TU?  */
4723   if (sig_entry->per_cu.tu_read)
4724     return sig_entry;
4725
4726   /* Ok, this is the first time we're reading this TU.  */
4727   if (dwo_file->tus == NULL)
4728     return NULL;
4729   find_dwo_entry.signature = sig;
4730   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4731   if (dwo_entry == NULL)
4732     return NULL;
4733
4734   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4735   sig_entry->per_cu.tu_read = 1;
4736   return sig_entry;
4737 }
4738
4739 /* Subroutine of lookup_dwp_signatured_type.
4740    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4741
4742 static struct signatured_type *
4743 add_type_unit (ULONGEST sig)
4744 {
4745   struct objfile *objfile = dwarf2_per_objfile->objfile;
4746   int n_type_units = dwarf2_per_objfile->n_type_units;
4747   struct signatured_type *sig_type;
4748   void **slot;
4749
4750   ++n_type_units;
4751   dwarf2_per_objfile->all_type_units =
4752     xrealloc (dwarf2_per_objfile->all_type_units,
4753               n_type_units * sizeof (struct signatured_type *));
4754   dwarf2_per_objfile->n_type_units = n_type_units;
4755   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4756                              struct signatured_type);
4757   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4758   sig_type->signature = sig;
4759   sig_type->per_cu.is_debug_types = 1;
4760   sig_type->per_cu.v.quick =
4761     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4762                     struct dwarf2_per_cu_quick_data);
4763   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4764                          sig_type, INSERT);
4765   gdb_assert (*slot == NULL);
4766   *slot = sig_type;
4767   /* The rest of sig_type must be filled in by the caller.  */
4768   return sig_type;
4769 }
4770
4771 /* Subroutine of lookup_signatured_type.
4772    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4773    then try the DWP file.
4774    Normally this "can't happen", but if there's a bug in signature
4775    generation and/or the DWP file is built incorrectly, it can happen.
4776    Using the type directly from the DWP file means we don't have the stub
4777    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4778    not critical.  [Eventually the stub may go away for type units anyway.]  */
4779
4780 static struct signatured_type *
4781 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4782 {
4783   struct objfile *objfile = dwarf2_per_objfile->objfile;
4784   struct dwp_file *dwp_file = get_dwp_file ();
4785   struct dwo_unit *dwo_entry;
4786   struct signatured_type find_sig_entry, *sig_entry;
4787
4788   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4789   gdb_assert (dwp_file != NULL);
4790
4791   if (dwarf2_per_objfile->signatured_types != NULL)
4792     {
4793       find_sig_entry.signature = sig;
4794       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4795                              &find_sig_entry);
4796       if (sig_entry != NULL)
4797         return sig_entry;
4798     }
4799
4800   /* This is the "shouldn't happen" case.
4801      Try the DWP file and hope for the best.  */
4802   if (dwp_file->tus == NULL)
4803     return NULL;
4804   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
4805                                       sig, 1 /* is_debug_types */);
4806   if (dwo_entry == NULL)
4807     return NULL;
4808
4809   sig_entry = add_type_unit (sig);
4810   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4811
4812   /* The caller will signal a complaint if we return NULL.
4813      Here we don't return NULL but we still want to complain.  */
4814   complaint (&symfile_complaints,
4815              _("Bad type signature %s referenced by %s at 0x%x,"
4816                " coping by using copy in DWP [in module %s]"),
4817              hex_string (sig),
4818              cu->per_cu->is_debug_types ? "TU" : "CU",
4819              cu->per_cu->offset.sect_off,
4820              objfile_name (objfile));
4821
4822   return sig_entry;
4823 }
4824
4825 /* Lookup a signature based type for DW_FORM_ref_sig8.
4826    Returns NULL if signature SIG is not present in the table.
4827    It is up to the caller to complain about this.  */
4828
4829 static struct signatured_type *
4830 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4831 {
4832   if (cu->dwo_unit
4833       && dwarf2_per_objfile->using_index)
4834     {
4835       /* We're in a DWO/DWP file, and we're using .gdb_index.
4836          These cases require special processing.  */
4837       if (get_dwp_file () == NULL)
4838         return lookup_dwo_signatured_type (cu, sig);
4839       else
4840         return lookup_dwp_signatured_type (cu, sig);
4841     }
4842   else
4843     {
4844       struct signatured_type find_entry, *entry;
4845
4846       if (dwarf2_per_objfile->signatured_types == NULL)
4847         return NULL;
4848       find_entry.signature = sig;
4849       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4850       return entry;
4851     }
4852 }
4853 \f
4854 /* Low level DIE reading support.  */
4855
4856 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4857
4858 static void
4859 init_cu_die_reader (struct die_reader_specs *reader,
4860                     struct dwarf2_cu *cu,
4861                     struct dwarf2_section_info *section,
4862                     struct dwo_file *dwo_file)
4863 {
4864   gdb_assert (section->readin && section->buffer != NULL);
4865   reader->abfd = get_section_bfd_owner (section);
4866   reader->cu = cu;
4867   reader->dwo_file = dwo_file;
4868   reader->die_section = section;
4869   reader->buffer = section->buffer;
4870   reader->buffer_end = section->buffer + section->size;
4871   reader->comp_dir = NULL;
4872 }
4873
4874 /* Subroutine of init_cutu_and_read_dies to simplify it.
4875    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4876    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4877    already.
4878
4879    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4880    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4881    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4882    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4883    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4884    COMP_DIR must be non-NULL.
4885    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4886    are filled in with the info of the DIE from the DWO file.
4887    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4888    provided an abbrev table to use.
4889    The result is non-zero if a valid (non-dummy) DIE was found.  */
4890
4891 static int
4892 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4893                         struct dwo_unit *dwo_unit,
4894                         int abbrev_table_provided,
4895                         struct die_info *stub_comp_unit_die,
4896                         const char *stub_comp_dir,
4897                         struct die_reader_specs *result_reader,
4898                         const gdb_byte **result_info_ptr,
4899                         struct die_info **result_comp_unit_die,
4900                         int *result_has_children)
4901 {
4902   struct objfile *objfile = dwarf2_per_objfile->objfile;
4903   struct dwarf2_cu *cu = this_cu->cu;
4904   struct dwarf2_section_info *section;
4905   bfd *abfd;
4906   const gdb_byte *begin_info_ptr, *info_ptr;
4907   const char *comp_dir_string;
4908   ULONGEST signature; /* Or dwo_id.  */
4909   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4910   int i,num_extra_attrs;
4911   struct dwarf2_section_info *dwo_abbrev_section;
4912   struct attribute *attr;
4913   struct attribute comp_dir_attr;
4914   struct die_info *comp_unit_die;
4915
4916   /* Both can't be provided.  */
4917   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4918
4919   /* These attributes aren't processed until later:
4920      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4921      However, the attribute is found in the stub which we won't have later.
4922      In order to not impose this complication on the rest of the code,
4923      we read them here and copy them to the DWO CU/TU die.  */
4924
4925   stmt_list = NULL;
4926   low_pc = NULL;
4927   high_pc = NULL;
4928   ranges = NULL;
4929   comp_dir = NULL;
4930
4931   if (stub_comp_unit_die != NULL)
4932     {
4933       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4934          DWO file.  */
4935       if (! this_cu->is_debug_types)
4936         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4937       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4938       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4939       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4940       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4941
4942       /* There should be a DW_AT_addr_base attribute here (if needed).
4943          We need the value before we can process DW_FORM_GNU_addr_index.  */
4944       cu->addr_base = 0;
4945       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4946       if (attr)
4947         cu->addr_base = DW_UNSND (attr);
4948
4949       /* There should be a DW_AT_ranges_base attribute here (if needed).
4950          We need the value before we can process DW_AT_ranges.  */
4951       cu->ranges_base = 0;
4952       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4953       if (attr)
4954         cu->ranges_base = DW_UNSND (attr);
4955     }
4956   else if (stub_comp_dir != NULL)
4957     {
4958       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4959       comp_dir = (struct attribute *)
4960         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4961       comp_dir->name = DW_AT_comp_dir;
4962       comp_dir->form = DW_FORM_string;
4963       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4964       DW_STRING (comp_dir) = stub_comp_dir;
4965     }
4966
4967   /* Set up for reading the DWO CU/TU.  */
4968   cu->dwo_unit = dwo_unit;
4969   section = dwo_unit->section;
4970   dwarf2_read_section (objfile, section);
4971   abfd = get_section_bfd_owner (section);
4972   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4973   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4974   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4975
4976   if (this_cu->is_debug_types)
4977     {
4978       ULONGEST header_signature;
4979       cu_offset type_offset_in_tu;
4980       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4981
4982       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4983                                                 dwo_abbrev_section,
4984                                                 info_ptr,
4985                                                 &header_signature,
4986                                                 &type_offset_in_tu);
4987       /* This is not an assert because it can be caused by bad debug info.  */
4988       if (sig_type->signature != header_signature)
4989         {
4990           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4991                    " TU at offset 0x%x [in module %s]"),
4992                  hex_string (sig_type->signature),
4993                  hex_string (header_signature),
4994                  dwo_unit->offset.sect_off,
4995                  bfd_get_filename (abfd));
4996         }
4997       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4998       /* For DWOs coming from DWP files, we don't know the CU length
4999          nor the type's offset in the TU until now.  */
5000       dwo_unit->length = get_cu_length (&cu->header);
5001       dwo_unit->type_offset_in_tu = type_offset_in_tu;
5002
5003       /* Establish the type offset that can be used to lookup the type.
5004          For DWO files, we don't know it until now.  */
5005       sig_type->type_offset_in_section.sect_off =
5006         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
5007     }
5008   else
5009     {
5010       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5011                                                 dwo_abbrev_section,
5012                                                 info_ptr, 0);
5013       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5014       /* For DWOs coming from DWP files, we don't know the CU length
5015          until now.  */
5016       dwo_unit->length = get_cu_length (&cu->header);
5017     }
5018
5019   /* Replace the CU's original abbrev table with the DWO's.
5020      Reminder: We can't read the abbrev table until we've read the header.  */
5021   if (abbrev_table_provided)
5022     {
5023       /* Don't free the provided abbrev table, the caller of
5024          init_cutu_and_read_dies owns it.  */
5025       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5026       /* Ensure the DWO abbrev table gets freed.  */
5027       make_cleanup (dwarf2_free_abbrev_table, cu);
5028     }
5029   else
5030     {
5031       dwarf2_free_abbrev_table (cu);
5032       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5033       /* Leave any existing abbrev table cleanup as is.  */
5034     }
5035
5036   /* Read in the die, but leave space to copy over the attributes
5037      from the stub.  This has the benefit of simplifying the rest of
5038      the code - all the work to maintain the illusion of a single
5039      DW_TAG_{compile,type}_unit DIE is done here.  */
5040   num_extra_attrs = ((stmt_list != NULL)
5041                      + (low_pc != NULL)
5042                      + (high_pc != NULL)
5043                      + (ranges != NULL)
5044                      + (comp_dir != NULL));
5045   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5046                               result_has_children, num_extra_attrs);
5047
5048   /* Copy over the attributes from the stub to the DIE we just read in.  */
5049   comp_unit_die = *result_comp_unit_die;
5050   i = comp_unit_die->num_attrs;
5051   if (stmt_list != NULL)
5052     comp_unit_die->attrs[i++] = *stmt_list;
5053   if (low_pc != NULL)
5054     comp_unit_die->attrs[i++] = *low_pc;
5055   if (high_pc != NULL)
5056     comp_unit_die->attrs[i++] = *high_pc;
5057   if (ranges != NULL)
5058     comp_unit_die->attrs[i++] = *ranges;
5059   if (comp_dir != NULL)
5060     comp_unit_die->attrs[i++] = *comp_dir;
5061   comp_unit_die->num_attrs += num_extra_attrs;
5062
5063   if (dwarf2_die_debug)
5064     {
5065       fprintf_unfiltered (gdb_stdlog,
5066                           "Read die from %s@0x%x of %s:\n",
5067                           get_section_name (section),
5068                           (unsigned) (begin_info_ptr - section->buffer),
5069                           bfd_get_filename (abfd));
5070       dump_die (comp_unit_die, dwarf2_die_debug);
5071     }
5072
5073   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5074      TUs by skipping the stub and going directly to the entry in the DWO file.
5075      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5076      to get it via circuitous means.  Blech.  */
5077   if (comp_dir != NULL)
5078     result_reader->comp_dir = DW_STRING (comp_dir);
5079
5080   /* Skip dummy compilation units.  */
5081   if (info_ptr >= begin_info_ptr + dwo_unit->length
5082       || peek_abbrev_code (abfd, info_ptr) == 0)
5083     return 0;
5084
5085   *result_info_ptr = info_ptr;
5086   return 1;
5087 }
5088
5089 /* Subroutine of init_cutu_and_read_dies to simplify it.
5090    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5091    Returns NULL if the specified DWO unit cannot be found.  */
5092
5093 static struct dwo_unit *
5094 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5095                  struct die_info *comp_unit_die)
5096 {
5097   struct dwarf2_cu *cu = this_cu->cu;
5098   struct attribute *attr;
5099   ULONGEST signature;
5100   struct dwo_unit *dwo_unit;
5101   const char *comp_dir, *dwo_name;
5102
5103   gdb_assert (cu != NULL);
5104
5105   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5106   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5107   gdb_assert (attr != NULL);
5108   dwo_name = DW_STRING (attr);
5109   comp_dir = NULL;
5110   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5111   if (attr)
5112     comp_dir = DW_STRING (attr);
5113
5114   if (this_cu->is_debug_types)
5115     {
5116       struct signatured_type *sig_type;
5117
5118       /* Since this_cu is the first member of struct signatured_type,
5119          we can go from a pointer to one to a pointer to the other.  */
5120       sig_type = (struct signatured_type *) this_cu;
5121       signature = sig_type->signature;
5122       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5123     }
5124   else
5125     {
5126       struct attribute *attr;
5127
5128       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5129       if (! attr)
5130         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5131                  " [in module %s]"),
5132                dwo_name, objfile_name (this_cu->objfile));
5133       signature = DW_UNSND (attr);
5134       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5135                                        signature);
5136     }
5137
5138   return dwo_unit;
5139 }
5140
5141 /* Subroutine of init_cutu_and_read_dies to simplify it.
5142    Read a TU directly from a DWO file, bypassing the stub.  */
5143
5144 static void
5145 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
5146                            die_reader_func_ftype *die_reader_func,
5147                            void *data)
5148 {
5149   struct dwarf2_cu *cu;
5150   struct signatured_type *sig_type;
5151   struct cleanup *cleanups, *free_cu_cleanup;
5152   struct die_reader_specs reader;
5153   const gdb_byte *info_ptr;
5154   struct die_info *comp_unit_die;
5155   int has_children;
5156
5157   /* Verify we can do the following downcast, and that we have the
5158      data we need.  */
5159   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5160   sig_type = (struct signatured_type *) this_cu;
5161   gdb_assert (sig_type->dwo_unit != NULL);
5162
5163   cleanups = make_cleanup (null_cleanup, NULL);
5164
5165   gdb_assert (this_cu->cu == NULL);
5166   cu = xmalloc (sizeof (*cu));
5167   init_one_comp_unit (cu, this_cu);
5168   /* If an error occurs while loading, release our storage.  */
5169   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5170
5171   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5172                               0 /* abbrev_table_provided */,
5173                               NULL /* stub_comp_unit_die */,
5174                               sig_type->dwo_unit->dwo_file->comp_dir,
5175                               &reader, &info_ptr,
5176                               &comp_unit_die, &has_children) == 0)
5177     {
5178       /* Dummy die.  */
5179       do_cleanups (cleanups);
5180       return;
5181     }
5182
5183   /* All the "real" work is done here.  */
5184   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5185
5186   /* This duplicates some code in init_cutu_and_read_dies,
5187      but the alternative is making the latter more complex.
5188      This function is only for the special case of using DWO files directly:
5189      no point in overly complicating the general case just to handle this.  */
5190   if (keep)
5191     {
5192       /* We've successfully allocated this compilation unit.  Let our
5193          caller clean it up when finished with it.  */
5194       discard_cleanups (free_cu_cleanup);
5195
5196       /* We can only discard free_cu_cleanup and all subsequent cleanups.
5197          So we have to manually free the abbrev table.  */
5198       dwarf2_free_abbrev_table (cu);
5199
5200       /* Link this CU into read_in_chain.  */
5201       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5202       dwarf2_per_objfile->read_in_chain = this_cu;
5203     }
5204   else
5205     do_cleanups (free_cu_cleanup);
5206
5207   do_cleanups (cleanups);
5208 }
5209
5210 /* Initialize a CU (or TU) and read its DIEs.
5211    If the CU defers to a DWO file, read the DWO file as well.
5212
5213    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5214    Otherwise the table specified in the comp unit header is read in and used.
5215    This is an optimization for when we already have the abbrev table.
5216
5217    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5218    Otherwise, a new CU is allocated with xmalloc.
5219
5220    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5221    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5222
5223    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5224    linker) then DIE_READER_FUNC will not get called.  */
5225
5226 static void
5227 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5228                          struct abbrev_table *abbrev_table,
5229                          int use_existing_cu, int keep,
5230                          die_reader_func_ftype *die_reader_func,
5231                          void *data)
5232 {
5233   struct objfile *objfile = dwarf2_per_objfile->objfile;
5234   struct dwarf2_section_info *section = this_cu->section;
5235   bfd *abfd = get_section_bfd_owner (section);
5236   struct dwarf2_cu *cu;
5237   const gdb_byte *begin_info_ptr, *info_ptr;
5238   struct die_reader_specs reader;
5239   struct die_info *comp_unit_die;
5240   int has_children;
5241   struct attribute *attr;
5242   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5243   struct signatured_type *sig_type = NULL;
5244   struct dwarf2_section_info *abbrev_section;
5245   /* Non-zero if CU currently points to a DWO file and we need to
5246      reread it.  When this happens we need to reread the skeleton die
5247      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5248   int rereading_dwo_cu = 0;
5249
5250   if (dwarf2_die_debug)
5251     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5252                         this_cu->is_debug_types ? "type" : "comp",
5253                         this_cu->offset.sect_off);
5254
5255   if (use_existing_cu)
5256     gdb_assert (keep);
5257
5258   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5259      file (instead of going through the stub), short-circuit all of this.  */
5260   if (this_cu->reading_dwo_directly)
5261     {
5262       /* Narrow down the scope of possibilities to have to understand.  */
5263       gdb_assert (this_cu->is_debug_types);
5264       gdb_assert (abbrev_table == NULL);
5265       gdb_assert (!use_existing_cu);
5266       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5267       return;
5268     }
5269
5270   cleanups = make_cleanup (null_cleanup, NULL);
5271
5272   /* This is cheap if the section is already read in.  */
5273   dwarf2_read_section (objfile, section);
5274
5275   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5276
5277   abbrev_section = get_abbrev_section_for_cu (this_cu);
5278
5279   if (use_existing_cu && this_cu->cu != NULL)
5280     {
5281       cu = this_cu->cu;
5282
5283       /* If this CU is from a DWO file we need to start over, we need to
5284          refetch the attributes from the skeleton CU.
5285          This could be optimized by retrieving those attributes from when we
5286          were here the first time: the previous comp_unit_die was stored in
5287          comp_unit_obstack.  But there's no data yet that we need this
5288          optimization.  */
5289       if (cu->dwo_unit != NULL)
5290         rereading_dwo_cu = 1;
5291     }
5292   else
5293     {
5294       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5295       gdb_assert (this_cu->cu == NULL);
5296
5297       cu = xmalloc (sizeof (*cu));
5298       init_one_comp_unit (cu, this_cu);
5299
5300       /* If an error occurs while loading, release our storage.  */
5301       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5302     }
5303
5304   /* Get the header.  */
5305   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5306     {
5307       /* We already have the header, there's no need to read it in again.  */
5308       info_ptr += cu->header.first_die_offset.cu_off;
5309     }
5310   else
5311     {
5312       if (this_cu->is_debug_types)
5313         {
5314           ULONGEST signature;
5315           cu_offset type_offset_in_tu;
5316
5317           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5318                                                     abbrev_section, info_ptr,
5319                                                     &signature,
5320                                                     &type_offset_in_tu);
5321
5322           /* Since per_cu is the first member of struct signatured_type,
5323              we can go from a pointer to one to a pointer to the other.  */
5324           sig_type = (struct signatured_type *) this_cu;
5325           gdb_assert (sig_type->signature == signature);
5326           gdb_assert (sig_type->type_offset_in_tu.cu_off
5327                       == type_offset_in_tu.cu_off);
5328           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5329
5330           /* LENGTH has not been set yet for type units if we're
5331              using .gdb_index.  */
5332           this_cu->length = get_cu_length (&cu->header);
5333
5334           /* Establish the type offset that can be used to lookup the type.  */
5335           sig_type->type_offset_in_section.sect_off =
5336             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5337         }
5338       else
5339         {
5340           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5341                                                     abbrev_section,
5342                                                     info_ptr, 0);
5343
5344           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5345           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5346         }
5347     }
5348
5349   /* Skip dummy compilation units.  */
5350   if (info_ptr >= begin_info_ptr + this_cu->length
5351       || peek_abbrev_code (abfd, info_ptr) == 0)
5352     {
5353       do_cleanups (cleanups);
5354       return;
5355     }
5356
5357   /* If we don't have them yet, read the abbrevs for this compilation unit.
5358      And if we need to read them now, make sure they're freed when we're
5359      done.  Note that it's important that if the CU had an abbrev table
5360      on entry we don't free it when we're done: Somewhere up the call stack
5361      it may be in use.  */
5362   if (abbrev_table != NULL)
5363     {
5364       gdb_assert (cu->abbrev_table == NULL);
5365       gdb_assert (cu->header.abbrev_offset.sect_off
5366                   == abbrev_table->offset.sect_off);
5367       cu->abbrev_table = abbrev_table;
5368     }
5369   else if (cu->abbrev_table == NULL)
5370     {
5371       dwarf2_read_abbrevs (cu, abbrev_section);
5372       make_cleanup (dwarf2_free_abbrev_table, cu);
5373     }
5374   else if (rereading_dwo_cu)
5375     {
5376       dwarf2_free_abbrev_table (cu);
5377       dwarf2_read_abbrevs (cu, abbrev_section);
5378     }
5379
5380   /* Read the top level CU/TU die.  */
5381   init_cu_die_reader (&reader, cu, section, NULL);
5382   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5383
5384   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5385      from the DWO file.
5386      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5387      DWO CU, that this test will fail (the attribute will not be present).  */
5388   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5389   if (attr)
5390     {
5391       struct dwo_unit *dwo_unit;
5392       struct die_info *dwo_comp_unit_die;
5393
5394       if (has_children)
5395         {
5396           complaint (&symfile_complaints,
5397                      _("compilation unit with DW_AT_GNU_dwo_name"
5398                        " has children (offset 0x%x) [in module %s]"),
5399                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5400         }
5401       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5402       if (dwo_unit != NULL)
5403         {
5404           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5405                                       abbrev_table != NULL,
5406                                       comp_unit_die, NULL,
5407                                       &reader, &info_ptr,
5408                                       &dwo_comp_unit_die, &has_children) == 0)
5409             {
5410               /* Dummy die.  */
5411               do_cleanups (cleanups);
5412               return;
5413             }
5414           comp_unit_die = dwo_comp_unit_die;
5415         }
5416       else
5417         {
5418           /* Yikes, we couldn't find the rest of the DIE, we only have
5419              the stub.  A complaint has already been logged.  There's
5420              not much more we can do except pass on the stub DIE to
5421              die_reader_func.  We don't want to throw an error on bad
5422              debug info.  */
5423         }
5424     }
5425
5426   /* All of the above is setup for this call.  Yikes.  */
5427   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5428
5429   /* Done, clean up.  */
5430   if (free_cu_cleanup != NULL)
5431     {
5432       if (keep)
5433         {
5434           /* We've successfully allocated this compilation unit.  Let our
5435              caller clean it up when finished with it.  */
5436           discard_cleanups (free_cu_cleanup);
5437
5438           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5439              So we have to manually free the abbrev table.  */
5440           dwarf2_free_abbrev_table (cu);
5441
5442           /* Link this CU into read_in_chain.  */
5443           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5444           dwarf2_per_objfile->read_in_chain = this_cu;
5445         }
5446       else
5447         do_cleanups (free_cu_cleanup);
5448     }
5449
5450   do_cleanups (cleanups);
5451 }
5452
5453 /* Read CU/TU THIS_CU in section SECTION,
5454    but do not follow DW_AT_GNU_dwo_name if present.
5455    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5456    to have already done the lookup to find the DWO/DWP file).
5457
5458    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5459    THIS_CU->is_debug_types, but nothing else.
5460
5461    We fill in THIS_CU->length.
5462
5463    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5464    linker) then DIE_READER_FUNC will not get called.
5465
5466    THIS_CU->cu is always freed when done.
5467    This is done in order to not leave THIS_CU->cu in a state where we have
5468    to care whether it refers to the "main" CU or the DWO CU.  */
5469
5470 static void
5471 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5472                                    struct dwarf2_section_info *abbrev_section,
5473                                    struct dwo_file *dwo_file,
5474                                    die_reader_func_ftype *die_reader_func,
5475                                    void *data)
5476 {
5477   struct objfile *objfile = dwarf2_per_objfile->objfile;
5478   struct dwarf2_section_info *section = this_cu->section;
5479   bfd *abfd = get_section_bfd_owner (section);
5480   struct dwarf2_cu cu;
5481   const gdb_byte *begin_info_ptr, *info_ptr;
5482   struct die_reader_specs reader;
5483   struct cleanup *cleanups;
5484   struct die_info *comp_unit_die;
5485   int has_children;
5486
5487   if (dwarf2_die_debug)
5488     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5489                         this_cu->is_debug_types ? "type" : "comp",
5490                         this_cu->offset.sect_off);
5491
5492   gdb_assert (this_cu->cu == NULL);
5493
5494   /* This is cheap if the section is already read in.  */
5495   dwarf2_read_section (objfile, section);
5496
5497   init_one_comp_unit (&cu, this_cu);
5498
5499   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5500
5501   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5502   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5503                                             abbrev_section, info_ptr,
5504                                             this_cu->is_debug_types);
5505
5506   this_cu->length = get_cu_length (&cu.header);
5507
5508   /* Skip dummy compilation units.  */
5509   if (info_ptr >= begin_info_ptr + this_cu->length
5510       || peek_abbrev_code (abfd, info_ptr) == 0)
5511     {
5512       do_cleanups (cleanups);
5513       return;
5514     }
5515
5516   dwarf2_read_abbrevs (&cu, abbrev_section);
5517   make_cleanup (dwarf2_free_abbrev_table, &cu);
5518
5519   init_cu_die_reader (&reader, &cu, section, dwo_file);
5520   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5521
5522   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5523
5524   do_cleanups (cleanups);
5525 }
5526
5527 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5528    does not lookup the specified DWO file.
5529    This cannot be used to read DWO files.
5530
5531    THIS_CU->cu is always freed when done.
5532    This is done in order to not leave THIS_CU->cu in a state where we have
5533    to care whether it refers to the "main" CU or the DWO CU.
5534    We can revisit this if the data shows there's a performance issue.  */
5535
5536 static void
5537 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5538                                 die_reader_func_ftype *die_reader_func,
5539                                 void *data)
5540 {
5541   init_cutu_and_read_dies_no_follow (this_cu,
5542                                      get_abbrev_section_for_cu (this_cu),
5543                                      NULL,
5544                                      die_reader_func, data);
5545 }
5546 \f
5547 /* Type Unit Groups.
5548
5549    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5550    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5551    so that all types coming from the same compilation (.o file) are grouped
5552    together.  A future step could be to put the types in the same symtab as
5553    the CU the types ultimately came from.  */
5554
5555 static hashval_t
5556 hash_type_unit_group (const void *item)
5557 {
5558   const struct type_unit_group *tu_group = item;
5559
5560   return hash_stmt_list_entry (&tu_group->hash);
5561 }
5562
5563 static int
5564 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5565 {
5566   const struct type_unit_group *lhs = item_lhs;
5567   const struct type_unit_group *rhs = item_rhs;
5568
5569   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5570 }
5571
5572 /* Allocate a hash table for type unit groups.  */
5573
5574 static htab_t
5575 allocate_type_unit_groups_table (void)
5576 {
5577   return htab_create_alloc_ex (3,
5578                                hash_type_unit_group,
5579                                eq_type_unit_group,
5580                                NULL,
5581                                &dwarf2_per_objfile->objfile->objfile_obstack,
5582                                hashtab_obstack_allocate,
5583                                dummy_obstack_deallocate);
5584 }
5585
5586 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5587    partial symtabs.  We combine several TUs per psymtab to not let the size
5588    of any one psymtab grow too big.  */
5589 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5590 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5591
5592 /* Helper routine for get_type_unit_group.
5593    Create the type_unit_group object used to hold one or more TUs.  */
5594
5595 static struct type_unit_group *
5596 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5597 {
5598   struct objfile *objfile = dwarf2_per_objfile->objfile;
5599   struct dwarf2_per_cu_data *per_cu;
5600   struct type_unit_group *tu_group;
5601
5602   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5603                              struct type_unit_group);
5604   per_cu = &tu_group->per_cu;
5605   per_cu->objfile = objfile;
5606
5607   if (dwarf2_per_objfile->using_index)
5608     {
5609       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5610                                         struct dwarf2_per_cu_quick_data);
5611     }
5612   else
5613     {
5614       unsigned int line_offset = line_offset_struct.sect_off;
5615       struct partial_symtab *pst;
5616       char *name;
5617
5618       /* Give the symtab a useful name for debug purposes.  */
5619       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5620         name = xstrprintf ("<type_units_%d>",
5621                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5622       else
5623         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5624
5625       pst = create_partial_symtab (per_cu, name);
5626       pst->anonymous = 1;
5627
5628       xfree (name);
5629     }
5630
5631   tu_group->hash.dwo_unit = cu->dwo_unit;
5632   tu_group->hash.line_offset = line_offset_struct;
5633
5634   return tu_group;
5635 }
5636
5637 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5638    STMT_LIST is a DW_AT_stmt_list attribute.  */
5639
5640 static struct type_unit_group *
5641 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5642 {
5643   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5644   struct type_unit_group *tu_group;
5645   void **slot;
5646   unsigned int line_offset;
5647   struct type_unit_group type_unit_group_for_lookup;
5648
5649   if (dwarf2_per_objfile->type_unit_groups == NULL)
5650     {
5651       dwarf2_per_objfile->type_unit_groups =
5652         allocate_type_unit_groups_table ();
5653     }
5654
5655   /* Do we need to create a new group, or can we use an existing one?  */
5656
5657   if (stmt_list)
5658     {
5659       line_offset = DW_UNSND (stmt_list);
5660       ++tu_stats->nr_symtab_sharers;
5661     }
5662   else
5663     {
5664       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5665          We can do various things here like create one group per TU or
5666          spread them over multiple groups to split up the expansion work.
5667          To avoid worst case scenarios (too many groups or too large groups)
5668          we, umm, group them in bunches.  */
5669       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5670                      | (tu_stats->nr_stmt_less_type_units
5671                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5672       ++tu_stats->nr_stmt_less_type_units;
5673     }
5674
5675   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5676   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5677   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5678                          &type_unit_group_for_lookup, INSERT);
5679   if (*slot != NULL)
5680     {
5681       tu_group = *slot;
5682       gdb_assert (tu_group != NULL);
5683     }
5684   else
5685     {
5686       sect_offset line_offset_struct;
5687
5688       line_offset_struct.sect_off = line_offset;
5689       tu_group = create_type_unit_group (cu, line_offset_struct);
5690       *slot = tu_group;
5691       ++tu_stats->nr_symtabs;
5692     }
5693
5694   return tu_group;
5695 }
5696
5697 /* Struct used to sort TUs by their abbreviation table offset.  */
5698
5699 struct tu_abbrev_offset
5700 {
5701   struct signatured_type *sig_type;
5702   sect_offset abbrev_offset;
5703 };
5704
5705 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5706
5707 static int
5708 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5709 {
5710   const struct tu_abbrev_offset * const *a = ap;
5711   const struct tu_abbrev_offset * const *b = bp;
5712   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5713   unsigned int boff = (*b)->abbrev_offset.sect_off;
5714
5715   return (aoff > boff) - (aoff < boff);
5716 }
5717
5718 /* A helper function to add a type_unit_group to a table.  */
5719
5720 static int
5721 add_type_unit_group_to_table (void **slot, void *datum)
5722 {
5723   struct type_unit_group *tu_group = *slot;
5724   struct type_unit_group ***datap = datum;
5725
5726   **datap = tu_group;
5727   ++*datap;
5728
5729   return 1;
5730 }
5731
5732 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5733    each one passing FUNC,DATA.
5734
5735    The efficiency is because we sort TUs by the abbrev table they use and
5736    only read each abbrev table once.  In one program there are 200K TUs
5737    sharing 8K abbrev tables.
5738
5739    The main purpose of this function is to support building the
5740    dwarf2_per_objfile->type_unit_groups table.
5741    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5742    can collapse the search space by grouping them by stmt_list.
5743    The savings can be significant, in the same program from above the 200K TUs
5744    share 8K stmt_list tables.
5745
5746    FUNC is expected to call get_type_unit_group, which will create the
5747    struct type_unit_group if necessary and add it to
5748    dwarf2_per_objfile->type_unit_groups.  */
5749
5750 static void
5751 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5752 {
5753   struct objfile *objfile = dwarf2_per_objfile->objfile;
5754   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5755   struct cleanup *cleanups;
5756   struct abbrev_table *abbrev_table;
5757   sect_offset abbrev_offset;
5758   struct tu_abbrev_offset *sorted_by_abbrev;
5759   struct type_unit_group **iter;
5760   int i;
5761
5762   /* It's up to the caller to not call us multiple times.  */
5763   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5764
5765   if (dwarf2_per_objfile->n_type_units == 0)
5766     return;
5767
5768   /* TUs typically share abbrev tables, and there can be way more TUs than
5769      abbrev tables.  Sort by abbrev table to reduce the number of times we
5770      read each abbrev table in.
5771      Alternatives are to punt or to maintain a cache of abbrev tables.
5772      This is simpler and efficient enough for now.
5773
5774      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5775      symtab to use).  Typically TUs with the same abbrev offset have the same
5776      stmt_list value too so in practice this should work well.
5777
5778      The basic algorithm here is:
5779
5780       sort TUs by abbrev table
5781       for each TU with same abbrev table:
5782         read abbrev table if first user
5783         read TU top level DIE
5784           [IWBN if DWO skeletons had DW_AT_stmt_list]
5785         call FUNC  */
5786
5787   if (dwarf2_read_debug)
5788     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5789
5790   /* Sort in a separate table to maintain the order of all_type_units
5791      for .gdb_index: TU indices directly index all_type_units.  */
5792   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5793                               dwarf2_per_objfile->n_type_units);
5794   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5795     {
5796       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5797
5798       sorted_by_abbrev[i].sig_type = sig_type;
5799       sorted_by_abbrev[i].abbrev_offset =
5800         read_abbrev_offset (sig_type->per_cu.section,
5801                             sig_type->per_cu.offset);
5802     }
5803   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5804   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5805          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5806
5807   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5808      called any number of times, so we don't reset tu_stats here.  */
5809
5810   abbrev_offset.sect_off = ~(unsigned) 0;
5811   abbrev_table = NULL;
5812   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5813
5814   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5815     {
5816       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5817
5818       /* Switch to the next abbrev table if necessary.  */
5819       if (abbrev_table == NULL
5820           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5821         {
5822           if (abbrev_table != NULL)
5823             {
5824               abbrev_table_free (abbrev_table);
5825               /* Reset to NULL in case abbrev_table_read_table throws
5826                  an error: abbrev_table_free_cleanup will get called.  */
5827               abbrev_table = NULL;
5828             }
5829           abbrev_offset = tu->abbrev_offset;
5830           abbrev_table =
5831             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5832                                      abbrev_offset);
5833           ++tu_stats->nr_uniq_abbrev_tables;
5834         }
5835
5836       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5837                                func, data);
5838     }
5839
5840   /* type_unit_groups can be NULL if there is an error in the debug info.
5841      Just create an empty table so the rest of gdb doesn't have to watch
5842      for this error case.  */
5843   if (dwarf2_per_objfile->type_unit_groups == NULL)
5844     {
5845       dwarf2_per_objfile->type_unit_groups =
5846         allocate_type_unit_groups_table ();
5847       dwarf2_per_objfile->n_type_unit_groups = 0;
5848     }
5849
5850   /* Create a vector of pointers to primary type units to make it easy to
5851      iterate over them and CUs.  See dw2_get_primary_cu.  */
5852   dwarf2_per_objfile->n_type_unit_groups =
5853     htab_elements (dwarf2_per_objfile->type_unit_groups);
5854   dwarf2_per_objfile->all_type_unit_groups =
5855     obstack_alloc (&objfile->objfile_obstack,
5856                    dwarf2_per_objfile->n_type_unit_groups
5857                    * sizeof (struct type_unit_group *));
5858   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5859   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5860                           add_type_unit_group_to_table, &iter);
5861   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5862               == dwarf2_per_objfile->n_type_unit_groups);
5863
5864   do_cleanups (cleanups);
5865
5866   if (dwarf2_read_debug)
5867     {
5868       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5869       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5870                           dwarf2_per_objfile->n_type_units);
5871       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5872                           tu_stats->nr_uniq_abbrev_tables);
5873       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5874                           tu_stats->nr_symtabs);
5875       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5876                           tu_stats->nr_symtab_sharers);
5877       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5878                           tu_stats->nr_stmt_less_type_units);
5879     }
5880 }
5881 \f
5882 /* Partial symbol tables.  */
5883
5884 /* Create a psymtab named NAME and assign it to PER_CU.
5885
5886    The caller must fill in the following details:
5887    dirname, textlow, texthigh.  */
5888
5889 static struct partial_symtab *
5890 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5891 {
5892   struct objfile *objfile = per_cu->objfile;
5893   struct partial_symtab *pst;
5894
5895   pst = start_psymtab_common (objfile, objfile->section_offsets,
5896                               name, 0,
5897                               objfile->global_psymbols.next,
5898                               objfile->static_psymbols.next);
5899
5900   pst->psymtabs_addrmap_supported = 1;
5901
5902   /* This is the glue that links PST into GDB's symbol API.  */
5903   pst->read_symtab_private = per_cu;
5904   pst->read_symtab = dwarf2_read_symtab;
5905   per_cu->v.psymtab = pst;
5906
5907   return pst;
5908 }
5909
5910 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5911    type.  */
5912
5913 struct process_psymtab_comp_unit_data
5914 {
5915   /* True if we are reading a DW_TAG_partial_unit.  */
5916
5917   int want_partial_unit;
5918
5919   /* The "pretend" language that is used if the CU doesn't declare a
5920      language.  */
5921
5922   enum language pretend_language;
5923 };
5924
5925 /* die_reader_func for process_psymtab_comp_unit.  */
5926
5927 static void
5928 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5929                                   const gdb_byte *info_ptr,
5930                                   struct die_info *comp_unit_die,
5931                                   int has_children,
5932                                   void *data)
5933 {
5934   struct dwarf2_cu *cu = reader->cu;
5935   struct objfile *objfile = cu->objfile;
5936   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5937   struct attribute *attr;
5938   CORE_ADDR baseaddr;
5939   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5940   struct partial_symtab *pst;
5941   int has_pc_info;
5942   const char *filename;
5943   struct process_psymtab_comp_unit_data *info = data;
5944
5945   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5946     return;
5947
5948   gdb_assert (! per_cu->is_debug_types);
5949
5950   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5951
5952   cu->list_in_scope = &file_symbols;
5953
5954   /* Allocate a new partial symbol table structure.  */
5955   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5956   if (attr == NULL || !DW_STRING (attr))
5957     filename = "";
5958   else
5959     filename = DW_STRING (attr);
5960
5961   pst = create_partial_symtab (per_cu, filename);
5962
5963   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5964   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5965   if (attr != NULL)
5966     pst->dirname = DW_STRING (attr);
5967
5968   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5969
5970   dwarf2_find_base_address (comp_unit_die, cu);
5971
5972   /* Possibly set the default values of LOWPC and HIGHPC from
5973      `DW_AT_ranges'.  */
5974   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5975                                       &best_highpc, cu, pst);
5976   if (has_pc_info == 1 && best_lowpc < best_highpc)
5977     /* Store the contiguous range if it is not empty; it can be empty for
5978        CUs with no code.  */
5979     addrmap_set_empty (objfile->psymtabs_addrmap,
5980                        best_lowpc + baseaddr,
5981                        best_highpc + baseaddr - 1, pst);
5982
5983   /* Check if comp unit has_children.
5984      If so, read the rest of the partial symbols from this comp unit.
5985      If not, there's no more debug_info for this comp unit.  */
5986   if (has_children)
5987     {
5988       struct partial_die_info *first_die;
5989       CORE_ADDR lowpc, highpc;
5990
5991       lowpc = ((CORE_ADDR) -1);
5992       highpc = ((CORE_ADDR) 0);
5993
5994       first_die = load_partial_dies (reader, info_ptr, 1);
5995
5996       scan_partial_symbols (first_die, &lowpc, &highpc,
5997                             ! has_pc_info, cu);
5998
5999       /* If we didn't find a lowpc, set it to highpc to avoid
6000          complaints from `maint check'.  */
6001       if (lowpc == ((CORE_ADDR) -1))
6002         lowpc = highpc;
6003
6004       /* If the compilation unit didn't have an explicit address range,
6005          then use the information extracted from its child dies.  */
6006       if (! has_pc_info)
6007         {
6008           best_lowpc = lowpc;
6009           best_highpc = highpc;
6010         }
6011     }
6012   pst->textlow = best_lowpc + baseaddr;
6013   pst->texthigh = best_highpc + baseaddr;
6014
6015   pst->n_global_syms = objfile->global_psymbols.next -
6016     (objfile->global_psymbols.list + pst->globals_offset);
6017   pst->n_static_syms = objfile->static_psymbols.next -
6018     (objfile->static_psymbols.list + pst->statics_offset);
6019   sort_pst_symbols (objfile, pst);
6020
6021   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6022     {
6023       int i;
6024       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6025       struct dwarf2_per_cu_data *iter;
6026
6027       /* Fill in 'dependencies' here; we fill in 'users' in a
6028          post-pass.  */
6029       pst->number_of_dependencies = len;
6030       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6031                                          len * sizeof (struct symtab *));
6032       for (i = 0;
6033            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6034                         i, iter);
6035            ++i)
6036         pst->dependencies[i] = iter->v.psymtab;
6037
6038       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6039     }
6040
6041   /* Get the list of files included in the current compilation unit,
6042      and build a psymtab for each of them.  */
6043   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6044
6045   if (dwarf2_read_debug)
6046     {
6047       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6048
6049       fprintf_unfiltered (gdb_stdlog,
6050                           "Psymtab for %s unit @0x%x: %s - %s"
6051                           ", %d global, %d static syms\n",
6052                           per_cu->is_debug_types ? "type" : "comp",
6053                           per_cu->offset.sect_off,
6054                           paddress (gdbarch, pst->textlow),
6055                           paddress (gdbarch, pst->texthigh),
6056                           pst->n_global_syms, pst->n_static_syms);
6057     }
6058 }
6059
6060 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6061    Process compilation unit THIS_CU for a psymtab.  */
6062
6063 static void
6064 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6065                            int want_partial_unit,
6066                            enum language pretend_language)
6067 {
6068   struct process_psymtab_comp_unit_data info;
6069
6070   /* If this compilation unit was already read in, free the
6071      cached copy in order to read it in again.  This is
6072      necessary because we skipped some symbols when we first
6073      read in the compilation unit (see load_partial_dies).
6074      This problem could be avoided, but the benefit is unclear.  */
6075   if (this_cu->cu != NULL)
6076     free_one_cached_comp_unit (this_cu);
6077
6078   gdb_assert (! this_cu->is_debug_types);
6079   info.want_partial_unit = want_partial_unit;
6080   info.pretend_language = pretend_language;
6081   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6082                            process_psymtab_comp_unit_reader,
6083                            &info);
6084
6085   /* Age out any secondary CUs.  */
6086   age_cached_comp_units ();
6087 }
6088
6089 /* Reader function for build_type_psymtabs.  */
6090
6091 static void
6092 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6093                             const gdb_byte *info_ptr,
6094                             struct die_info *type_unit_die,
6095                             int has_children,
6096                             void *data)
6097 {
6098   struct objfile *objfile = dwarf2_per_objfile->objfile;
6099   struct dwarf2_cu *cu = reader->cu;
6100   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6101   struct signatured_type *sig_type;
6102   struct type_unit_group *tu_group;
6103   struct attribute *attr;
6104   struct partial_die_info *first_die;
6105   CORE_ADDR lowpc, highpc;
6106   struct partial_symtab *pst;
6107
6108   gdb_assert (data == NULL);
6109   gdb_assert (per_cu->is_debug_types);
6110   sig_type = (struct signatured_type *) per_cu;
6111
6112   if (! has_children)
6113     return;
6114
6115   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6116   tu_group = get_type_unit_group (cu, attr);
6117
6118   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6119
6120   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6121   cu->list_in_scope = &file_symbols;
6122   pst = create_partial_symtab (per_cu, "");
6123   pst->anonymous = 1;
6124
6125   first_die = load_partial_dies (reader, info_ptr, 1);
6126
6127   lowpc = (CORE_ADDR) -1;
6128   highpc = (CORE_ADDR) 0;
6129   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6130
6131   pst->n_global_syms = objfile->global_psymbols.next -
6132     (objfile->global_psymbols.list + pst->globals_offset);
6133   pst->n_static_syms = objfile->static_psymbols.next -
6134     (objfile->static_psymbols.list + pst->statics_offset);
6135   sort_pst_symbols (objfile, pst);
6136 }
6137
6138 /* Traversal function for build_type_psymtabs.  */
6139
6140 static int
6141 build_type_psymtab_dependencies (void **slot, void *info)
6142 {
6143   struct objfile *objfile = dwarf2_per_objfile->objfile;
6144   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6145   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6146   struct partial_symtab *pst = per_cu->v.psymtab;
6147   int len = VEC_length (sig_type_ptr, tu_group->tus);
6148   struct signatured_type *iter;
6149   int i;
6150
6151   gdb_assert (len > 0);
6152   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6153
6154   pst->number_of_dependencies = len;
6155   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6156                                      len * sizeof (struct psymtab *));
6157   for (i = 0;
6158        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6159        ++i)
6160     {
6161       gdb_assert (iter->per_cu.is_debug_types);
6162       pst->dependencies[i] = iter->per_cu.v.psymtab;
6163       iter->type_unit_group = tu_group;
6164     }
6165
6166   VEC_free (sig_type_ptr, tu_group->tus);
6167
6168   return 1;
6169 }
6170
6171 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6172    Build partial symbol tables for the .debug_types comp-units.  */
6173
6174 static void
6175 build_type_psymtabs (struct objfile *objfile)
6176 {
6177   if (! create_all_type_units (objfile))
6178     return;
6179
6180   build_type_unit_groups (build_type_psymtabs_reader, NULL);
6181
6182   /* Now that all TUs have been processed we can fill in the dependencies.  */
6183   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6184                           build_type_psymtab_dependencies, NULL);
6185 }
6186
6187 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6188
6189 static void
6190 psymtabs_addrmap_cleanup (void *o)
6191 {
6192   struct objfile *objfile = o;
6193
6194   objfile->psymtabs_addrmap = NULL;
6195 }
6196
6197 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6198
6199 static void
6200 set_partial_user (struct objfile *objfile)
6201 {
6202   int i;
6203
6204   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6205     {
6206       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6207       struct partial_symtab *pst = per_cu->v.psymtab;
6208       int j;
6209
6210       if (pst == NULL)
6211         continue;
6212
6213       for (j = 0; j < pst->number_of_dependencies; ++j)
6214         {
6215           /* Set the 'user' field only if it is not already set.  */
6216           if (pst->dependencies[j]->user == NULL)
6217             pst->dependencies[j]->user = pst;
6218         }
6219     }
6220 }
6221
6222 /* Build the partial symbol table by doing a quick pass through the
6223    .debug_info and .debug_abbrev sections.  */
6224
6225 static void
6226 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6227 {
6228   struct cleanup *back_to, *addrmap_cleanup;
6229   struct obstack temp_obstack;
6230   int i;
6231
6232   if (dwarf2_read_debug)
6233     {
6234       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6235                           objfile_name (objfile));
6236     }
6237
6238   dwarf2_per_objfile->reading_partial_symbols = 1;
6239
6240   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6241
6242   /* Any cached compilation units will be linked by the per-objfile
6243      read_in_chain.  Make sure to free them when we're done.  */
6244   back_to = make_cleanup (free_cached_comp_units, NULL);
6245
6246   build_type_psymtabs (objfile);
6247
6248   create_all_comp_units (objfile);
6249
6250   /* Create a temporary address map on a temporary obstack.  We later
6251      copy this to the final obstack.  */
6252   obstack_init (&temp_obstack);
6253   make_cleanup_obstack_free (&temp_obstack);
6254   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6255   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6256
6257   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6258     {
6259       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6260
6261       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6262     }
6263
6264   set_partial_user (objfile);
6265
6266   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6267                                                     &objfile->objfile_obstack);
6268   discard_cleanups (addrmap_cleanup);
6269
6270   do_cleanups (back_to);
6271
6272   if (dwarf2_read_debug)
6273     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6274                         objfile_name (objfile));
6275 }
6276
6277 /* die_reader_func for load_partial_comp_unit.  */
6278
6279 static void
6280 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6281                                const gdb_byte *info_ptr,
6282                                struct die_info *comp_unit_die,
6283                                int has_children,
6284                                void *data)
6285 {
6286   struct dwarf2_cu *cu = reader->cu;
6287
6288   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6289
6290   /* Check if comp unit has_children.
6291      If so, read the rest of the partial symbols from this comp unit.
6292      If not, there's no more debug_info for this comp unit.  */
6293   if (has_children)
6294     load_partial_dies (reader, info_ptr, 0);
6295 }
6296
6297 /* Load the partial DIEs for a secondary CU into memory.
6298    This is also used when rereading a primary CU with load_all_dies.  */
6299
6300 static void
6301 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6302 {
6303   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6304                            load_partial_comp_unit_reader, NULL);
6305 }
6306
6307 static void
6308 read_comp_units_from_section (struct objfile *objfile,
6309                               struct dwarf2_section_info *section,
6310                               unsigned int is_dwz,
6311                               int *n_allocated,
6312                               int *n_comp_units,
6313                               struct dwarf2_per_cu_data ***all_comp_units)
6314 {
6315   const gdb_byte *info_ptr;
6316   bfd *abfd = get_section_bfd_owner (section);
6317
6318   if (dwarf2_read_debug)
6319     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6320                         get_section_name (section),
6321                         get_section_file_name (section));
6322
6323   dwarf2_read_section (objfile, section);
6324
6325   info_ptr = section->buffer;
6326
6327   while (info_ptr < section->buffer + section->size)
6328     {
6329       unsigned int length, initial_length_size;
6330       struct dwarf2_per_cu_data *this_cu;
6331       sect_offset offset;
6332
6333       offset.sect_off = info_ptr - section->buffer;
6334
6335       /* Read just enough information to find out where the next
6336          compilation unit is.  */
6337       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6338
6339       /* Save the compilation unit for later lookup.  */
6340       this_cu = obstack_alloc (&objfile->objfile_obstack,
6341                                sizeof (struct dwarf2_per_cu_data));
6342       memset (this_cu, 0, sizeof (*this_cu));
6343       this_cu->offset = offset;
6344       this_cu->length = length + initial_length_size;
6345       this_cu->is_dwz = is_dwz;
6346       this_cu->objfile = objfile;
6347       this_cu->section = section;
6348
6349       if (*n_comp_units == *n_allocated)
6350         {
6351           *n_allocated *= 2;
6352           *all_comp_units = xrealloc (*all_comp_units,
6353                                       *n_allocated
6354                                       * sizeof (struct dwarf2_per_cu_data *));
6355         }
6356       (*all_comp_units)[*n_comp_units] = this_cu;
6357       ++*n_comp_units;
6358
6359       info_ptr = info_ptr + this_cu->length;
6360     }
6361 }
6362
6363 /* Create a list of all compilation units in OBJFILE.
6364    This is only done for -readnow and building partial symtabs.  */
6365
6366 static void
6367 create_all_comp_units (struct objfile *objfile)
6368 {
6369   int n_allocated;
6370   int n_comp_units;
6371   struct dwarf2_per_cu_data **all_comp_units;
6372   struct dwz_file *dwz;
6373
6374   n_comp_units = 0;
6375   n_allocated = 10;
6376   all_comp_units = xmalloc (n_allocated
6377                             * sizeof (struct dwarf2_per_cu_data *));
6378
6379   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6380                                 &n_allocated, &n_comp_units, &all_comp_units);
6381
6382   dwz = dwarf2_get_dwz_file ();
6383   if (dwz != NULL)
6384     read_comp_units_from_section (objfile, &dwz->info, 1,
6385                                   &n_allocated, &n_comp_units,
6386                                   &all_comp_units);
6387
6388   dwarf2_per_objfile->all_comp_units
6389     = obstack_alloc (&objfile->objfile_obstack,
6390                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6391   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6392           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6393   xfree (all_comp_units);
6394   dwarf2_per_objfile->n_comp_units = n_comp_units;
6395 }
6396
6397 /* Process all loaded DIEs for compilation unit CU, starting at
6398    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6399    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6400    DW_AT_ranges).  If NEED_PC is set, then this function will set
6401    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6402    and record the covered ranges in the addrmap.  */
6403
6404 static void
6405 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6406                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6407 {
6408   struct partial_die_info *pdi;
6409
6410   /* Now, march along the PDI's, descending into ones which have
6411      interesting children but skipping the children of the other ones,
6412      until we reach the end of the compilation unit.  */
6413
6414   pdi = first_die;
6415
6416   while (pdi != NULL)
6417     {
6418       fixup_partial_die (pdi, cu);
6419
6420       /* Anonymous namespaces or modules have no name but have interesting
6421          children, so we need to look at them.  Ditto for anonymous
6422          enums.  */
6423
6424       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6425           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6426           || pdi->tag == DW_TAG_imported_unit)
6427         {
6428           switch (pdi->tag)
6429             {
6430             case DW_TAG_subprogram:
6431               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6432               break;
6433             case DW_TAG_constant:
6434             case DW_TAG_variable:
6435             case DW_TAG_typedef:
6436             case DW_TAG_union_type:
6437               if (!pdi->is_declaration)
6438                 {
6439                   add_partial_symbol (pdi, cu);
6440                 }
6441               break;
6442             case DW_TAG_class_type:
6443             case DW_TAG_interface_type:
6444             case DW_TAG_structure_type:
6445               if (!pdi->is_declaration)
6446                 {
6447                   add_partial_symbol (pdi, cu);
6448                 }
6449               break;
6450             case DW_TAG_enumeration_type:
6451               if (!pdi->is_declaration)
6452                 add_partial_enumeration (pdi, cu);
6453               break;
6454             case DW_TAG_base_type:
6455             case DW_TAG_subrange_type:
6456               /* File scope base type definitions are added to the partial
6457                  symbol table.  */
6458               add_partial_symbol (pdi, cu);
6459               break;
6460             case DW_TAG_namespace:
6461               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6462               break;
6463             case DW_TAG_module:
6464               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6465               break;
6466             case DW_TAG_imported_unit:
6467               {
6468                 struct dwarf2_per_cu_data *per_cu;
6469
6470                 /* For now we don't handle imported units in type units.  */
6471                 if (cu->per_cu->is_debug_types)
6472                   {
6473                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6474                              " supported in type units [in module %s]"),
6475                            objfile_name (cu->objfile));
6476                   }
6477
6478                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6479                                                            pdi->is_dwz,
6480                                                            cu->objfile);
6481
6482                 /* Go read the partial unit, if needed.  */
6483                 if (per_cu->v.psymtab == NULL)
6484                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6485
6486                 VEC_safe_push (dwarf2_per_cu_ptr,
6487                                cu->per_cu->imported_symtabs, per_cu);
6488               }
6489               break;
6490             default:
6491               break;
6492             }
6493         }
6494
6495       /* If the die has a sibling, skip to the sibling.  */
6496
6497       pdi = pdi->die_sibling;
6498     }
6499 }
6500
6501 /* Functions used to compute the fully scoped name of a partial DIE.
6502
6503    Normally, this is simple.  For C++, the parent DIE's fully scoped
6504    name is concatenated with "::" and the partial DIE's name.  For
6505    Java, the same thing occurs except that "." is used instead of "::".
6506    Enumerators are an exception; they use the scope of their parent
6507    enumeration type, i.e. the name of the enumeration type is not
6508    prepended to the enumerator.
6509
6510    There are two complexities.  One is DW_AT_specification; in this
6511    case "parent" means the parent of the target of the specification,
6512    instead of the direct parent of the DIE.  The other is compilers
6513    which do not emit DW_TAG_namespace; in this case we try to guess
6514    the fully qualified name of structure types from their members'
6515    linkage names.  This must be done using the DIE's children rather
6516    than the children of any DW_AT_specification target.  We only need
6517    to do this for structures at the top level, i.e. if the target of
6518    any DW_AT_specification (if any; otherwise the DIE itself) does not
6519    have a parent.  */
6520
6521 /* Compute the scope prefix associated with PDI's parent, in
6522    compilation unit CU.  The result will be allocated on CU's
6523    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6524    field.  NULL is returned if no prefix is necessary.  */
6525 static const char *
6526 partial_die_parent_scope (struct partial_die_info *pdi,
6527                           struct dwarf2_cu *cu)
6528 {
6529   const char *grandparent_scope;
6530   struct partial_die_info *parent, *real_pdi;
6531
6532   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6533      then this means the parent of the specification DIE.  */
6534
6535   real_pdi = pdi;
6536   while (real_pdi->has_specification)
6537     real_pdi = find_partial_die (real_pdi->spec_offset,
6538                                  real_pdi->spec_is_dwz, cu);
6539
6540   parent = real_pdi->die_parent;
6541   if (parent == NULL)
6542     return NULL;
6543
6544   if (parent->scope_set)
6545     return parent->scope;
6546
6547   fixup_partial_die (parent, cu);
6548
6549   grandparent_scope = partial_die_parent_scope (parent, cu);
6550
6551   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6552      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6553      Work around this problem here.  */
6554   if (cu->language == language_cplus
6555       && parent->tag == DW_TAG_namespace
6556       && strcmp (parent->name, "::") == 0
6557       && grandparent_scope == NULL)
6558     {
6559       parent->scope = NULL;
6560       parent->scope_set = 1;
6561       return NULL;
6562     }
6563
6564   if (pdi->tag == DW_TAG_enumerator)
6565     /* Enumerators should not get the name of the enumeration as a prefix.  */
6566     parent->scope = grandparent_scope;
6567   else if (parent->tag == DW_TAG_namespace
6568       || parent->tag == DW_TAG_module
6569       || parent->tag == DW_TAG_structure_type
6570       || parent->tag == DW_TAG_class_type
6571       || parent->tag == DW_TAG_interface_type
6572       || parent->tag == DW_TAG_union_type
6573       || parent->tag == DW_TAG_enumeration_type)
6574     {
6575       if (grandparent_scope == NULL)
6576         parent->scope = parent->name;
6577       else
6578         parent->scope = typename_concat (&cu->comp_unit_obstack,
6579                                          grandparent_scope,
6580                                          parent->name, 0, cu);
6581     }
6582   else
6583     {
6584       /* FIXME drow/2004-04-01: What should we be doing with
6585          function-local names?  For partial symbols, we should probably be
6586          ignoring them.  */
6587       complaint (&symfile_complaints,
6588                  _("unhandled containing DIE tag %d for DIE at %d"),
6589                  parent->tag, pdi->offset.sect_off);
6590       parent->scope = grandparent_scope;
6591     }
6592
6593   parent->scope_set = 1;
6594   return parent->scope;
6595 }
6596
6597 /* Return the fully scoped name associated with PDI, from compilation unit
6598    CU.  The result will be allocated with malloc.  */
6599
6600 static char *
6601 partial_die_full_name (struct partial_die_info *pdi,
6602                        struct dwarf2_cu *cu)
6603 {
6604   const char *parent_scope;
6605
6606   /* If this is a template instantiation, we can not work out the
6607      template arguments from partial DIEs.  So, unfortunately, we have
6608      to go through the full DIEs.  At least any work we do building
6609      types here will be reused if full symbols are loaded later.  */
6610   if (pdi->has_template_arguments)
6611     {
6612       fixup_partial_die (pdi, cu);
6613
6614       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6615         {
6616           struct die_info *die;
6617           struct attribute attr;
6618           struct dwarf2_cu *ref_cu = cu;
6619
6620           /* DW_FORM_ref_addr is using section offset.  */
6621           attr.name = 0;
6622           attr.form = DW_FORM_ref_addr;
6623           attr.u.unsnd = pdi->offset.sect_off;
6624           die = follow_die_ref (NULL, &attr, &ref_cu);
6625
6626           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6627         }
6628     }
6629
6630   parent_scope = partial_die_parent_scope (pdi, cu);
6631   if (parent_scope == NULL)
6632     return NULL;
6633   else
6634     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6635 }
6636
6637 static void
6638 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6639 {
6640   struct objfile *objfile = cu->objfile;
6641   CORE_ADDR addr = 0;
6642   const char *actual_name = NULL;
6643   CORE_ADDR baseaddr;
6644   char *built_actual_name;
6645
6646   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6647
6648   built_actual_name = partial_die_full_name (pdi, cu);
6649   if (built_actual_name != NULL)
6650     actual_name = built_actual_name;
6651
6652   if (actual_name == NULL)
6653     actual_name = pdi->name;
6654
6655   switch (pdi->tag)
6656     {
6657     case DW_TAG_subprogram:
6658       if (pdi->is_external || cu->language == language_ada)
6659         {
6660           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6661              of the global scope.  But in Ada, we want to be able to access
6662              nested procedures globally.  So all Ada subprograms are stored
6663              in the global scope.  */
6664           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6665              mst_text, objfile); */
6666           add_psymbol_to_list (actual_name, strlen (actual_name),
6667                                built_actual_name != NULL,
6668                                VAR_DOMAIN, LOC_BLOCK,
6669                                &objfile->global_psymbols,
6670                                0, pdi->lowpc + baseaddr,
6671                                cu->language, objfile);
6672         }
6673       else
6674         {
6675           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6676              mst_file_text, objfile); */
6677           add_psymbol_to_list (actual_name, strlen (actual_name),
6678                                built_actual_name != NULL,
6679                                VAR_DOMAIN, LOC_BLOCK,
6680                                &objfile->static_psymbols,
6681                                0, pdi->lowpc + baseaddr,
6682                                cu->language, objfile);
6683         }
6684       break;
6685     case DW_TAG_constant:
6686       {
6687         struct psymbol_allocation_list *list;
6688
6689         if (pdi->is_external)
6690           list = &objfile->global_psymbols;
6691         else
6692           list = &objfile->static_psymbols;
6693         add_psymbol_to_list (actual_name, strlen (actual_name),
6694                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6695                              list, 0, 0, cu->language, objfile);
6696       }
6697       break;
6698     case DW_TAG_variable:
6699       if (pdi->d.locdesc)
6700         addr = decode_locdesc (pdi->d.locdesc, cu);
6701
6702       if (pdi->d.locdesc
6703           && addr == 0
6704           && !dwarf2_per_objfile->has_section_at_zero)
6705         {
6706           /* A global or static variable may also have been stripped
6707              out by the linker if unused, in which case its address
6708              will be nullified; do not add such variables into partial
6709              symbol table then.  */
6710         }
6711       else if (pdi->is_external)
6712         {
6713           /* Global Variable.
6714              Don't enter into the minimal symbol tables as there is
6715              a minimal symbol table entry from the ELF symbols already.
6716              Enter into partial symbol table if it has a location
6717              descriptor or a type.
6718              If the location descriptor is missing, new_symbol will create
6719              a LOC_UNRESOLVED symbol, the address of the variable will then
6720              be determined from the minimal symbol table whenever the variable
6721              is referenced.
6722              The address for the partial symbol table entry is not
6723              used by GDB, but it comes in handy for debugging partial symbol
6724              table building.  */
6725
6726           if (pdi->d.locdesc || pdi->has_type)
6727             add_psymbol_to_list (actual_name, strlen (actual_name),
6728                                  built_actual_name != NULL,
6729                                  VAR_DOMAIN, LOC_STATIC,
6730                                  &objfile->global_psymbols,
6731                                  0, addr + baseaddr,
6732                                  cu->language, objfile);
6733         }
6734       else
6735         {
6736           /* Static Variable.  Skip symbols without location descriptors.  */
6737           if (pdi->d.locdesc == NULL)
6738             {
6739               xfree (built_actual_name);
6740               return;
6741             }
6742           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6743              mst_file_data, objfile); */
6744           add_psymbol_to_list (actual_name, strlen (actual_name),
6745                                built_actual_name != NULL,
6746                                VAR_DOMAIN, LOC_STATIC,
6747                                &objfile->static_psymbols,
6748                                0, addr + baseaddr,
6749                                cu->language, objfile);
6750         }
6751       break;
6752     case DW_TAG_typedef:
6753     case DW_TAG_base_type:
6754     case DW_TAG_subrange_type:
6755       add_psymbol_to_list (actual_name, strlen (actual_name),
6756                            built_actual_name != NULL,
6757                            VAR_DOMAIN, LOC_TYPEDEF,
6758                            &objfile->static_psymbols,
6759                            0, (CORE_ADDR) 0, cu->language, objfile);
6760       break;
6761     case DW_TAG_namespace:
6762       add_psymbol_to_list (actual_name, strlen (actual_name),
6763                            built_actual_name != NULL,
6764                            VAR_DOMAIN, LOC_TYPEDEF,
6765                            &objfile->global_psymbols,
6766                            0, (CORE_ADDR) 0, cu->language, objfile);
6767       break;
6768     case DW_TAG_class_type:
6769     case DW_TAG_interface_type:
6770     case DW_TAG_structure_type:
6771     case DW_TAG_union_type:
6772     case DW_TAG_enumeration_type:
6773       /* Skip external references.  The DWARF standard says in the section
6774          about "Structure, Union, and Class Type Entries": "An incomplete
6775          structure, union or class type is represented by a structure,
6776          union or class entry that does not have a byte size attribute
6777          and that has a DW_AT_declaration attribute."  */
6778       if (!pdi->has_byte_size && pdi->is_declaration)
6779         {
6780           xfree (built_actual_name);
6781           return;
6782         }
6783
6784       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6785          static vs. global.  */
6786       add_psymbol_to_list (actual_name, strlen (actual_name),
6787                            built_actual_name != NULL,
6788                            STRUCT_DOMAIN, LOC_TYPEDEF,
6789                            (cu->language == language_cplus
6790                             || cu->language == language_java)
6791                            ? &objfile->global_psymbols
6792                            : &objfile->static_psymbols,
6793                            0, (CORE_ADDR) 0, cu->language, objfile);
6794
6795       break;
6796     case DW_TAG_enumerator:
6797       add_psymbol_to_list (actual_name, strlen (actual_name),
6798                            built_actual_name != NULL,
6799                            VAR_DOMAIN, LOC_CONST,
6800                            (cu->language == language_cplus
6801                             || cu->language == language_java)
6802                            ? &objfile->global_psymbols
6803                            : &objfile->static_psymbols,
6804                            0, (CORE_ADDR) 0, cu->language, objfile);
6805       break;
6806     default:
6807       break;
6808     }
6809
6810   xfree (built_actual_name);
6811 }
6812
6813 /* Read a partial die corresponding to a namespace; also, add a symbol
6814    corresponding to that namespace to the symbol table.  NAMESPACE is
6815    the name of the enclosing namespace.  */
6816
6817 static void
6818 add_partial_namespace (struct partial_die_info *pdi,
6819                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6820                        int need_pc, struct dwarf2_cu *cu)
6821 {
6822   /* Add a symbol for the namespace.  */
6823
6824   add_partial_symbol (pdi, cu);
6825
6826   /* Now scan partial symbols in that namespace.  */
6827
6828   if (pdi->has_children)
6829     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6830 }
6831
6832 /* Read a partial die corresponding to a Fortran module.  */
6833
6834 static void
6835 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6836                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6837 {
6838   /* Now scan partial symbols in that module.  */
6839
6840   if (pdi->has_children)
6841     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6842 }
6843
6844 /* Read a partial die corresponding to a subprogram and create a partial
6845    symbol for that subprogram.  When the CU language allows it, this
6846    routine also defines a partial symbol for each nested subprogram
6847    that this subprogram contains.
6848
6849    DIE my also be a lexical block, in which case we simply search
6850    recursively for suprograms defined inside that lexical block.
6851    Again, this is only performed when the CU language allows this
6852    type of definitions.  */
6853
6854 static void
6855 add_partial_subprogram (struct partial_die_info *pdi,
6856                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6857                         int need_pc, struct dwarf2_cu *cu)
6858 {
6859   if (pdi->tag == DW_TAG_subprogram)
6860     {
6861       if (pdi->has_pc_info)
6862         {
6863           if (pdi->lowpc < *lowpc)
6864             *lowpc = pdi->lowpc;
6865           if (pdi->highpc > *highpc)
6866             *highpc = pdi->highpc;
6867           if (need_pc)
6868             {
6869               CORE_ADDR baseaddr;
6870               struct objfile *objfile = cu->objfile;
6871
6872               baseaddr = ANOFFSET (objfile->section_offsets,
6873                                    SECT_OFF_TEXT (objfile));
6874               addrmap_set_empty (objfile->psymtabs_addrmap,
6875                                  pdi->lowpc + baseaddr,
6876                                  pdi->highpc - 1 + baseaddr,
6877                                  cu->per_cu->v.psymtab);
6878             }
6879         }
6880
6881       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6882         {
6883           if (!pdi->is_declaration)
6884             /* Ignore subprogram DIEs that do not have a name, they are
6885                illegal.  Do not emit a complaint at this point, we will
6886                do so when we convert this psymtab into a symtab.  */
6887             if (pdi->name)
6888               add_partial_symbol (pdi, cu);
6889         }
6890     }
6891
6892   if (! pdi->has_children)
6893     return;
6894
6895   if (cu->language == language_ada)
6896     {
6897       pdi = pdi->die_child;
6898       while (pdi != NULL)
6899         {
6900           fixup_partial_die (pdi, cu);
6901           if (pdi->tag == DW_TAG_subprogram
6902               || pdi->tag == DW_TAG_lexical_block)
6903             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6904           pdi = pdi->die_sibling;
6905         }
6906     }
6907 }
6908
6909 /* Read a partial die corresponding to an enumeration type.  */
6910
6911 static void
6912 add_partial_enumeration (struct partial_die_info *enum_pdi,
6913                          struct dwarf2_cu *cu)
6914 {
6915   struct partial_die_info *pdi;
6916
6917   if (enum_pdi->name != NULL)
6918     add_partial_symbol (enum_pdi, cu);
6919
6920   pdi = enum_pdi->die_child;
6921   while (pdi)
6922     {
6923       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6924         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6925       else
6926         add_partial_symbol (pdi, cu);
6927       pdi = pdi->die_sibling;
6928     }
6929 }
6930
6931 /* Return the initial uleb128 in the die at INFO_PTR.  */
6932
6933 static unsigned int
6934 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6935 {
6936   unsigned int bytes_read;
6937
6938   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6939 }
6940
6941 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6942    Return the corresponding abbrev, or NULL if the number is zero (indicating
6943    an empty DIE).  In either case *BYTES_READ will be set to the length of
6944    the initial number.  */
6945
6946 static struct abbrev_info *
6947 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6948                  struct dwarf2_cu *cu)
6949 {
6950   bfd *abfd = cu->objfile->obfd;
6951   unsigned int abbrev_number;
6952   struct abbrev_info *abbrev;
6953
6954   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6955
6956   if (abbrev_number == 0)
6957     return NULL;
6958
6959   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6960   if (!abbrev)
6961     {
6962       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6963              abbrev_number, bfd_get_filename (abfd));
6964     }
6965
6966   return abbrev;
6967 }
6968
6969 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6970    Returns a pointer to the end of a series of DIEs, terminated by an empty
6971    DIE.  Any children of the skipped DIEs will also be skipped.  */
6972
6973 static const gdb_byte *
6974 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6975 {
6976   struct dwarf2_cu *cu = reader->cu;
6977   struct abbrev_info *abbrev;
6978   unsigned int bytes_read;
6979
6980   while (1)
6981     {
6982       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6983       if (abbrev == NULL)
6984         return info_ptr + bytes_read;
6985       else
6986         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6987     }
6988 }
6989
6990 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6991    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6992    abbrev corresponding to that skipped uleb128 should be passed in
6993    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6994    children.  */
6995
6996 static const gdb_byte *
6997 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6998               struct abbrev_info *abbrev)
6999 {
7000   unsigned int bytes_read;
7001   struct attribute attr;
7002   bfd *abfd = reader->abfd;
7003   struct dwarf2_cu *cu = reader->cu;
7004   const gdb_byte *buffer = reader->buffer;
7005   const gdb_byte *buffer_end = reader->buffer_end;
7006   const gdb_byte *start_info_ptr = info_ptr;
7007   unsigned int form, i;
7008
7009   for (i = 0; i < abbrev->num_attrs; i++)
7010     {
7011       /* The only abbrev we care about is DW_AT_sibling.  */
7012       if (abbrev->attrs[i].name == DW_AT_sibling)
7013         {
7014           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7015           if (attr.form == DW_FORM_ref_addr)
7016             complaint (&symfile_complaints,
7017                        _("ignoring absolute DW_AT_sibling"));
7018           else
7019             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
7020         }
7021
7022       /* If it isn't DW_AT_sibling, skip this attribute.  */
7023       form = abbrev->attrs[i].form;
7024     skip_attribute:
7025       switch (form)
7026         {
7027         case DW_FORM_ref_addr:
7028           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7029              and later it is offset sized.  */
7030           if (cu->header.version == 2)
7031             info_ptr += cu->header.addr_size;
7032           else
7033             info_ptr += cu->header.offset_size;
7034           break;
7035         case DW_FORM_GNU_ref_alt:
7036           info_ptr += cu->header.offset_size;
7037           break;
7038         case DW_FORM_addr:
7039           info_ptr += cu->header.addr_size;
7040           break;
7041         case DW_FORM_data1:
7042         case DW_FORM_ref1:
7043         case DW_FORM_flag:
7044           info_ptr += 1;
7045           break;
7046         case DW_FORM_flag_present:
7047           break;
7048         case DW_FORM_data2:
7049         case DW_FORM_ref2:
7050           info_ptr += 2;
7051           break;
7052         case DW_FORM_data4:
7053         case DW_FORM_ref4:
7054           info_ptr += 4;
7055           break;
7056         case DW_FORM_data8:
7057         case DW_FORM_ref8:
7058         case DW_FORM_ref_sig8:
7059           info_ptr += 8;
7060           break;
7061         case DW_FORM_string:
7062           read_direct_string (abfd, info_ptr, &bytes_read);
7063           info_ptr += bytes_read;
7064           break;
7065         case DW_FORM_sec_offset:
7066         case DW_FORM_strp:
7067         case DW_FORM_GNU_strp_alt:
7068           info_ptr += cu->header.offset_size;
7069           break;
7070         case DW_FORM_exprloc:
7071         case DW_FORM_block:
7072           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7073           info_ptr += bytes_read;
7074           break;
7075         case DW_FORM_block1:
7076           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7077           break;
7078         case DW_FORM_block2:
7079           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7080           break;
7081         case DW_FORM_block4:
7082           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7083           break;
7084         case DW_FORM_sdata:
7085         case DW_FORM_udata:
7086         case DW_FORM_ref_udata:
7087         case DW_FORM_GNU_addr_index:
7088         case DW_FORM_GNU_str_index:
7089           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7090           break;
7091         case DW_FORM_indirect:
7092           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7093           info_ptr += bytes_read;
7094           /* We need to continue parsing from here, so just go back to
7095              the top.  */
7096           goto skip_attribute;
7097
7098         default:
7099           error (_("Dwarf Error: Cannot handle %s "
7100                    "in DWARF reader [in module %s]"),
7101                  dwarf_form_name (form),
7102                  bfd_get_filename (abfd));
7103         }
7104     }
7105
7106   if (abbrev->has_children)
7107     return skip_children (reader, info_ptr);
7108   else
7109     return info_ptr;
7110 }
7111
7112 /* Locate ORIG_PDI's sibling.
7113    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7114
7115 static const gdb_byte *
7116 locate_pdi_sibling (const struct die_reader_specs *reader,
7117                     struct partial_die_info *orig_pdi,
7118                     const gdb_byte *info_ptr)
7119 {
7120   /* Do we know the sibling already?  */
7121
7122   if (orig_pdi->sibling)
7123     return orig_pdi->sibling;
7124
7125   /* Are there any children to deal with?  */
7126
7127   if (!orig_pdi->has_children)
7128     return info_ptr;
7129
7130   /* Skip the children the long way.  */
7131
7132   return skip_children (reader, info_ptr);
7133 }
7134
7135 /* Expand this partial symbol table into a full symbol table.  SELF is
7136    not NULL.  */
7137
7138 static void
7139 dwarf2_read_symtab (struct partial_symtab *self,
7140                     struct objfile *objfile)
7141 {
7142   if (self->readin)
7143     {
7144       warning (_("bug: psymtab for %s is already read in."),
7145                self->filename);
7146     }
7147   else
7148     {
7149       if (info_verbose)
7150         {
7151           printf_filtered (_("Reading in symbols for %s..."),
7152                            self->filename);
7153           gdb_flush (gdb_stdout);
7154         }
7155
7156       /* Restore our global data.  */
7157       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
7158
7159       /* If this psymtab is constructed from a debug-only objfile, the
7160          has_section_at_zero flag will not necessarily be correct.  We
7161          can get the correct value for this flag by looking at the data
7162          associated with the (presumably stripped) associated objfile.  */
7163       if (objfile->separate_debug_objfile_backlink)
7164         {
7165           struct dwarf2_per_objfile *dpo_backlink
7166             = objfile_data (objfile->separate_debug_objfile_backlink,
7167                             dwarf2_objfile_data_key);
7168
7169           dwarf2_per_objfile->has_section_at_zero
7170             = dpo_backlink->has_section_at_zero;
7171         }
7172
7173       dwarf2_per_objfile->reading_partial_symbols = 0;
7174
7175       psymtab_to_symtab_1 (self);
7176
7177       /* Finish up the debug error message.  */
7178       if (info_verbose)
7179         printf_filtered (_("done.\n"));
7180     }
7181
7182   process_cu_includes ();
7183 }
7184 \f
7185 /* Reading in full CUs.  */
7186
7187 /* Add PER_CU to the queue.  */
7188
7189 static void
7190 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7191                  enum language pretend_language)
7192 {
7193   struct dwarf2_queue_item *item;
7194
7195   per_cu->queued = 1;
7196   item = xmalloc (sizeof (*item));
7197   item->per_cu = per_cu;
7198   item->pretend_language = pretend_language;
7199   item->next = NULL;
7200
7201   if (dwarf2_queue == NULL)
7202     dwarf2_queue = item;
7203   else
7204     dwarf2_queue_tail->next = item;
7205
7206   dwarf2_queue_tail = item;
7207 }
7208
7209 /* If PER_CU is not yet queued, add it to the queue.
7210    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7211    dependency.
7212    The result is non-zero if PER_CU was queued, otherwise the result is zero
7213    meaning either PER_CU is already queued or it is already loaded.
7214
7215    N.B. There is an invariant here that if a CU is queued then it is loaded.
7216    The caller is required to load PER_CU if we return non-zero.  */
7217
7218 static int
7219 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7220                        struct dwarf2_per_cu_data *per_cu,
7221                        enum language pretend_language)
7222 {
7223   /* We may arrive here during partial symbol reading, if we need full
7224      DIEs to process an unusual case (e.g. template arguments).  Do
7225      not queue PER_CU, just tell our caller to load its DIEs.  */
7226   if (dwarf2_per_objfile->reading_partial_symbols)
7227     {
7228       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7229         return 1;
7230       return 0;
7231     }
7232
7233   /* Mark the dependence relation so that we don't flush PER_CU
7234      too early.  */
7235   if (dependent_cu != NULL)
7236     dwarf2_add_dependence (dependent_cu, per_cu);
7237
7238   /* If it's already on the queue, we have nothing to do.  */
7239   if (per_cu->queued)
7240     return 0;
7241
7242   /* If the compilation unit is already loaded, just mark it as
7243      used.  */
7244   if (per_cu->cu != NULL)
7245     {
7246       per_cu->cu->last_used = 0;
7247       return 0;
7248     }
7249
7250   /* Add it to the queue.  */
7251   queue_comp_unit (per_cu, pretend_language);
7252
7253   return 1;
7254 }
7255
7256 /* Process the queue.  */
7257
7258 static void
7259 process_queue (void)
7260 {
7261   struct dwarf2_queue_item *item, *next_item;
7262
7263   if (dwarf2_read_debug)
7264     {
7265       fprintf_unfiltered (gdb_stdlog,
7266                           "Expanding one or more symtabs of objfile %s ...\n",
7267                           objfile_name (dwarf2_per_objfile->objfile));
7268     }
7269
7270   /* The queue starts out with one item, but following a DIE reference
7271      may load a new CU, adding it to the end of the queue.  */
7272   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7273     {
7274       if (dwarf2_per_objfile->using_index
7275           ? !item->per_cu->v.quick->symtab
7276           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7277         {
7278           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7279           char buf[100];
7280
7281           if (per_cu->is_debug_types)
7282             {
7283               struct signatured_type *sig_type =
7284                 (struct signatured_type *) per_cu;
7285
7286               sprintf (buf, "TU %s at offset 0x%x",
7287                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7288             }
7289           else
7290             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7291
7292           if (dwarf2_read_debug)
7293             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7294
7295           if (per_cu->is_debug_types)
7296             process_full_type_unit (per_cu, item->pretend_language);
7297           else
7298             process_full_comp_unit (per_cu, item->pretend_language);
7299
7300           if (dwarf2_read_debug)
7301             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7302         }
7303
7304       item->per_cu->queued = 0;
7305       next_item = item->next;
7306       xfree (item);
7307     }
7308
7309   dwarf2_queue_tail = NULL;
7310
7311   if (dwarf2_read_debug)
7312     {
7313       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7314                           objfile_name (dwarf2_per_objfile->objfile));
7315     }
7316 }
7317
7318 /* Free all allocated queue entries.  This function only releases anything if
7319    an error was thrown; if the queue was processed then it would have been
7320    freed as we went along.  */
7321
7322 static void
7323 dwarf2_release_queue (void *dummy)
7324 {
7325   struct dwarf2_queue_item *item, *last;
7326
7327   item = dwarf2_queue;
7328   while (item)
7329     {
7330       /* Anything still marked queued is likely to be in an
7331          inconsistent state, so discard it.  */
7332       if (item->per_cu->queued)
7333         {
7334           if (item->per_cu->cu != NULL)
7335             free_one_cached_comp_unit (item->per_cu);
7336           item->per_cu->queued = 0;
7337         }
7338
7339       last = item;
7340       item = item->next;
7341       xfree (last);
7342     }
7343
7344   dwarf2_queue = dwarf2_queue_tail = NULL;
7345 }
7346
7347 /* Read in full symbols for PST, and anything it depends on.  */
7348
7349 static void
7350 psymtab_to_symtab_1 (struct partial_symtab *pst)
7351 {
7352   struct dwarf2_per_cu_data *per_cu;
7353   int i;
7354
7355   if (pst->readin)
7356     return;
7357
7358   for (i = 0; i < pst->number_of_dependencies; i++)
7359     if (!pst->dependencies[i]->readin
7360         && pst->dependencies[i]->user == NULL)
7361       {
7362         /* Inform about additional files that need to be read in.  */
7363         if (info_verbose)
7364           {
7365             /* FIXME: i18n: Need to make this a single string.  */
7366             fputs_filtered (" ", gdb_stdout);
7367             wrap_here ("");
7368             fputs_filtered ("and ", gdb_stdout);
7369             wrap_here ("");
7370             printf_filtered ("%s...", pst->dependencies[i]->filename);
7371             wrap_here ("");     /* Flush output.  */
7372             gdb_flush (gdb_stdout);
7373           }
7374         psymtab_to_symtab_1 (pst->dependencies[i]);
7375       }
7376
7377   per_cu = pst->read_symtab_private;
7378
7379   if (per_cu == NULL)
7380     {
7381       /* It's an include file, no symbols to read for it.
7382          Everything is in the parent symtab.  */
7383       pst->readin = 1;
7384       return;
7385     }
7386
7387   dw2_do_instantiate_symtab (per_cu);
7388 }
7389
7390 /* Trivial hash function for die_info: the hash value of a DIE
7391    is its offset in .debug_info for this objfile.  */
7392
7393 static hashval_t
7394 die_hash (const void *item)
7395 {
7396   const struct die_info *die = item;
7397
7398   return die->offset.sect_off;
7399 }
7400
7401 /* Trivial comparison function for die_info structures: two DIEs
7402    are equal if they have the same offset.  */
7403
7404 static int
7405 die_eq (const void *item_lhs, const void *item_rhs)
7406 {
7407   const struct die_info *die_lhs = item_lhs;
7408   const struct die_info *die_rhs = item_rhs;
7409
7410   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7411 }
7412
7413 /* die_reader_func for load_full_comp_unit.
7414    This is identical to read_signatured_type_reader,
7415    but is kept separate for now.  */
7416
7417 static void
7418 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7419                             const gdb_byte *info_ptr,
7420                             struct die_info *comp_unit_die,
7421                             int has_children,
7422                             void *data)
7423 {
7424   struct dwarf2_cu *cu = reader->cu;
7425   enum language *language_ptr = data;
7426
7427   gdb_assert (cu->die_hash == NULL);
7428   cu->die_hash =
7429     htab_create_alloc_ex (cu->header.length / 12,
7430                           die_hash,
7431                           die_eq,
7432                           NULL,
7433                           &cu->comp_unit_obstack,
7434                           hashtab_obstack_allocate,
7435                           dummy_obstack_deallocate);
7436
7437   if (has_children)
7438     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7439                                                   &info_ptr, comp_unit_die);
7440   cu->dies = comp_unit_die;
7441   /* comp_unit_die is not stored in die_hash, no need.  */
7442
7443   /* We try not to read any attributes in this function, because not
7444      all CUs needed for references have been loaded yet, and symbol
7445      table processing isn't initialized.  But we have to set the CU language,
7446      or we won't be able to build types correctly.
7447      Similarly, if we do not read the producer, we can not apply
7448      producer-specific interpretation.  */
7449   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7450 }
7451
7452 /* Load the DIEs associated with PER_CU into memory.  */
7453
7454 static void
7455 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7456                      enum language pretend_language)
7457 {
7458   gdb_assert (! this_cu->is_debug_types);
7459
7460   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7461                            load_full_comp_unit_reader, &pretend_language);
7462 }
7463
7464 /* Add a DIE to the delayed physname list.  */
7465
7466 static void
7467 add_to_method_list (struct type *type, int fnfield_index, int index,
7468                     const char *name, struct die_info *die,
7469                     struct dwarf2_cu *cu)
7470 {
7471   struct delayed_method_info mi;
7472   mi.type = type;
7473   mi.fnfield_index = fnfield_index;
7474   mi.index = index;
7475   mi.name = name;
7476   mi.die = die;
7477   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7478 }
7479
7480 /* A cleanup for freeing the delayed method list.  */
7481
7482 static void
7483 free_delayed_list (void *ptr)
7484 {
7485   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7486   if (cu->method_list != NULL)
7487     {
7488       VEC_free (delayed_method_info, cu->method_list);
7489       cu->method_list = NULL;
7490     }
7491 }
7492
7493 /* Compute the physnames of any methods on the CU's method list.
7494
7495    The computation of method physnames is delayed in order to avoid the
7496    (bad) condition that one of the method's formal parameters is of an as yet
7497    incomplete type.  */
7498
7499 static void
7500 compute_delayed_physnames (struct dwarf2_cu *cu)
7501 {
7502   int i;
7503   struct delayed_method_info *mi;
7504   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7505     {
7506       const char *physname;
7507       struct fn_fieldlist *fn_flp
7508         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7509       physname = dwarf2_physname (mi->name, mi->die, cu);
7510       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7511     }
7512 }
7513
7514 /* Go objects should be embedded in a DW_TAG_module DIE,
7515    and it's not clear if/how imported objects will appear.
7516    To keep Go support simple until that's worked out,
7517    go back through what we've read and create something usable.
7518    We could do this while processing each DIE, and feels kinda cleaner,
7519    but that way is more invasive.
7520    This is to, for example, allow the user to type "p var" or "b main"
7521    without having to specify the package name, and allow lookups
7522    of module.object to work in contexts that use the expression
7523    parser.  */
7524
7525 static void
7526 fixup_go_packaging (struct dwarf2_cu *cu)
7527 {
7528   char *package_name = NULL;
7529   struct pending *list;
7530   int i;
7531
7532   for (list = global_symbols; list != NULL; list = list->next)
7533     {
7534       for (i = 0; i < list->nsyms; ++i)
7535         {
7536           struct symbol *sym = list->symbol[i];
7537
7538           if (SYMBOL_LANGUAGE (sym) == language_go
7539               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7540             {
7541               char *this_package_name = go_symbol_package_name (sym);
7542
7543               if (this_package_name == NULL)
7544                 continue;
7545               if (package_name == NULL)
7546                 package_name = this_package_name;
7547               else
7548                 {
7549                   if (strcmp (package_name, this_package_name) != 0)
7550                     complaint (&symfile_complaints,
7551                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7552                                (SYMBOL_SYMTAB (sym)
7553                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7554                                 : objfile_name (cu->objfile)),
7555                                this_package_name, package_name);
7556                   xfree (this_package_name);
7557                 }
7558             }
7559         }
7560     }
7561
7562   if (package_name != NULL)
7563     {
7564       struct objfile *objfile = cu->objfile;
7565       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7566                                                       package_name,
7567                                                       strlen (package_name));
7568       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7569                                      saved_package_name, objfile);
7570       struct symbol *sym;
7571
7572       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7573
7574       sym = allocate_symbol (objfile);
7575       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7576       SYMBOL_SET_NAMES (sym, saved_package_name,
7577                         strlen (saved_package_name), 0, objfile);
7578       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7579          e.g., "main" finds the "main" module and not C's main().  */
7580       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7581       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7582       SYMBOL_TYPE (sym) = type;
7583
7584       add_symbol_to_list (sym, &global_symbols);
7585
7586       xfree (package_name);
7587     }
7588 }
7589
7590 /* Return the symtab for PER_CU.  This works properly regardless of
7591    whether we're using the index or psymtabs.  */
7592
7593 static struct symtab *
7594 get_symtab (struct dwarf2_per_cu_data *per_cu)
7595 {
7596   return (dwarf2_per_objfile->using_index
7597           ? per_cu->v.quick->symtab
7598           : per_cu->v.psymtab->symtab);
7599 }
7600
7601 /* A helper function for computing the list of all symbol tables
7602    included by PER_CU.  */
7603
7604 static void
7605 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7606                                 htab_t all_children, htab_t all_type_symtabs,
7607                                 struct dwarf2_per_cu_data *per_cu,
7608                                 struct symtab *immediate_parent)
7609 {
7610   void **slot;
7611   int ix;
7612   struct symtab *symtab;
7613   struct dwarf2_per_cu_data *iter;
7614
7615   slot = htab_find_slot (all_children, per_cu, INSERT);
7616   if (*slot != NULL)
7617     {
7618       /* This inclusion and its children have been processed.  */
7619       return;
7620     }
7621
7622   *slot = per_cu;
7623   /* Only add a CU if it has a symbol table.  */
7624   symtab = get_symtab (per_cu);
7625   if (symtab != NULL)
7626     {
7627       /* If this is a type unit only add its symbol table if we haven't
7628          seen it yet (type unit per_cu's can share symtabs).  */
7629       if (per_cu->is_debug_types)
7630         {
7631           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7632           if (*slot == NULL)
7633             {
7634               *slot = symtab;
7635               VEC_safe_push (symtab_ptr, *result, symtab);
7636               if (symtab->user == NULL)
7637                 symtab->user = immediate_parent;
7638             }
7639         }
7640       else
7641         {
7642           VEC_safe_push (symtab_ptr, *result, symtab);
7643           if (symtab->user == NULL)
7644             symtab->user = immediate_parent;
7645         }
7646     }
7647
7648   for (ix = 0;
7649        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7650        ++ix)
7651     {
7652       recursively_compute_inclusions (result, all_children,
7653                                       all_type_symtabs, iter, symtab);
7654     }
7655 }
7656
7657 /* Compute the symtab 'includes' fields for the symtab related to
7658    PER_CU.  */
7659
7660 static void
7661 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7662 {
7663   gdb_assert (! per_cu->is_debug_types);
7664
7665   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7666     {
7667       int ix, len;
7668       struct dwarf2_per_cu_data *per_cu_iter;
7669       struct symtab *symtab_iter;
7670       VEC (symtab_ptr) *result_symtabs = NULL;
7671       htab_t all_children, all_type_symtabs;
7672       struct symtab *symtab = get_symtab (per_cu);
7673
7674       /* If we don't have a symtab, we can just skip this case.  */
7675       if (symtab == NULL)
7676         return;
7677
7678       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7679                                         NULL, xcalloc, xfree);
7680       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7681                                             NULL, xcalloc, xfree);
7682
7683       for (ix = 0;
7684            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7685                         ix, per_cu_iter);
7686            ++ix)
7687         {
7688           recursively_compute_inclusions (&result_symtabs, all_children,
7689                                           all_type_symtabs, per_cu_iter,
7690                                           symtab);
7691         }
7692
7693       /* Now we have a transitive closure of all the included symtabs.  */
7694       len = VEC_length (symtab_ptr, result_symtabs);
7695       symtab->includes
7696         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7697                          (len + 1) * sizeof (struct symtab *));
7698       for (ix = 0;
7699            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7700            ++ix)
7701         symtab->includes[ix] = symtab_iter;
7702       symtab->includes[len] = NULL;
7703
7704       VEC_free (symtab_ptr, result_symtabs);
7705       htab_delete (all_children);
7706       htab_delete (all_type_symtabs);
7707     }
7708 }
7709
7710 /* Compute the 'includes' field for the symtabs of all the CUs we just
7711    read.  */
7712
7713 static void
7714 process_cu_includes (void)
7715 {
7716   int ix;
7717   struct dwarf2_per_cu_data *iter;
7718
7719   for (ix = 0;
7720        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7721                     ix, iter);
7722        ++ix)
7723     {
7724       if (! iter->is_debug_types)
7725         compute_symtab_includes (iter);
7726     }
7727
7728   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7729 }
7730
7731 /* Generate full symbol information for PER_CU, whose DIEs have
7732    already been loaded into memory.  */
7733
7734 static void
7735 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7736                         enum language pretend_language)
7737 {
7738   struct dwarf2_cu *cu = per_cu->cu;
7739   struct objfile *objfile = per_cu->objfile;
7740   CORE_ADDR lowpc, highpc;
7741   struct symtab *symtab;
7742   struct cleanup *back_to, *delayed_list_cleanup;
7743   CORE_ADDR baseaddr;
7744   struct block *static_block;
7745
7746   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7747
7748   buildsym_init ();
7749   back_to = make_cleanup (really_free_pendings, NULL);
7750   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7751
7752   cu->list_in_scope = &file_symbols;
7753
7754   cu->language = pretend_language;
7755   cu->language_defn = language_def (cu->language);
7756
7757   /* Do line number decoding in read_file_scope () */
7758   process_die (cu->dies, cu);
7759
7760   /* For now fudge the Go package.  */
7761   if (cu->language == language_go)
7762     fixup_go_packaging (cu);
7763
7764   /* Now that we have processed all the DIEs in the CU, all the types 
7765      should be complete, and it should now be safe to compute all of the
7766      physnames.  */
7767   compute_delayed_physnames (cu);
7768   do_cleanups (delayed_list_cleanup);
7769
7770   /* Some compilers don't define a DW_AT_high_pc attribute for the
7771      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7772      it, by scanning the DIE's below the compilation unit.  */
7773   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7774
7775   static_block
7776     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7777
7778   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7779      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7780      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7781      addrmap to help ensure it has an accurate map of pc values belonging to
7782      this comp unit.  */
7783   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7784
7785   symtab = end_symtab_from_static_block (static_block, objfile,
7786                                          SECT_OFF_TEXT (objfile), 0);
7787
7788   if (symtab != NULL)
7789     {
7790       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7791
7792       /* Set symtab language to language from DW_AT_language.  If the
7793          compilation is from a C file generated by language preprocessors, do
7794          not set the language if it was already deduced by start_subfile.  */
7795       if (!(cu->language == language_c && symtab->language != language_c))
7796         symtab->language = cu->language;
7797
7798       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7799          produce DW_AT_location with location lists but it can be possibly
7800          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7801          there were bugs in prologue debug info, fixed later in GCC-4.5
7802          by "unwind info for epilogues" patch (which is not directly related).
7803
7804          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7805          needed, it would be wrong due to missing DW_AT_producer there.
7806
7807          Still one can confuse GDB by using non-standard GCC compilation
7808          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7809          */ 
7810       if (cu->has_loclist && gcc_4_minor >= 5)
7811         symtab->locations_valid = 1;
7812
7813       if (gcc_4_minor >= 5)
7814         symtab->epilogue_unwind_valid = 1;
7815
7816       symtab->call_site_htab = cu->call_site_htab;
7817     }
7818
7819   if (dwarf2_per_objfile->using_index)
7820     per_cu->v.quick->symtab = symtab;
7821   else
7822     {
7823       struct partial_symtab *pst = per_cu->v.psymtab;
7824       pst->symtab = symtab;
7825       pst->readin = 1;
7826     }
7827
7828   /* Push it for inclusion processing later.  */
7829   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7830
7831   do_cleanups (back_to);
7832 }
7833
7834 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7835    already been loaded into memory.  */
7836
7837 static void
7838 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7839                         enum language pretend_language)
7840 {
7841   struct dwarf2_cu *cu = per_cu->cu;
7842   struct objfile *objfile = per_cu->objfile;
7843   struct symtab *symtab;
7844   struct cleanup *back_to, *delayed_list_cleanup;
7845   struct signatured_type *sig_type;
7846
7847   gdb_assert (per_cu->is_debug_types);
7848   sig_type = (struct signatured_type *) per_cu;
7849
7850   buildsym_init ();
7851   back_to = make_cleanup (really_free_pendings, NULL);
7852   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7853
7854   cu->list_in_scope = &file_symbols;
7855
7856   cu->language = pretend_language;
7857   cu->language_defn = language_def (cu->language);
7858
7859   /* The symbol tables are set up in read_type_unit_scope.  */
7860   process_die (cu->dies, cu);
7861
7862   /* For now fudge the Go package.  */
7863   if (cu->language == language_go)
7864     fixup_go_packaging (cu);
7865
7866   /* Now that we have processed all the DIEs in the CU, all the types 
7867      should be complete, and it should now be safe to compute all of the
7868      physnames.  */
7869   compute_delayed_physnames (cu);
7870   do_cleanups (delayed_list_cleanup);
7871
7872   /* TUs share symbol tables.
7873      If this is the first TU to use this symtab, complete the construction
7874      of it with end_expandable_symtab.  Otherwise, complete the addition of
7875      this TU's symbols to the existing symtab.  */
7876   if (sig_type->type_unit_group->primary_symtab == NULL)
7877     {
7878       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7879       sig_type->type_unit_group->primary_symtab = symtab;
7880
7881       if (symtab != NULL)
7882         {
7883           /* Set symtab language to language from DW_AT_language.  If the
7884              compilation is from a C file generated by language preprocessors,
7885              do not set the language if it was already deduced by
7886              start_subfile.  */
7887           if (!(cu->language == language_c && symtab->language != language_c))
7888             symtab->language = cu->language;
7889         }
7890     }
7891   else
7892     {
7893       augment_type_symtab (objfile,
7894                            sig_type->type_unit_group->primary_symtab);
7895       symtab = sig_type->type_unit_group->primary_symtab;
7896     }
7897
7898   if (dwarf2_per_objfile->using_index)
7899     per_cu->v.quick->symtab = symtab;
7900   else
7901     {
7902       struct partial_symtab *pst = per_cu->v.psymtab;
7903       pst->symtab = symtab;
7904       pst->readin = 1;
7905     }
7906
7907   do_cleanups (back_to);
7908 }
7909
7910 /* Process an imported unit DIE.  */
7911
7912 static void
7913 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7914 {
7915   struct attribute *attr;
7916
7917   /* For now we don't handle imported units in type units.  */
7918   if (cu->per_cu->is_debug_types)
7919     {
7920       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7921                " supported in type units [in module %s]"),
7922              objfile_name (cu->objfile));
7923     }
7924
7925   attr = dwarf2_attr (die, DW_AT_import, cu);
7926   if (attr != NULL)
7927     {
7928       struct dwarf2_per_cu_data *per_cu;
7929       struct symtab *imported_symtab;
7930       sect_offset offset;
7931       int is_dwz;
7932
7933       offset = dwarf2_get_ref_die_offset (attr);
7934       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7935       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7936
7937       /* If necessary, add it to the queue and load its DIEs.  */
7938       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7939         load_full_comp_unit (per_cu, cu->language);
7940
7941       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7942                      per_cu);
7943     }
7944 }
7945
7946 /* Process a die and its children.  */
7947
7948 static void
7949 process_die (struct die_info *die, struct dwarf2_cu *cu)
7950 {
7951   switch (die->tag)
7952     {
7953     case DW_TAG_padding:
7954       break;
7955     case DW_TAG_compile_unit:
7956     case DW_TAG_partial_unit:
7957       read_file_scope (die, cu);
7958       break;
7959     case DW_TAG_type_unit:
7960       read_type_unit_scope (die, cu);
7961       break;
7962     case DW_TAG_subprogram:
7963     case DW_TAG_inlined_subroutine:
7964       read_func_scope (die, cu);
7965       break;
7966     case DW_TAG_lexical_block:
7967     case DW_TAG_try_block:
7968     case DW_TAG_catch_block:
7969       read_lexical_block_scope (die, cu);
7970       break;
7971     case DW_TAG_GNU_call_site:
7972       read_call_site_scope (die, cu);
7973       break;
7974     case DW_TAG_class_type:
7975     case DW_TAG_interface_type:
7976     case DW_TAG_structure_type:
7977     case DW_TAG_union_type:
7978       process_structure_scope (die, cu);
7979       break;
7980     case DW_TAG_enumeration_type:
7981       process_enumeration_scope (die, cu);
7982       break;
7983
7984     /* These dies have a type, but processing them does not create
7985        a symbol or recurse to process the children.  Therefore we can
7986        read them on-demand through read_type_die.  */
7987     case DW_TAG_subroutine_type:
7988     case DW_TAG_set_type:
7989     case DW_TAG_array_type:
7990     case DW_TAG_pointer_type:
7991     case DW_TAG_ptr_to_member_type:
7992     case DW_TAG_reference_type:
7993     case DW_TAG_string_type:
7994       break;
7995
7996     case DW_TAG_base_type:
7997     case DW_TAG_subrange_type:
7998     case DW_TAG_typedef:
7999       /* Add a typedef symbol for the type definition, if it has a
8000          DW_AT_name.  */
8001       new_symbol (die, read_type_die (die, cu), cu);
8002       break;
8003     case DW_TAG_common_block:
8004       read_common_block (die, cu);
8005       break;
8006     case DW_TAG_common_inclusion:
8007       break;
8008     case DW_TAG_namespace:
8009       cu->processing_has_namespace_info = 1;
8010       read_namespace (die, cu);
8011       break;
8012     case DW_TAG_module:
8013       cu->processing_has_namespace_info = 1;
8014       read_module (die, cu);
8015       break;
8016     case DW_TAG_imported_declaration:
8017     case DW_TAG_imported_module:
8018       cu->processing_has_namespace_info = 1;
8019       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8020                                  || cu->language != language_fortran))
8021         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8022                    dwarf_tag_name (die->tag));
8023       read_import_statement (die, cu);
8024       break;
8025
8026     case DW_TAG_imported_unit:
8027       process_imported_unit_die (die, cu);
8028       break;
8029
8030     default:
8031       new_symbol (die, NULL, cu);
8032       break;
8033     }
8034 }
8035 \f
8036 /* DWARF name computation.  */
8037
8038 /* A helper function for dwarf2_compute_name which determines whether DIE
8039    needs to have the name of the scope prepended to the name listed in the
8040    die.  */
8041
8042 static int
8043 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8044 {
8045   struct attribute *attr;
8046
8047   switch (die->tag)
8048     {
8049     case DW_TAG_namespace:
8050     case DW_TAG_typedef:
8051     case DW_TAG_class_type:
8052     case DW_TAG_interface_type:
8053     case DW_TAG_structure_type:
8054     case DW_TAG_union_type:
8055     case DW_TAG_enumeration_type:
8056     case DW_TAG_enumerator:
8057     case DW_TAG_subprogram:
8058     case DW_TAG_member:
8059       return 1;
8060
8061     case DW_TAG_variable:
8062     case DW_TAG_constant:
8063       /* We only need to prefix "globally" visible variables.  These include
8064          any variable marked with DW_AT_external or any variable that
8065          lives in a namespace.  [Variables in anonymous namespaces
8066          require prefixing, but they are not DW_AT_external.]  */
8067
8068       if (dwarf2_attr (die, DW_AT_specification, cu))
8069         {
8070           struct dwarf2_cu *spec_cu = cu;
8071
8072           return die_needs_namespace (die_specification (die, &spec_cu),
8073                                       spec_cu);
8074         }
8075
8076       attr = dwarf2_attr (die, DW_AT_external, cu);
8077       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8078           && die->parent->tag != DW_TAG_module)
8079         return 0;
8080       /* A variable in a lexical block of some kind does not need a
8081          namespace, even though in C++ such variables may be external
8082          and have a mangled name.  */
8083       if (die->parent->tag ==  DW_TAG_lexical_block
8084           || die->parent->tag ==  DW_TAG_try_block
8085           || die->parent->tag ==  DW_TAG_catch_block
8086           || die->parent->tag == DW_TAG_subprogram)
8087         return 0;
8088       return 1;
8089
8090     default:
8091       return 0;
8092     }
8093 }
8094
8095 /* Retrieve the last character from a mem_file.  */
8096
8097 static void
8098 do_ui_file_peek_last (void *object, const char *buffer, long length)
8099 {
8100   char *last_char_p = (char *) object;
8101
8102   if (length > 0)
8103     *last_char_p = buffer[length - 1];
8104 }
8105
8106 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8107    compute the physname for the object, which include a method's:
8108    - formal parameters (C++/Java),
8109    - receiver type (Go),
8110    - return type (Java).
8111
8112    The term "physname" is a bit confusing.
8113    For C++, for example, it is the demangled name.
8114    For Go, for example, it's the mangled name.
8115
8116    For Ada, return the DIE's linkage name rather than the fully qualified
8117    name.  PHYSNAME is ignored..
8118
8119    The result is allocated on the objfile_obstack and canonicalized.  */
8120
8121 static const char *
8122 dwarf2_compute_name (const char *name,
8123                      struct die_info *die, struct dwarf2_cu *cu,
8124                      int physname)
8125 {
8126   struct objfile *objfile = cu->objfile;
8127
8128   if (name == NULL)
8129     name = dwarf2_name (die, cu);
8130
8131   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
8132      compute it by typename_concat inside GDB.  */
8133   if (cu->language == language_ada
8134       || (cu->language == language_fortran && physname))
8135     {
8136       /* For Ada unit, we prefer the linkage name over the name, as
8137          the former contains the exported name, which the user expects
8138          to be able to reference.  Ideally, we want the user to be able
8139          to reference this entity using either natural or linkage name,
8140          but we haven't started looking at this enhancement yet.  */
8141       struct attribute *attr;
8142
8143       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8144       if (attr == NULL)
8145         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8146       if (attr && DW_STRING (attr))
8147         return DW_STRING (attr);
8148     }
8149
8150   /* These are the only languages we know how to qualify names in.  */
8151   if (name != NULL
8152       && (cu->language == language_cplus || cu->language == language_java
8153           || cu->language == language_fortran))
8154     {
8155       if (die_needs_namespace (die, cu))
8156         {
8157           long length;
8158           const char *prefix;
8159           struct ui_file *buf;
8160
8161           prefix = determine_prefix (die, cu);
8162           buf = mem_fileopen ();
8163           if (*prefix != '\0')
8164             {
8165               char *prefixed_name = typename_concat (NULL, prefix, name,
8166                                                      physname, cu);
8167
8168               fputs_unfiltered (prefixed_name, buf);
8169               xfree (prefixed_name);
8170             }
8171           else
8172             fputs_unfiltered (name, buf);
8173
8174           /* Template parameters may be specified in the DIE's DW_AT_name, or
8175              as children with DW_TAG_template_type_param or
8176              DW_TAG_value_type_param.  If the latter, add them to the name
8177              here.  If the name already has template parameters, then
8178              skip this step; some versions of GCC emit both, and
8179              it is more efficient to use the pre-computed name.
8180
8181              Something to keep in mind about this process: it is very
8182              unlikely, or in some cases downright impossible, to produce
8183              something that will match the mangled name of a function.
8184              If the definition of the function has the same debug info,
8185              we should be able to match up with it anyway.  But fallbacks
8186              using the minimal symbol, for instance to find a method
8187              implemented in a stripped copy of libstdc++, will not work.
8188              If we do not have debug info for the definition, we will have to
8189              match them up some other way.
8190
8191              When we do name matching there is a related problem with function
8192              templates; two instantiated function templates are allowed to
8193              differ only by their return types, which we do not add here.  */
8194
8195           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8196             {
8197               struct attribute *attr;
8198               struct die_info *child;
8199               int first = 1;
8200
8201               die->building_fullname = 1;
8202
8203               for (child = die->child; child != NULL; child = child->sibling)
8204                 {
8205                   struct type *type;
8206                   LONGEST value;
8207                   const gdb_byte *bytes;
8208                   struct dwarf2_locexpr_baton *baton;
8209                   struct value *v;
8210
8211                   if (child->tag != DW_TAG_template_type_param
8212                       && child->tag != DW_TAG_template_value_param)
8213                     continue;
8214
8215                   if (first)
8216                     {
8217                       fputs_unfiltered ("<", buf);
8218                       first = 0;
8219                     }
8220                   else
8221                     fputs_unfiltered (", ", buf);
8222
8223                   attr = dwarf2_attr (child, DW_AT_type, cu);
8224                   if (attr == NULL)
8225                     {
8226                       complaint (&symfile_complaints,
8227                                  _("template parameter missing DW_AT_type"));
8228                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
8229                       continue;
8230                     }
8231                   type = die_type (child, cu);
8232
8233                   if (child->tag == DW_TAG_template_type_param)
8234                     {
8235                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8236                       continue;
8237                     }
8238
8239                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8240                   if (attr == NULL)
8241                     {
8242                       complaint (&symfile_complaints,
8243                                  _("template parameter missing "
8244                                    "DW_AT_const_value"));
8245                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8246                       continue;
8247                     }
8248
8249                   dwarf2_const_value_attr (attr, type, name,
8250                                            &cu->comp_unit_obstack, cu,
8251                                            &value, &bytes, &baton);
8252
8253                   if (TYPE_NOSIGN (type))
8254                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8255                        changed, this can use value_print instead.  */
8256                     c_printchar (value, type, buf);
8257                   else
8258                     {
8259                       struct value_print_options opts;
8260
8261                       if (baton != NULL)
8262                         v = dwarf2_evaluate_loc_desc (type, NULL,
8263                                                       baton->data,
8264                                                       baton->size,
8265                                                       baton->per_cu);
8266                       else if (bytes != NULL)
8267                         {
8268                           v = allocate_value (type);
8269                           memcpy (value_contents_writeable (v), bytes,
8270                                   TYPE_LENGTH (type));
8271                         }
8272                       else
8273                         v = value_from_longest (type, value);
8274
8275                       /* Specify decimal so that we do not depend on
8276                          the radix.  */
8277                       get_formatted_print_options (&opts, 'd');
8278                       opts.raw = 1;
8279                       value_print (v, buf, &opts);
8280                       release_value (v);
8281                       value_free (v);
8282                     }
8283                 }
8284
8285               die->building_fullname = 0;
8286
8287               if (!first)
8288                 {
8289                   /* Close the argument list, with a space if necessary
8290                      (nested templates).  */
8291                   char last_char = '\0';
8292                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8293                   if (last_char == '>')
8294                     fputs_unfiltered (" >", buf);
8295                   else
8296                     fputs_unfiltered (">", buf);
8297                 }
8298             }
8299
8300           /* For Java and C++ methods, append formal parameter type
8301              information, if PHYSNAME.  */
8302
8303           if (physname && die->tag == DW_TAG_subprogram
8304               && (cu->language == language_cplus
8305                   || cu->language == language_java))
8306             {
8307               struct type *type = read_type_die (die, cu);
8308
8309               c_type_print_args (type, buf, 1, cu->language,
8310                                  &type_print_raw_options);
8311
8312               if (cu->language == language_java)
8313                 {
8314                   /* For java, we must append the return type to method
8315                      names.  */
8316                   if (die->tag == DW_TAG_subprogram)
8317                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8318                                      0, 0, &type_print_raw_options);
8319                 }
8320               else if (cu->language == language_cplus)
8321                 {
8322                   /* Assume that an artificial first parameter is
8323                      "this", but do not crash if it is not.  RealView
8324                      marks unnamed (and thus unused) parameters as
8325                      artificial; there is no way to differentiate
8326                      the two cases.  */
8327                   if (TYPE_NFIELDS (type) > 0
8328                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8329                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8330                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8331                                                                         0))))
8332                     fputs_unfiltered (" const", buf);
8333                 }
8334             }
8335
8336           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8337                                        &length);
8338           ui_file_delete (buf);
8339
8340           if (cu->language == language_cplus)
8341             {
8342               const char *cname
8343                 = dwarf2_canonicalize_name (name, cu,
8344                                             &objfile->objfile_obstack);
8345
8346               if (cname != NULL)
8347                 name = cname;
8348             }
8349         }
8350     }
8351
8352   return name;
8353 }
8354
8355 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8356    If scope qualifiers are appropriate they will be added.  The result
8357    will be allocated on the objfile_obstack, or NULL if the DIE does
8358    not have a name.  NAME may either be from a previous call to
8359    dwarf2_name or NULL.
8360
8361    The output string will be canonicalized (if C++/Java).  */
8362
8363 static const char *
8364 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8365 {
8366   return dwarf2_compute_name (name, die, cu, 0);
8367 }
8368
8369 /* Construct a physname for the given DIE in CU.  NAME may either be
8370    from a previous call to dwarf2_name or NULL.  The result will be
8371    allocated on the objfile_objstack or NULL if the DIE does not have a
8372    name.
8373
8374    The output string will be canonicalized (if C++/Java).  */
8375
8376 static const char *
8377 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8378 {
8379   struct objfile *objfile = cu->objfile;
8380   struct attribute *attr;
8381   const char *retval, *mangled = NULL, *canon = NULL;
8382   struct cleanup *back_to;
8383   int need_copy = 1;
8384
8385   /* In this case dwarf2_compute_name is just a shortcut not building anything
8386      on its own.  */
8387   if (!die_needs_namespace (die, cu))
8388     return dwarf2_compute_name (name, die, cu, 1);
8389
8390   back_to = make_cleanup (null_cleanup, NULL);
8391
8392   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8393   if (!attr)
8394     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8395
8396   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8397      has computed.  */
8398   if (attr && DW_STRING (attr))
8399     {
8400       char *demangled;
8401
8402       mangled = DW_STRING (attr);
8403
8404       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8405          type.  It is easier for GDB users to search for such functions as
8406          `name(params)' than `long name(params)'.  In such case the minimal
8407          symbol names do not match the full symbol names but for template
8408          functions there is never a need to look up their definition from their
8409          declaration so the only disadvantage remains the minimal symbol
8410          variant `long name(params)' does not have the proper inferior type.
8411          */
8412
8413       if (cu->language == language_go)
8414         {
8415           /* This is a lie, but we already lie to the caller new_symbol_full.
8416              new_symbol_full assumes we return the mangled name.
8417              This just undoes that lie until things are cleaned up.  */
8418           demangled = NULL;
8419         }
8420       else
8421         {
8422           demangled = gdb_demangle (mangled,
8423                                     (DMGL_PARAMS | DMGL_ANSI
8424                                      | (cu->language == language_java
8425                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8426                                         : DMGL_RET_DROP)));
8427         }
8428       if (demangled)
8429         {
8430           make_cleanup (xfree, demangled);
8431           canon = demangled;
8432         }
8433       else
8434         {
8435           canon = mangled;
8436           need_copy = 0;
8437         }
8438     }
8439
8440   if (canon == NULL || check_physname)
8441     {
8442       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8443
8444       if (canon != NULL && strcmp (physname, canon) != 0)
8445         {
8446           /* It may not mean a bug in GDB.  The compiler could also
8447              compute DW_AT_linkage_name incorrectly.  But in such case
8448              GDB would need to be bug-to-bug compatible.  */
8449
8450           complaint (&symfile_complaints,
8451                      _("Computed physname <%s> does not match demangled <%s> "
8452                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8453                      physname, canon, mangled, die->offset.sect_off,
8454                      objfile_name (objfile));
8455
8456           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8457              is available here - over computed PHYSNAME.  It is safer
8458              against both buggy GDB and buggy compilers.  */
8459
8460           retval = canon;
8461         }
8462       else
8463         {
8464           retval = physname;
8465           need_copy = 0;
8466         }
8467     }
8468   else
8469     retval = canon;
8470
8471   if (need_copy)
8472     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8473
8474   do_cleanups (back_to);
8475   return retval;
8476 }
8477
8478 /* Read the import statement specified by the given die and record it.  */
8479
8480 static void
8481 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8482 {
8483   struct objfile *objfile = cu->objfile;
8484   struct attribute *import_attr;
8485   struct die_info *imported_die, *child_die;
8486   struct dwarf2_cu *imported_cu;
8487   const char *imported_name;
8488   const char *imported_name_prefix;
8489   const char *canonical_name;
8490   const char *import_alias;
8491   const char *imported_declaration = NULL;
8492   const char *import_prefix;
8493   VEC (const_char_ptr) *excludes = NULL;
8494   struct cleanup *cleanups;
8495
8496   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8497   if (import_attr == NULL)
8498     {
8499       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8500                  dwarf_tag_name (die->tag));
8501       return;
8502     }
8503
8504   imported_cu = cu;
8505   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8506   imported_name = dwarf2_name (imported_die, imported_cu);
8507   if (imported_name == NULL)
8508     {
8509       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8510
8511         The import in the following code:
8512         namespace A
8513           {
8514             typedef int B;
8515           }
8516
8517         int main ()
8518           {
8519             using A::B;
8520             B b;
8521             return b;
8522           }
8523
8524         ...
8525          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8526             <52>   DW_AT_decl_file   : 1
8527             <53>   DW_AT_decl_line   : 6
8528             <54>   DW_AT_import      : <0x75>
8529          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8530             <59>   DW_AT_name        : B
8531             <5b>   DW_AT_decl_file   : 1
8532             <5c>   DW_AT_decl_line   : 2
8533             <5d>   DW_AT_type        : <0x6e>
8534         ...
8535          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8536             <76>   DW_AT_byte_size   : 4
8537             <77>   DW_AT_encoding    : 5        (signed)
8538
8539         imports the wrong die ( 0x75 instead of 0x58 ).
8540         This case will be ignored until the gcc bug is fixed.  */
8541       return;
8542     }
8543
8544   /* Figure out the local name after import.  */
8545   import_alias = dwarf2_name (die, cu);
8546
8547   /* Figure out where the statement is being imported to.  */
8548   import_prefix = determine_prefix (die, cu);
8549
8550   /* Figure out what the scope of the imported die is and prepend it
8551      to the name of the imported die.  */
8552   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8553
8554   if (imported_die->tag != DW_TAG_namespace
8555       && imported_die->tag != DW_TAG_module)
8556     {
8557       imported_declaration = imported_name;
8558       canonical_name = imported_name_prefix;
8559     }
8560   else if (strlen (imported_name_prefix) > 0)
8561     canonical_name = obconcat (&objfile->objfile_obstack,
8562                                imported_name_prefix, "::", imported_name,
8563                                (char *) NULL);
8564   else
8565     canonical_name = imported_name;
8566
8567   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8568
8569   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8570     for (child_die = die->child; child_die && child_die->tag;
8571          child_die = sibling_die (child_die))
8572       {
8573         /* DWARF-4: A Fortran use statement with a “rename list” may be
8574            represented by an imported module entry with an import attribute
8575            referring to the module and owned entries corresponding to those
8576            entities that are renamed as part of being imported.  */
8577
8578         if (child_die->tag != DW_TAG_imported_declaration)
8579           {
8580             complaint (&symfile_complaints,
8581                        _("child DW_TAG_imported_declaration expected "
8582                          "- DIE at 0x%x [in module %s]"),
8583                        child_die->offset.sect_off, objfile_name (objfile));
8584             continue;
8585           }
8586
8587         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8588         if (import_attr == NULL)
8589           {
8590             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8591                        dwarf_tag_name (child_die->tag));
8592             continue;
8593           }
8594
8595         imported_cu = cu;
8596         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8597                                               &imported_cu);
8598         imported_name = dwarf2_name (imported_die, imported_cu);
8599         if (imported_name == NULL)
8600           {
8601             complaint (&symfile_complaints,
8602                        _("child DW_TAG_imported_declaration has unknown "
8603                          "imported name - DIE at 0x%x [in module %s]"),
8604                        child_die->offset.sect_off, objfile_name (objfile));
8605             continue;
8606           }
8607
8608         VEC_safe_push (const_char_ptr, excludes, imported_name);
8609
8610         process_die (child_die, cu);
8611       }
8612
8613   cp_add_using_directive (import_prefix,
8614                           canonical_name,
8615                           import_alias,
8616                           imported_declaration,
8617                           excludes,
8618                           0,
8619                           &objfile->objfile_obstack);
8620
8621   do_cleanups (cleanups);
8622 }
8623
8624 /* Cleanup function for handle_DW_AT_stmt_list.  */
8625
8626 static void
8627 free_cu_line_header (void *arg)
8628 {
8629   struct dwarf2_cu *cu = arg;
8630
8631   free_line_header (cu->line_header);
8632   cu->line_header = NULL;
8633 }
8634
8635 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8636    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8637    this, it was first present in GCC release 4.3.0.  */
8638
8639 static int
8640 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8641 {
8642   if (!cu->checked_producer)
8643     check_producer (cu);
8644
8645   return cu->producer_is_gcc_lt_4_3;
8646 }
8647
8648 static void
8649 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8650                          const char **name, const char **comp_dir)
8651 {
8652   struct attribute *attr;
8653
8654   *name = NULL;
8655   *comp_dir = NULL;
8656
8657   /* Find the filename.  Do not use dwarf2_name here, since the filename
8658      is not a source language identifier.  */
8659   attr = dwarf2_attr (die, DW_AT_name, cu);
8660   if (attr)
8661     {
8662       *name = DW_STRING (attr);
8663     }
8664
8665   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8666   if (attr)
8667     *comp_dir = DW_STRING (attr);
8668   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8669            && IS_ABSOLUTE_PATH (*name))
8670     {
8671       char *d = ldirname (*name);
8672
8673       *comp_dir = d;
8674       if (d != NULL)
8675         make_cleanup (xfree, d);
8676     }
8677   if (*comp_dir != NULL)
8678     {
8679       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8680          directory, get rid of it.  */
8681       char *cp = strchr (*comp_dir, ':');
8682
8683       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8684         *comp_dir = cp + 1;
8685     }
8686
8687   if (*name == NULL)
8688     *name = "<unknown>";
8689 }
8690
8691 /* Handle DW_AT_stmt_list for a compilation unit.
8692    DIE is the DW_TAG_compile_unit die for CU.
8693    COMP_DIR is the compilation directory.
8694    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8695
8696 static void
8697 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8698                         const char *comp_dir) /* ARI: editCase function */
8699 {
8700   struct attribute *attr;
8701
8702   gdb_assert (! cu->per_cu->is_debug_types);
8703
8704   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8705   if (attr)
8706     {
8707       unsigned int line_offset = DW_UNSND (attr);
8708       struct line_header *line_header
8709         = dwarf_decode_line_header (line_offset, cu);
8710
8711       if (line_header)
8712         {
8713           cu->line_header = line_header;
8714           make_cleanup (free_cu_line_header, cu);
8715           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8716         }
8717     }
8718 }
8719
8720 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8721
8722 static void
8723 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8724 {
8725   struct objfile *objfile = dwarf2_per_objfile->objfile;
8726   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8727   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8728   CORE_ADDR highpc = ((CORE_ADDR) 0);
8729   struct attribute *attr;
8730   const char *name = NULL;
8731   const char *comp_dir = NULL;
8732   struct die_info *child_die;
8733   bfd *abfd = objfile->obfd;
8734   CORE_ADDR baseaddr;
8735
8736   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8737
8738   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8739
8740   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8741      from finish_block.  */
8742   if (lowpc == ((CORE_ADDR) -1))
8743     lowpc = highpc;
8744   lowpc += baseaddr;
8745   highpc += baseaddr;
8746
8747   find_file_and_directory (die, cu, &name, &comp_dir);
8748
8749   prepare_one_comp_unit (cu, die, cu->language);
8750
8751   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8752      standardised yet.  As a workaround for the language detection we fall
8753      back to the DW_AT_producer string.  */
8754   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8755     cu->language = language_opencl;
8756
8757   /* Similar hack for Go.  */
8758   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8759     set_cu_language (DW_LANG_Go, cu);
8760
8761   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8762
8763   /* Decode line number information if present.  We do this before
8764      processing child DIEs, so that the line header table is available
8765      for DW_AT_decl_file.  */
8766   handle_DW_AT_stmt_list (die, cu, comp_dir);
8767
8768   /* Process all dies in compilation unit.  */
8769   if (die->child != NULL)
8770     {
8771       child_die = die->child;
8772       while (child_die && child_die->tag)
8773         {
8774           process_die (child_die, cu);
8775           child_die = sibling_die (child_die);
8776         }
8777     }
8778
8779   /* Decode macro information, if present.  Dwarf 2 macro information
8780      refers to information in the line number info statement program
8781      header, so we can only read it if we've read the header
8782      successfully.  */
8783   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8784   if (attr && cu->line_header)
8785     {
8786       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8787         complaint (&symfile_complaints,
8788                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8789
8790       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8791     }
8792   else
8793     {
8794       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8795       if (attr && cu->line_header)
8796         {
8797           unsigned int macro_offset = DW_UNSND (attr);
8798
8799           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8800         }
8801     }
8802
8803   do_cleanups (back_to);
8804 }
8805
8806 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8807    Create the set of symtabs used by this TU, or if this TU is sharing
8808    symtabs with another TU and the symtabs have already been created
8809    then restore those symtabs in the line header.
8810    We don't need the pc/line-number mapping for type units.  */
8811
8812 static void
8813 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8814 {
8815   struct objfile *objfile = dwarf2_per_objfile->objfile;
8816   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8817   struct type_unit_group *tu_group;
8818   int first_time;
8819   struct line_header *lh;
8820   struct attribute *attr;
8821   unsigned int i, line_offset;
8822   struct signatured_type *sig_type;
8823
8824   gdb_assert (per_cu->is_debug_types);
8825   sig_type = (struct signatured_type *) per_cu;
8826
8827   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8828
8829   /* If we're using .gdb_index (includes -readnow) then
8830      per_cu->type_unit_group may not have been set up yet.  */
8831   if (sig_type->type_unit_group == NULL)
8832     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8833   tu_group = sig_type->type_unit_group;
8834
8835   /* If we've already processed this stmt_list there's no real need to
8836      do it again, we could fake it and just recreate the part we need
8837      (file name,index -> symtab mapping).  If data shows this optimization
8838      is useful we can do it then.  */
8839   first_time = tu_group->primary_symtab == NULL;
8840
8841   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8842      debug info.  */
8843   lh = NULL;
8844   if (attr != NULL)
8845     {
8846       line_offset = DW_UNSND (attr);
8847       lh = dwarf_decode_line_header (line_offset, cu);
8848     }
8849   if (lh == NULL)
8850     {
8851       if (first_time)
8852         dwarf2_start_symtab (cu, "", NULL, 0);
8853       else
8854         {
8855           gdb_assert (tu_group->symtabs == NULL);
8856           restart_symtab (0);
8857         }
8858       /* Note: The primary symtab will get allocated at the end.  */
8859       return;
8860     }
8861
8862   cu->line_header = lh;
8863   make_cleanup (free_cu_line_header, cu);
8864
8865   if (first_time)
8866     {
8867       dwarf2_start_symtab (cu, "", NULL, 0);
8868
8869       tu_group->num_symtabs = lh->num_file_names;
8870       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8871
8872       for (i = 0; i < lh->num_file_names; ++i)
8873         {
8874           const char *dir = NULL;
8875           struct file_entry *fe = &lh->file_names[i];
8876
8877           if (fe->dir_index)
8878             dir = lh->include_dirs[fe->dir_index - 1];
8879           dwarf2_start_subfile (fe->name, dir, NULL);
8880
8881           /* Note: We don't have to watch for the main subfile here, type units
8882              don't have DW_AT_name.  */
8883
8884           if (current_subfile->symtab == NULL)
8885             {
8886               /* NOTE: start_subfile will recognize when it's been passed
8887                  a file it has already seen.  So we can't assume there's a
8888                  simple mapping from lh->file_names to subfiles,
8889                  lh->file_names may contain dups.  */
8890               current_subfile->symtab = allocate_symtab (current_subfile->name,
8891                                                          objfile);
8892             }
8893
8894           fe->symtab = current_subfile->symtab;
8895           tu_group->symtabs[i] = fe->symtab;
8896         }
8897     }
8898   else
8899     {
8900       restart_symtab (0);
8901
8902       for (i = 0; i < lh->num_file_names; ++i)
8903         {
8904           struct file_entry *fe = &lh->file_names[i];
8905
8906           fe->symtab = tu_group->symtabs[i];
8907         }
8908     }
8909
8910   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8911      so they don't have a "real" (so to speak) symtab anyway.
8912      There is later code that will assign the main symtab to all symbols
8913      that don't have one.  We need to handle the case of a symbol with a
8914      missing symtab (DW_AT_decl_file) anyway.  */
8915 }
8916
8917 /* Process DW_TAG_type_unit.
8918    For TUs we want to skip the first top level sibling if it's not the
8919    actual type being defined by this TU.  In this case the first top
8920    level sibling is there to provide context only.  */
8921
8922 static void
8923 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8924 {
8925   struct die_info *child_die;
8926
8927   prepare_one_comp_unit (cu, die, language_minimal);
8928
8929   /* Initialize (or reinitialize) the machinery for building symtabs.
8930      We do this before processing child DIEs, so that the line header table
8931      is available for DW_AT_decl_file.  */
8932   setup_type_unit_groups (die, cu);
8933
8934   if (die->child != NULL)
8935     {
8936       child_die = die->child;
8937       while (child_die && child_die->tag)
8938         {
8939           process_die (child_die, cu);
8940           child_die = sibling_die (child_die);
8941         }
8942     }
8943 }
8944 \f
8945 /* DWO/DWP files.
8946
8947    http://gcc.gnu.org/wiki/DebugFission
8948    http://gcc.gnu.org/wiki/DebugFissionDWP
8949
8950    To simplify handling of both DWO files ("object" files with the DWARF info)
8951    and DWP files (a file with the DWOs packaged up into one file), we treat
8952    DWP files as having a collection of virtual DWO files.  */
8953
8954 static hashval_t
8955 hash_dwo_file (const void *item)
8956 {
8957   const struct dwo_file *dwo_file = item;
8958   hashval_t hash;
8959
8960   hash = htab_hash_string (dwo_file->dwo_name);
8961   if (dwo_file->comp_dir != NULL)
8962     hash += htab_hash_string (dwo_file->comp_dir);
8963   return hash;
8964 }
8965
8966 static int
8967 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8968 {
8969   const struct dwo_file *lhs = item_lhs;
8970   const struct dwo_file *rhs = item_rhs;
8971
8972   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8973     return 0;
8974   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8975     return lhs->comp_dir == rhs->comp_dir;
8976   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8977 }
8978
8979 /* Allocate a hash table for DWO files.  */
8980
8981 static htab_t
8982 allocate_dwo_file_hash_table (void)
8983 {
8984   struct objfile *objfile = dwarf2_per_objfile->objfile;
8985
8986   return htab_create_alloc_ex (41,
8987                                hash_dwo_file,
8988                                eq_dwo_file,
8989                                NULL,
8990                                &objfile->objfile_obstack,
8991                                hashtab_obstack_allocate,
8992                                dummy_obstack_deallocate);
8993 }
8994
8995 /* Lookup DWO file DWO_NAME.  */
8996
8997 static void **
8998 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8999 {
9000   struct dwo_file find_entry;
9001   void **slot;
9002
9003   if (dwarf2_per_objfile->dwo_files == NULL)
9004     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9005
9006   memset (&find_entry, 0, sizeof (find_entry));
9007   find_entry.dwo_name = dwo_name;
9008   find_entry.comp_dir = comp_dir;
9009   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9010
9011   return slot;
9012 }
9013
9014 static hashval_t
9015 hash_dwo_unit (const void *item)
9016 {
9017   const struct dwo_unit *dwo_unit = item;
9018
9019   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9020   return dwo_unit->signature;
9021 }
9022
9023 static int
9024 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9025 {
9026   const struct dwo_unit *lhs = item_lhs;
9027   const struct dwo_unit *rhs = item_rhs;
9028
9029   /* The signature is assumed to be unique within the DWO file.
9030      So while object file CU dwo_id's always have the value zero,
9031      that's OK, assuming each object file DWO file has only one CU,
9032      and that's the rule for now.  */
9033   return lhs->signature == rhs->signature;
9034 }
9035
9036 /* Allocate a hash table for DWO CUs,TUs.
9037    There is one of these tables for each of CUs,TUs for each DWO file.  */
9038
9039 static htab_t
9040 allocate_dwo_unit_table (struct objfile *objfile)
9041 {
9042   /* Start out with a pretty small number.
9043      Generally DWO files contain only one CU and maybe some TUs.  */
9044   return htab_create_alloc_ex (3,
9045                                hash_dwo_unit,
9046                                eq_dwo_unit,
9047                                NULL,
9048                                &objfile->objfile_obstack,
9049                                hashtab_obstack_allocate,
9050                                dummy_obstack_deallocate);
9051 }
9052
9053 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9054
9055 struct create_dwo_cu_data
9056 {
9057   struct dwo_file *dwo_file;
9058   struct dwo_unit dwo_unit;
9059 };
9060
9061 /* die_reader_func for create_dwo_cu.  */
9062
9063 static void
9064 create_dwo_cu_reader (const struct die_reader_specs *reader,
9065                       const gdb_byte *info_ptr,
9066                       struct die_info *comp_unit_die,
9067                       int has_children,
9068                       void *datap)
9069 {
9070   struct dwarf2_cu *cu = reader->cu;
9071   struct objfile *objfile = dwarf2_per_objfile->objfile;
9072   sect_offset offset = cu->per_cu->offset;
9073   struct dwarf2_section_info *section = cu->per_cu->section;
9074   struct create_dwo_cu_data *data = datap;
9075   struct dwo_file *dwo_file = data->dwo_file;
9076   struct dwo_unit *dwo_unit = &data->dwo_unit;
9077   struct attribute *attr;
9078
9079   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9080   if (attr == NULL)
9081     {
9082       complaint (&symfile_complaints,
9083                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9084                    " its dwo_id [in module %s]"),
9085                  offset.sect_off, dwo_file->dwo_name);
9086       return;
9087     }
9088
9089   dwo_unit->dwo_file = dwo_file;
9090   dwo_unit->signature = DW_UNSND (attr);
9091   dwo_unit->section = section;
9092   dwo_unit->offset = offset;
9093   dwo_unit->length = cu->per_cu->length;
9094
9095   if (dwarf2_read_debug)
9096     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9097                         offset.sect_off, hex_string (dwo_unit->signature));
9098 }
9099
9100 /* Create the dwo_unit for the lone CU in DWO_FILE.
9101    Note: This function processes DWO files only, not DWP files.  */
9102
9103 static struct dwo_unit *
9104 create_dwo_cu (struct dwo_file *dwo_file)
9105 {
9106   struct objfile *objfile = dwarf2_per_objfile->objfile;
9107   struct dwarf2_section_info *section = &dwo_file->sections.info;
9108   bfd *abfd;
9109   htab_t cu_htab;
9110   const gdb_byte *info_ptr, *end_ptr;
9111   struct create_dwo_cu_data create_dwo_cu_data;
9112   struct dwo_unit *dwo_unit;
9113
9114   dwarf2_read_section (objfile, section);
9115   info_ptr = section->buffer;
9116
9117   if (info_ptr == NULL)
9118     return NULL;
9119
9120   /* We can't set abfd until now because the section may be empty or
9121      not present, in which case section->asection will be NULL.  */
9122   abfd = get_section_bfd_owner (section);
9123
9124   if (dwarf2_read_debug)
9125     {
9126       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9127                           get_section_name (section),
9128                           get_section_file_name (section));
9129     }
9130
9131   create_dwo_cu_data.dwo_file = dwo_file;
9132   dwo_unit = NULL;
9133
9134   end_ptr = info_ptr + section->size;
9135   while (info_ptr < end_ptr)
9136     {
9137       struct dwarf2_per_cu_data per_cu;
9138
9139       memset (&create_dwo_cu_data.dwo_unit, 0,
9140               sizeof (create_dwo_cu_data.dwo_unit));
9141       memset (&per_cu, 0, sizeof (per_cu));
9142       per_cu.objfile = objfile;
9143       per_cu.is_debug_types = 0;
9144       per_cu.offset.sect_off = info_ptr - section->buffer;
9145       per_cu.section = section;
9146
9147       init_cutu_and_read_dies_no_follow (&per_cu,
9148                                          &dwo_file->sections.abbrev,
9149                                          dwo_file,
9150                                          create_dwo_cu_reader,
9151                                          &create_dwo_cu_data);
9152
9153       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9154         {
9155           /* If we've already found one, complain.  We only support one
9156              because having more than one requires hacking the dwo_name of
9157              each to match, which is highly unlikely to happen.  */
9158           if (dwo_unit != NULL)
9159             {
9160               complaint (&symfile_complaints,
9161                          _("Multiple CUs in DWO file %s [in module %s]"),
9162                          dwo_file->dwo_name, objfile_name (objfile));
9163               break;
9164             }
9165
9166           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9167           *dwo_unit = create_dwo_cu_data.dwo_unit;
9168         }
9169
9170       info_ptr += per_cu.length;
9171     }
9172
9173   return dwo_unit;
9174 }
9175
9176 /* DWP file .debug_{cu,tu}_index section format:
9177    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9178
9179    DWP Version 1:
9180
9181    Both index sections have the same format, and serve to map a 64-bit
9182    signature to a set of section numbers.  Each section begins with a header,
9183    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9184    indexes, and a pool of 32-bit section numbers.  The index sections will be
9185    aligned at 8-byte boundaries in the file.
9186
9187    The index section header consists of:
9188
9189     V, 32 bit version number
9190     -, 32 bits unused
9191     N, 32 bit number of compilation units or type units in the index
9192     M, 32 bit number of slots in the hash table
9193
9194    Numbers are recorded using the byte order of the application binary.
9195
9196    The hash table begins at offset 16 in the section, and consists of an array
9197    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9198    order of the application binary).  Unused slots in the hash table are 0.
9199    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9200
9201    The parallel table begins immediately after the hash table
9202    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9203    array of 32-bit indexes (using the byte order of the application binary),
9204    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9205    table contains a 32-bit index into the pool of section numbers.  For unused
9206    hash table slots, the corresponding entry in the parallel table will be 0.
9207
9208    The pool of section numbers begins immediately following the hash table
9209    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9210    section numbers consists of an array of 32-bit words (using the byte order
9211    of the application binary).  Each item in the array is indexed starting
9212    from 0.  The hash table entry provides the index of the first section
9213    number in the set.  Additional section numbers in the set follow, and the
9214    set is terminated by a 0 entry (section number 0 is not used in ELF).
9215
9216    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9217    section must be the first entry in the set, and the .debug_abbrev.dwo must
9218    be the second entry. Other members of the set may follow in any order.
9219
9220    ---
9221
9222    DWP Version 2:
9223
9224    DWP Version 2 combines all the .debug_info, etc. sections into one,
9225    and the entries in the index tables are now offsets into these sections.
9226    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9227    section.
9228
9229    Index Section Contents:
9230     Header
9231     Hash Table of Signatures   dwp_hash_table.hash_table
9232     Parallel Table of Indices  dwp_hash_table.unit_table
9233     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9234     Table of Section Sizes     dwp_hash_table.v2.sizes
9235
9236    The index section header consists of:
9237
9238     V, 32 bit version number
9239     L, 32 bit number of columns in the table of section offsets
9240     N, 32 bit number of compilation units or type units in the index
9241     M, 32 bit number of slots in the hash table
9242
9243    Numbers are recorded using the byte order of the application binary.
9244
9245    The hash table has the same format as version 1.
9246    The parallel table of indices has the same format as version 1,
9247    except that the entries are origin-1 indices into the table of sections
9248    offsets and the table of section sizes.
9249
9250    The table of offsets begins immediately following the parallel table
9251    (at offset 16 + 12 * M from the beginning of the section).  The table is
9252    a two-dimensional array of 32-bit words (using the byte order of the
9253    application binary), with L columns and N+1 rows, in row-major order.
9254    Each row in the array is indexed starting from 0.  The first row provides
9255    a key to the remaining rows: each column in this row provides an identifier
9256    for a debug section, and the offsets in the same column of subsequent rows
9257    refer to that section.  The section identifiers are:
9258
9259     DW_SECT_INFO         1  .debug_info.dwo
9260     DW_SECT_TYPES        2  .debug_types.dwo
9261     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9262     DW_SECT_LINE         4  .debug_line.dwo
9263     DW_SECT_LOC          5  .debug_loc.dwo
9264     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9265     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9266     DW_SECT_MACRO        8  .debug_macro.dwo
9267
9268    The offsets provided by the CU and TU index sections are the base offsets
9269    for the contributions made by each CU or TU to the corresponding section
9270    in the package file.  Each CU and TU header contains an abbrev_offset
9271    field, used to find the abbreviations table for that CU or TU within the
9272    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9273    be interpreted as relative to the base offset given in the index section.
9274    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9275    should be interpreted as relative to the base offset for .debug_line.dwo,
9276    and offsets into other debug sections obtained from DWARF attributes should
9277    also be interpreted as relative to the corresponding base offset.
9278
9279    The table of sizes begins immediately following the table of offsets.
9280    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9281    with L columns and N rows, in row-major order.  Each row in the array is
9282    indexed starting from 1 (row 0 is shared by the two tables).
9283
9284    ---
9285
9286    Hash table lookup is handled the same in version 1 and 2:
9287
9288    We assume that N and M will not exceed 2^32 - 1.
9289    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9290
9291    Given a 64-bit compilation unit signature or a type signature S, an entry
9292    in the hash table is located as follows:
9293
9294    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9295       the low-order k bits all set to 1.
9296
9297    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9298
9299    3) If the hash table entry at index H matches the signature, use that
9300       entry.  If the hash table entry at index H is unused (all zeroes),
9301       terminate the search: the signature is not present in the table.
9302
9303    4) Let H = (H + H') modulo M. Repeat at Step 3.
9304
9305    Because M > N and H' and M are relatively prime, the search is guaranteed
9306    to stop at an unused slot or find the match.  */
9307
9308 /* Create a hash table to map DWO IDs to their CU/TU entry in
9309    .debug_{info,types}.dwo in DWP_FILE.
9310    Returns NULL if there isn't one.
9311    Note: This function processes DWP files only, not DWO files.  */
9312
9313 static struct dwp_hash_table *
9314 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9315 {
9316   struct objfile *objfile = dwarf2_per_objfile->objfile;
9317   bfd *dbfd = dwp_file->dbfd;
9318   const gdb_byte *index_ptr, *index_end;
9319   struct dwarf2_section_info *index;
9320   uint32_t version, nr_columns, nr_units, nr_slots;
9321   struct dwp_hash_table *htab;
9322
9323   if (is_debug_types)
9324     index = &dwp_file->sections.tu_index;
9325   else
9326     index = &dwp_file->sections.cu_index;
9327
9328   if (dwarf2_section_empty_p (index))
9329     return NULL;
9330   dwarf2_read_section (objfile, index);
9331
9332   index_ptr = index->buffer;
9333   index_end = index_ptr + index->size;
9334
9335   version = read_4_bytes (dbfd, index_ptr);
9336   index_ptr += 4;
9337   if (version == 2)
9338     nr_columns = read_4_bytes (dbfd, index_ptr);
9339   else
9340     nr_columns = 0;
9341   index_ptr += 4;
9342   nr_units = read_4_bytes (dbfd, index_ptr);
9343   index_ptr += 4;
9344   nr_slots = read_4_bytes (dbfd, index_ptr);
9345   index_ptr += 4;
9346
9347   if (version != 1 && version != 2)
9348     {
9349       error (_("Dwarf Error: unsupported DWP file version (%s)"
9350                " [in module %s]"),
9351              pulongest (version), dwp_file->name);
9352     }
9353   if (nr_slots != (nr_slots & -nr_slots))
9354     {
9355       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9356                " is not power of 2 [in module %s]"),
9357              pulongest (nr_slots), dwp_file->name);
9358     }
9359
9360   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9361   htab->version = version;
9362   htab->nr_columns = nr_columns;
9363   htab->nr_units = nr_units;
9364   htab->nr_slots = nr_slots;
9365   htab->hash_table = index_ptr;
9366   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9367
9368   /* Exit early if the table is empty.  */
9369   if (nr_slots == 0 || nr_units == 0
9370       || (version == 2 && nr_columns == 0))
9371     {
9372       /* All must be zero.  */
9373       if (nr_slots != 0 || nr_units != 0
9374           || (version == 2 && nr_columns != 0))
9375         {
9376           complaint (&symfile_complaints,
9377                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9378                        " all zero [in modules %s]"),
9379                      dwp_file->name);
9380         }
9381       return htab;
9382     }
9383
9384   if (version == 1)
9385     {
9386       htab->section_pool.v1.indices =
9387         htab->unit_table + sizeof (uint32_t) * nr_slots;
9388       /* It's harder to decide whether the section is too small in v1.
9389          V1 is deprecated anyway so we punt.  */
9390     }
9391   else
9392     {
9393       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9394       int *ids = htab->section_pool.v2.section_ids;
9395       /* Reverse map for error checking.  */
9396       int ids_seen[DW_SECT_MAX + 1];
9397       int i;
9398
9399       if (nr_columns < 2)
9400         {
9401           error (_("Dwarf Error: bad DWP hash table, too few columns"
9402                    " in section table [in module %s]"),
9403                  dwp_file->name);
9404         }
9405       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
9406         {
9407           error (_("Dwarf Error: bad DWP hash table, too many columns"
9408                    " in section table [in module %s]"),
9409                  dwp_file->name);
9410         }
9411       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9412       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9413       for (i = 0; i < nr_columns; ++i)
9414         {
9415           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
9416
9417           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
9418             {
9419               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
9420                        " in section table [in module %s]"),
9421                      id, dwp_file->name);
9422             }
9423           if (ids_seen[id] != -1)
9424             {
9425               error (_("Dwarf Error: bad DWP hash table, duplicate section"
9426                        " id %d in section table [in module %s]"),
9427                      id, dwp_file->name);
9428             }
9429           ids_seen[id] = i;
9430           ids[i] = id;
9431         }
9432       /* Must have exactly one info or types section.  */
9433       if (((ids_seen[DW_SECT_INFO] != -1)
9434            + (ids_seen[DW_SECT_TYPES] != -1))
9435           != 1)
9436         {
9437           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
9438                    " DWO info/types section [in module %s]"),
9439                  dwp_file->name);
9440         }
9441       /* Must have an abbrev section.  */
9442       if (ids_seen[DW_SECT_ABBREV] == -1)
9443         {
9444           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
9445                    " section [in module %s]"),
9446                  dwp_file->name);
9447         }
9448       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
9449       htab->section_pool.v2.sizes =
9450         htab->section_pool.v2.offsets + (sizeof (uint32_t)
9451                                          * nr_units * nr_columns);
9452       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
9453                                           * nr_units * nr_columns))
9454           > index_end)
9455         {
9456           error (_("Dwarf Error: DWP index section is corrupt (too small)"
9457                    " [in module %s]"),
9458                  dwp_file->name);
9459         }
9460     }
9461
9462   return htab;
9463 }
9464
9465 /* Update SECTIONS with the data from SECTP.
9466
9467    This function is like the other "locate" section routines that are
9468    passed to bfd_map_over_sections, but in this context the sections to
9469    read comes from the DWP V1 hash table, not the full ELF section table.
9470
9471    The result is non-zero for success, or zero if an error was found.  */
9472
9473 static int
9474 locate_v1_virtual_dwo_sections (asection *sectp,
9475                                 struct virtual_v1_dwo_sections *sections)
9476 {
9477   const struct dwop_section_names *names = &dwop_section_names;
9478
9479   if (section_is_p (sectp->name, &names->abbrev_dwo))
9480     {
9481       /* There can be only one.  */
9482       if (sections->abbrev.s.asection != NULL)
9483         return 0;
9484       sections->abbrev.s.asection = sectp;
9485       sections->abbrev.size = bfd_get_section_size (sectp);
9486     }
9487   else if (section_is_p (sectp->name, &names->info_dwo)
9488            || section_is_p (sectp->name, &names->types_dwo))
9489     {
9490       /* There can be only one.  */
9491       if (sections->info_or_types.s.asection != NULL)
9492         return 0;
9493       sections->info_or_types.s.asection = sectp;
9494       sections->info_or_types.size = bfd_get_section_size (sectp);
9495     }
9496   else if (section_is_p (sectp->name, &names->line_dwo))
9497     {
9498       /* There can be only one.  */
9499       if (sections->line.s.asection != NULL)
9500         return 0;
9501       sections->line.s.asection = sectp;
9502       sections->line.size = bfd_get_section_size (sectp);
9503     }
9504   else if (section_is_p (sectp->name, &names->loc_dwo))
9505     {
9506       /* There can be only one.  */
9507       if (sections->loc.s.asection != NULL)
9508         return 0;
9509       sections->loc.s.asection = sectp;
9510       sections->loc.size = bfd_get_section_size (sectp);
9511     }
9512   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9513     {
9514       /* There can be only one.  */
9515       if (sections->macinfo.s.asection != NULL)
9516         return 0;
9517       sections->macinfo.s.asection = sectp;
9518       sections->macinfo.size = bfd_get_section_size (sectp);
9519     }
9520   else if (section_is_p (sectp->name, &names->macro_dwo))
9521     {
9522       /* There can be only one.  */
9523       if (sections->macro.s.asection != NULL)
9524         return 0;
9525       sections->macro.s.asection = sectp;
9526       sections->macro.size = bfd_get_section_size (sectp);
9527     }
9528   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9529     {
9530       /* There can be only one.  */
9531       if (sections->str_offsets.s.asection != NULL)
9532         return 0;
9533       sections->str_offsets.s.asection = sectp;
9534       sections->str_offsets.size = bfd_get_section_size (sectp);
9535     }
9536   else
9537     {
9538       /* No other kind of section is valid.  */
9539       return 0;
9540     }
9541
9542   return 1;
9543 }
9544
9545 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9546    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9547    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9548    This is for DWP version 1 files.  */
9549
9550 static struct dwo_unit *
9551 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
9552                            uint32_t unit_index,
9553                            const char *comp_dir,
9554                            ULONGEST signature, int is_debug_types)
9555 {
9556   struct objfile *objfile = dwarf2_per_objfile->objfile;
9557   const struct dwp_hash_table *dwp_htab =
9558     is_debug_types ? dwp_file->tus : dwp_file->cus;
9559   bfd *dbfd = dwp_file->dbfd;
9560   const char *kind = is_debug_types ? "TU" : "CU";
9561   struct dwo_file *dwo_file;
9562   struct dwo_unit *dwo_unit;
9563   struct virtual_v1_dwo_sections sections;
9564   void **dwo_file_slot;
9565   char *virtual_dwo_name;
9566   struct dwarf2_section_info *cutu;
9567   struct cleanup *cleanups;
9568   int i;
9569
9570   gdb_assert (dwp_file->version == 1);
9571
9572   if (dwarf2_read_debug)
9573     {
9574       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
9575                           kind,
9576                           pulongest (unit_index), hex_string (signature),
9577                           dwp_file->name);
9578     }
9579
9580   /* Fetch the sections of this DWO unit.
9581      Put a limit on the number of sections we look for so that bad data
9582      doesn't cause us to loop forever.  */
9583
9584 #define MAX_NR_V1_DWO_SECTIONS \
9585   (1 /* .debug_info or .debug_types */ \
9586    + 1 /* .debug_abbrev */ \
9587    + 1 /* .debug_line */ \
9588    + 1 /* .debug_loc */ \
9589    + 1 /* .debug_str_offsets */ \
9590    + 1 /* .debug_macro or .debug_macinfo */ \
9591    + 1 /* trailing zero */)
9592
9593   memset (&sections, 0, sizeof (sections));
9594   cleanups = make_cleanup (null_cleanup, 0);
9595
9596   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
9597     {
9598       asection *sectp;
9599       uint32_t section_nr =
9600         read_4_bytes (dbfd,
9601                       dwp_htab->section_pool.v1.indices
9602                       + (unit_index + i) * sizeof (uint32_t));
9603
9604       if (section_nr == 0)
9605         break;
9606       if (section_nr >= dwp_file->num_sections)
9607         {
9608           error (_("Dwarf Error: bad DWP hash table, section number too large"
9609                    " [in module %s]"),
9610                  dwp_file->name);
9611         }
9612
9613       sectp = dwp_file->elf_sections[section_nr];
9614       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
9615         {
9616           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9617                    " [in module %s]"),
9618                  dwp_file->name);
9619         }
9620     }
9621
9622   if (i < 2
9623       || dwarf2_section_empty_p (&sections.info_or_types)
9624       || dwarf2_section_empty_p (&sections.abbrev))
9625     {
9626       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9627                " [in module %s]"),
9628              dwp_file->name);
9629     }
9630   if (i == MAX_NR_V1_DWO_SECTIONS)
9631     {
9632       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9633                " [in module %s]"),
9634              dwp_file->name);
9635     }
9636
9637   /* It's easier for the rest of the code if we fake a struct dwo_file and
9638      have dwo_unit "live" in that.  At least for now.
9639
9640      The DWP file can be made up of a random collection of CUs and TUs.
9641      However, for each CU + set of TUs that came from the same original DWO
9642      file, we can combine them back into a virtual DWO file to save space
9643      (fewer struct dwo_file objects to allocate).  Remember that for really
9644      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9645
9646   virtual_dwo_name =
9647     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9648                 get_section_id (&sections.abbrev),
9649                 get_section_id (&sections.line),
9650                 get_section_id (&sections.loc),
9651                 get_section_id (&sections.str_offsets));
9652   make_cleanup (xfree, virtual_dwo_name);
9653   /* Can we use an existing virtual DWO file?  */
9654   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9655   /* Create one if necessary.  */
9656   if (*dwo_file_slot == NULL)
9657     {
9658       if (dwarf2_read_debug)
9659         {
9660           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9661                               virtual_dwo_name);
9662         }
9663       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9664       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9665                                           virtual_dwo_name,
9666                                           strlen (virtual_dwo_name));
9667       dwo_file->comp_dir = comp_dir;
9668       dwo_file->sections.abbrev = sections.abbrev;
9669       dwo_file->sections.line = sections.line;
9670       dwo_file->sections.loc = sections.loc;
9671       dwo_file->sections.macinfo = sections.macinfo;
9672       dwo_file->sections.macro = sections.macro;
9673       dwo_file->sections.str_offsets = sections.str_offsets;
9674       /* The "str" section is global to the entire DWP file.  */
9675       dwo_file->sections.str = dwp_file->sections.str;
9676       /* The info or types section is assigned below to dwo_unit,
9677          there's no need to record it in dwo_file.
9678          Also, we can't simply record type sections in dwo_file because
9679          we record a pointer into the vector in dwo_unit.  As we collect more
9680          types we'll grow the vector and eventually have to reallocate space
9681          for it, invalidating all copies of pointers into the previous
9682          contents.  */
9683       *dwo_file_slot = dwo_file;
9684     }
9685   else
9686     {
9687       if (dwarf2_read_debug)
9688         {
9689           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9690                               virtual_dwo_name);
9691         }
9692       dwo_file = *dwo_file_slot;
9693     }
9694   do_cleanups (cleanups);
9695
9696   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9697   dwo_unit->dwo_file = dwo_file;
9698   dwo_unit->signature = signature;
9699   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9700                                      sizeof (struct dwarf2_section_info));
9701   *dwo_unit->section = sections.info_or_types;
9702   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9703
9704   return dwo_unit;
9705 }
9706
9707 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
9708    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
9709    piece within that section used by a TU/CU, return a virtual section
9710    of just that piece.  */
9711
9712 static struct dwarf2_section_info
9713 create_dwp_v2_section (struct dwarf2_section_info *section,
9714                        bfd_size_type offset, bfd_size_type size)
9715 {
9716   struct dwarf2_section_info result;
9717   asection *sectp;
9718
9719   gdb_assert (section != NULL);
9720   gdb_assert (!section->is_virtual);
9721
9722   memset (&result, 0, sizeof (result));
9723   result.s.containing_section = section;
9724   result.is_virtual = 1;
9725
9726   if (size == 0)
9727     return result;
9728
9729   sectp = get_section_bfd_section (section);
9730
9731   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
9732      bounds of the real section.  This is a pretty-rare event, so just
9733      flag an error (easier) instead of a warning and trying to cope.  */
9734   if (sectp == NULL
9735       || offset + size > bfd_get_section_size (sectp))
9736     {
9737       bfd *abfd = sectp->owner;
9738
9739       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
9740                " in section %s [in module %s]"),
9741              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
9742              objfile_name (dwarf2_per_objfile->objfile));
9743     }
9744
9745   result.virtual_offset = offset;
9746   result.size = size;
9747   return result;
9748 }
9749
9750 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9751    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9752    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9753    This is for DWP version 2 files.  */
9754
9755 static struct dwo_unit *
9756 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
9757                            uint32_t unit_index,
9758                            const char *comp_dir,
9759                            ULONGEST signature, int is_debug_types)
9760 {
9761   struct objfile *objfile = dwarf2_per_objfile->objfile;
9762   const struct dwp_hash_table *dwp_htab =
9763     is_debug_types ? dwp_file->tus : dwp_file->cus;
9764   bfd *dbfd = dwp_file->dbfd;
9765   const char *kind = is_debug_types ? "TU" : "CU";
9766   struct dwo_file *dwo_file;
9767   struct dwo_unit *dwo_unit;
9768   struct virtual_v2_dwo_sections sections;
9769   void **dwo_file_slot;
9770   char *virtual_dwo_name;
9771   struct dwarf2_section_info *cutu;
9772   struct cleanup *cleanups;
9773   int i;
9774
9775   gdb_assert (dwp_file->version == 2);
9776
9777   if (dwarf2_read_debug)
9778     {
9779       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
9780                           kind,
9781                           pulongest (unit_index), hex_string (signature),
9782                           dwp_file->name);
9783     }
9784
9785   /* Fetch the section offsets of this DWO unit.  */
9786
9787   memset (&sections, 0, sizeof (sections));
9788   cleanups = make_cleanup (null_cleanup, 0);
9789
9790   for (i = 0; i < dwp_htab->nr_columns; ++i)
9791     {
9792       uint32_t offset = read_4_bytes (dbfd,
9793                                       dwp_htab->section_pool.v2.offsets
9794                                       + (((unit_index - 1) * dwp_htab->nr_columns
9795                                           + i)
9796                                          * sizeof (uint32_t)));
9797       uint32_t size = read_4_bytes (dbfd,
9798                                     dwp_htab->section_pool.v2.sizes
9799                                     + (((unit_index - 1) * dwp_htab->nr_columns
9800                                         + i)
9801                                        * sizeof (uint32_t)));
9802
9803       switch (dwp_htab->section_pool.v2.section_ids[i])
9804         {
9805         case DW_SECT_INFO:
9806         case DW_SECT_TYPES:
9807           sections.info_or_types_offset = offset;
9808           sections.info_or_types_size = size;
9809           break;
9810         case DW_SECT_ABBREV:
9811           sections.abbrev_offset = offset;
9812           sections.abbrev_size = size;
9813           break;
9814         case DW_SECT_LINE:
9815           sections.line_offset = offset;
9816           sections.line_size = size;
9817           break;
9818         case DW_SECT_LOC:
9819           sections.loc_offset = offset;
9820           sections.loc_size = size;
9821           break;
9822         case DW_SECT_STR_OFFSETS:
9823           sections.str_offsets_offset = offset;
9824           sections.str_offsets_size = size;
9825           break;
9826         case DW_SECT_MACINFO:
9827           sections.macinfo_offset = offset;
9828           sections.macinfo_size = size;
9829           break;
9830         case DW_SECT_MACRO:
9831           sections.macro_offset = offset;
9832           sections.macro_size = size;
9833           break;
9834         }
9835     }
9836
9837   /* It's easier for the rest of the code if we fake a struct dwo_file and
9838      have dwo_unit "live" in that.  At least for now.
9839
9840      The DWP file can be made up of a random collection of CUs and TUs.
9841      However, for each CU + set of TUs that came from the same original DWO
9842      file, we can combine them back into a virtual DWO file to save space
9843      (fewer struct dwo_file objects to allocate).  Remember that for really
9844      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9845
9846   virtual_dwo_name =
9847     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
9848                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
9849                 (long) (sections.line_size ? sections.line_offset : 0),
9850                 (long) (sections.loc_size ? sections.loc_offset : 0),
9851                 (long) (sections.str_offsets_size
9852                         ? sections.str_offsets_offset : 0));
9853   make_cleanup (xfree, virtual_dwo_name);
9854   /* Can we use an existing virtual DWO file?  */
9855   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9856   /* Create one if necessary.  */
9857   if (*dwo_file_slot == NULL)
9858     {
9859       if (dwarf2_read_debug)
9860         {
9861           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9862                               virtual_dwo_name);
9863         }
9864       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9865       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9866                                           virtual_dwo_name,
9867                                           strlen (virtual_dwo_name));
9868       dwo_file->comp_dir = comp_dir;
9869       dwo_file->sections.abbrev =
9870         create_dwp_v2_section (&dwp_file->sections.abbrev,
9871                                sections.abbrev_offset, sections.abbrev_size);
9872       dwo_file->sections.line =
9873         create_dwp_v2_section (&dwp_file->sections.line,
9874                                sections.line_offset, sections.line_size);
9875       dwo_file->sections.loc =
9876         create_dwp_v2_section (&dwp_file->sections.loc,
9877                                sections.loc_offset, sections.loc_size);
9878       dwo_file->sections.macinfo =
9879         create_dwp_v2_section (&dwp_file->sections.macinfo,
9880                                sections.macinfo_offset, sections.macinfo_size);
9881       dwo_file->sections.macro =
9882         create_dwp_v2_section (&dwp_file->sections.macro,
9883                                sections.macro_offset, sections.macro_size);
9884       dwo_file->sections.str_offsets =
9885         create_dwp_v2_section (&dwp_file->sections.str_offsets,
9886                                sections.str_offsets_offset,
9887                                sections.str_offsets_size);
9888       /* The "str" section is global to the entire DWP file.  */
9889       dwo_file->sections.str = dwp_file->sections.str;
9890       /* The info or types section is assigned below to dwo_unit,
9891          there's no need to record it in dwo_file.
9892          Also, we can't simply record type sections in dwo_file because
9893          we record a pointer into the vector in dwo_unit.  As we collect more
9894          types we'll grow the vector and eventually have to reallocate space
9895          for it, invalidating all copies of pointers into the previous
9896          contents.  */
9897       *dwo_file_slot = dwo_file;
9898     }
9899   else
9900     {
9901       if (dwarf2_read_debug)
9902         {
9903           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9904                               virtual_dwo_name);
9905         }
9906       dwo_file = *dwo_file_slot;
9907     }
9908   do_cleanups (cleanups);
9909
9910   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9911   dwo_unit->dwo_file = dwo_file;
9912   dwo_unit->signature = signature;
9913   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9914                                      sizeof (struct dwarf2_section_info));
9915   *dwo_unit->section = create_dwp_v2_section (is_debug_types
9916                                               ? &dwp_file->sections.types
9917                                               : &dwp_file->sections.info,
9918                                               sections.info_or_types_offset,
9919                                               sections.info_or_types_size);
9920   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9921
9922   return dwo_unit;
9923 }
9924
9925 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
9926    Returns NULL if the signature isn't found.  */
9927
9928 static struct dwo_unit *
9929 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
9930                         ULONGEST signature, int is_debug_types)
9931 {
9932   const struct dwp_hash_table *dwp_htab =
9933     is_debug_types ? dwp_file->tus : dwp_file->cus;
9934   bfd *dbfd = dwp_file->dbfd;
9935   uint32_t mask = dwp_htab->nr_slots - 1;
9936   uint32_t hash = signature & mask;
9937   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9938   unsigned int i;
9939   void **slot;
9940   struct dwo_unit find_dwo_cu, *dwo_cu;
9941
9942   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9943   find_dwo_cu.signature = signature;
9944   slot = htab_find_slot (is_debug_types
9945                          ? dwp_file->loaded_tus
9946                          : dwp_file->loaded_cus,
9947                          &find_dwo_cu, INSERT);
9948
9949   if (*slot != NULL)
9950     return *slot;
9951
9952   /* Use a for loop so that we don't loop forever on bad debug info.  */
9953   for (i = 0; i < dwp_htab->nr_slots; ++i)
9954     {
9955       ULONGEST signature_in_table;
9956
9957       signature_in_table =
9958         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
9959       if (signature_in_table == signature)
9960         {
9961           uint32_t unit_index =
9962             read_4_bytes (dbfd,
9963                           dwp_htab->unit_table + hash * sizeof (uint32_t));
9964
9965           if (dwp_file->version == 1)
9966             {
9967               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
9968                                                  comp_dir, signature,
9969                                                  is_debug_types);
9970             }
9971           else
9972             {
9973               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
9974                                                  comp_dir, signature,
9975                                                  is_debug_types);
9976             }
9977           return *slot;
9978         }
9979       if (signature_in_table == 0)
9980         return NULL;
9981       hash = (hash + hash2) & mask;
9982     }
9983
9984   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9985            " [in module %s]"),
9986          dwp_file->name);
9987 }
9988
9989 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9990    Open the file specified by FILE_NAME and hand it off to BFD for
9991    preliminary analysis.  Return a newly initialized bfd *, which
9992    includes a canonicalized copy of FILE_NAME.
9993    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9994    SEARCH_CWD is true if the current directory is to be searched.
9995    It will be searched before debug-file-directory.
9996    If unable to find/open the file, return NULL.
9997    NOTE: This function is derived from symfile_bfd_open.  */
9998
9999 static bfd *
10000 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10001 {
10002   bfd *sym_bfd;
10003   int desc, flags;
10004   char *absolute_name;
10005   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10006      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10007      to debug_file_directory.  */
10008   char *search_path;
10009   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10010
10011   if (search_cwd)
10012     {
10013       if (*debug_file_directory != '\0')
10014         search_path = concat (".", dirname_separator_string,
10015                               debug_file_directory, NULL);
10016       else
10017         search_path = xstrdup (".");
10018     }
10019   else
10020     search_path = xstrdup (debug_file_directory);
10021
10022   flags = OPF_RETURN_REALPATH;
10023   if (is_dwp)
10024     flags |= OPF_SEARCH_IN_PATH;
10025   desc = openp (search_path, flags, file_name,
10026                 O_RDONLY | O_BINARY, &absolute_name);
10027   xfree (search_path);
10028   if (desc < 0)
10029     return NULL;
10030
10031   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
10032   xfree (absolute_name);
10033   if (sym_bfd == NULL)
10034     return NULL;
10035   bfd_set_cacheable (sym_bfd, 1);
10036
10037   if (!bfd_check_format (sym_bfd, bfd_object))
10038     {
10039       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
10040       return NULL;
10041     }
10042
10043   return sym_bfd;
10044 }
10045
10046 /* Try to open DWO file FILE_NAME.
10047    COMP_DIR is the DW_AT_comp_dir attribute.
10048    The result is the bfd handle of the file.
10049    If there is a problem finding or opening the file, return NULL.
10050    Upon success, the canonicalized path of the file is stored in the bfd,
10051    same as symfile_bfd_open.  */
10052
10053 static bfd *
10054 open_dwo_file (const char *file_name, const char *comp_dir)
10055 {
10056   bfd *abfd;
10057
10058   if (IS_ABSOLUTE_PATH (file_name))
10059     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10060
10061   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10062
10063   if (comp_dir != NULL)
10064     {
10065       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
10066
10067       /* NOTE: If comp_dir is a relative path, this will also try the
10068          search path, which seems useful.  */
10069       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
10070       xfree (path_to_try);
10071       if (abfd != NULL)
10072         return abfd;
10073     }
10074
10075   /* That didn't work, try debug-file-directory, which, despite its name,
10076      is a list of paths.  */
10077
10078   if (*debug_file_directory == '\0')
10079     return NULL;
10080
10081   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10082 }
10083
10084 /* This function is mapped across the sections and remembers the offset and
10085    size of each of the DWO debugging sections we are interested in.  */
10086
10087 static void
10088 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10089 {
10090   struct dwo_sections *dwo_sections = dwo_sections_ptr;
10091   const struct dwop_section_names *names = &dwop_section_names;
10092
10093   if (section_is_p (sectp->name, &names->abbrev_dwo))
10094     {
10095       dwo_sections->abbrev.s.asection = sectp;
10096       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10097     }
10098   else if (section_is_p (sectp->name, &names->info_dwo))
10099     {
10100       dwo_sections->info.s.asection = sectp;
10101       dwo_sections->info.size = bfd_get_section_size (sectp);
10102     }
10103   else if (section_is_p (sectp->name, &names->line_dwo))
10104     {
10105       dwo_sections->line.s.asection = sectp;
10106       dwo_sections->line.size = bfd_get_section_size (sectp);
10107     }
10108   else if (section_is_p (sectp->name, &names->loc_dwo))
10109     {
10110       dwo_sections->loc.s.asection = sectp;
10111       dwo_sections->loc.size = bfd_get_section_size (sectp);
10112     }
10113   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10114     {
10115       dwo_sections->macinfo.s.asection = sectp;
10116       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10117     }
10118   else if (section_is_p (sectp->name, &names->macro_dwo))
10119     {
10120       dwo_sections->macro.s.asection = sectp;
10121       dwo_sections->macro.size = bfd_get_section_size (sectp);
10122     }
10123   else if (section_is_p (sectp->name, &names->str_dwo))
10124     {
10125       dwo_sections->str.s.asection = sectp;
10126       dwo_sections->str.size = bfd_get_section_size (sectp);
10127     }
10128   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10129     {
10130       dwo_sections->str_offsets.s.asection = sectp;
10131       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10132     }
10133   else if (section_is_p (sectp->name, &names->types_dwo))
10134     {
10135       struct dwarf2_section_info type_section;
10136
10137       memset (&type_section, 0, sizeof (type_section));
10138       type_section.s.asection = sectp;
10139       type_section.size = bfd_get_section_size (sectp);
10140       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10141                      &type_section);
10142     }
10143 }
10144
10145 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10146    by PER_CU.  This is for the non-DWP case.
10147    The result is NULL if DWO_NAME can't be found.  */
10148
10149 static struct dwo_file *
10150 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10151                         const char *dwo_name, const char *comp_dir)
10152 {
10153   struct objfile *objfile = dwarf2_per_objfile->objfile;
10154   struct dwo_file *dwo_file;
10155   bfd *dbfd;
10156   struct cleanup *cleanups;
10157
10158   dbfd = open_dwo_file (dwo_name, comp_dir);
10159   if (dbfd == NULL)
10160     {
10161       if (dwarf2_read_debug)
10162         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10163       return NULL;
10164     }
10165   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10166   dwo_file->dwo_name = dwo_name;
10167   dwo_file->comp_dir = comp_dir;
10168   dwo_file->dbfd = dbfd;
10169
10170   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10171
10172   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
10173
10174   dwo_file->cu = create_dwo_cu (dwo_file);
10175
10176   dwo_file->tus = create_debug_types_hash_table (dwo_file,
10177                                                  dwo_file->sections.types);
10178
10179   discard_cleanups (cleanups);
10180
10181   if (dwarf2_read_debug)
10182     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10183
10184   return dwo_file;
10185 }
10186
10187 /* This function is mapped across the sections and remembers the offset and
10188    size of each of the DWP debugging sections common to version 1 and 2 that
10189    we are interested in.  */
10190
10191 static void
10192 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10193                                    void *dwp_file_ptr)
10194 {
10195   struct dwp_file *dwp_file = dwp_file_ptr;
10196   const struct dwop_section_names *names = &dwop_section_names;
10197   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10198
10199   /* Record the ELF section number for later lookup: this is what the
10200      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10201   gdb_assert (elf_section_nr < dwp_file->num_sections);
10202   dwp_file->elf_sections[elf_section_nr] = sectp;
10203
10204   /* Look for specific sections that we need.  */
10205   if (section_is_p (sectp->name, &names->str_dwo))
10206     {
10207       dwp_file->sections.str.s.asection = sectp;
10208       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10209     }
10210   else if (section_is_p (sectp->name, &names->cu_index))
10211     {
10212       dwp_file->sections.cu_index.s.asection = sectp;
10213       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10214     }
10215   else if (section_is_p (sectp->name, &names->tu_index))
10216     {
10217       dwp_file->sections.tu_index.s.asection = sectp;
10218       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10219     }
10220 }
10221
10222 /* This function is mapped across the sections and remembers the offset and
10223    size of each of the DWP version 2 debugging sections that we are interested
10224    in.  This is split into a separate function because we don't know if we
10225    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10226
10227 static void
10228 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10229 {
10230   struct dwp_file *dwp_file = dwp_file_ptr;
10231   const struct dwop_section_names *names = &dwop_section_names;
10232   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10233
10234   /* Record the ELF section number for later lookup: this is what the
10235      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10236   gdb_assert (elf_section_nr < dwp_file->num_sections);
10237   dwp_file->elf_sections[elf_section_nr] = sectp;
10238
10239   /* Look for specific sections that we need.  */
10240   if (section_is_p (sectp->name, &names->abbrev_dwo))
10241     {
10242       dwp_file->sections.abbrev.s.asection = sectp;
10243       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10244     }
10245   else if (section_is_p (sectp->name, &names->info_dwo))
10246     {
10247       dwp_file->sections.info.s.asection = sectp;
10248       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10249     }
10250   else if (section_is_p (sectp->name, &names->line_dwo))
10251     {
10252       dwp_file->sections.line.s.asection = sectp;
10253       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10254     }
10255   else if (section_is_p (sectp->name, &names->loc_dwo))
10256     {
10257       dwp_file->sections.loc.s.asection = sectp;
10258       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10259     }
10260   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10261     {
10262       dwp_file->sections.macinfo.s.asection = sectp;
10263       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10264     }
10265   else if (section_is_p (sectp->name, &names->macro_dwo))
10266     {
10267       dwp_file->sections.macro.s.asection = sectp;
10268       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10269     }
10270   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10271     {
10272       dwp_file->sections.str_offsets.s.asection = sectp;
10273       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10274     }
10275   else if (section_is_p (sectp->name, &names->types_dwo))
10276     {
10277       dwp_file->sections.types.s.asection = sectp;
10278       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10279     }
10280 }
10281
10282 /* Hash function for dwp_file loaded CUs/TUs.  */
10283
10284 static hashval_t
10285 hash_dwp_loaded_cutus (const void *item)
10286 {
10287   const struct dwo_unit *dwo_unit = item;
10288
10289   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10290   return dwo_unit->signature;
10291 }
10292
10293 /* Equality function for dwp_file loaded CUs/TUs.  */
10294
10295 static int
10296 eq_dwp_loaded_cutus (const void *a, const void *b)
10297 {
10298   const struct dwo_unit *dua = a;
10299   const struct dwo_unit *dub = b;
10300
10301   return dua->signature == dub->signature;
10302 }
10303
10304 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10305
10306 static htab_t
10307 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10308 {
10309   return htab_create_alloc_ex (3,
10310                                hash_dwp_loaded_cutus,
10311                                eq_dwp_loaded_cutus,
10312                                NULL,
10313                                &objfile->objfile_obstack,
10314                                hashtab_obstack_allocate,
10315                                dummy_obstack_deallocate);
10316 }
10317
10318 /* Try to open DWP file FILE_NAME.
10319    The result is the bfd handle of the file.
10320    If there is a problem finding or opening the file, return NULL.
10321    Upon success, the canonicalized path of the file is stored in the bfd,
10322    same as symfile_bfd_open.  */
10323
10324 static bfd *
10325 open_dwp_file (const char *file_name)
10326 {
10327   bfd *abfd;
10328
10329   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
10330   if (abfd != NULL)
10331     return abfd;
10332
10333   /* Work around upstream bug 15652.
10334      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10335      [Whether that's a "bug" is debatable, but it is getting in our way.]
10336      We have no real idea where the dwp file is, because gdb's realpath-ing
10337      of the executable's path may have discarded the needed info.
10338      [IWBN if the dwp file name was recorded in the executable, akin to
10339      .gnu_debuglink, but that doesn't exist yet.]
10340      Strip the directory from FILE_NAME and search again.  */
10341   if (*debug_file_directory != '\0')
10342     {
10343       /* Don't implicitly search the current directory here.
10344          If the user wants to search "." to handle this case,
10345          it must be added to debug-file-directory.  */
10346       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10347                                  0 /*search_cwd*/);
10348     }
10349
10350   return NULL;
10351 }
10352
10353 /* Initialize the use of the DWP file for the current objfile.
10354    By convention the name of the DWP file is ${objfile}.dwp.
10355    The result is NULL if it can't be found.  */
10356
10357 static struct dwp_file *
10358 open_and_init_dwp_file (void)
10359 {
10360   struct objfile *objfile = dwarf2_per_objfile->objfile;
10361   struct dwp_file *dwp_file;
10362   char *dwp_name;
10363   bfd *dbfd;
10364   struct cleanup *cleanups;
10365
10366   /* Try to find first .dwp for the binary file before any symbolic links
10367      resolving.  */
10368   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
10369   cleanups = make_cleanup (xfree, dwp_name);
10370
10371   dbfd = open_dwp_file (dwp_name);
10372   if (dbfd == NULL
10373       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10374     {
10375       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10376       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
10377       make_cleanup (xfree, dwp_name);
10378       dbfd = open_dwp_file (dwp_name);
10379     }
10380
10381   if (dbfd == NULL)
10382     {
10383       if (dwarf2_read_debug)
10384         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
10385       do_cleanups (cleanups);
10386       return NULL;
10387     }
10388   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
10389   dwp_file->name = bfd_get_filename (dbfd);
10390   dwp_file->dbfd = dbfd;
10391   do_cleanups (cleanups);
10392
10393   /* +1: section 0 is unused */
10394   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
10395   dwp_file->elf_sections =
10396     OBSTACK_CALLOC (&objfile->objfile_obstack,
10397                     dwp_file->num_sections, asection *);
10398
10399   bfd_map_over_sections (dbfd, dwarf2_locate_common_dwp_sections, dwp_file);
10400
10401   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
10402
10403   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
10404
10405   /* The DWP file version is stored in the hash table.  Oh well.  */
10406   if (dwp_file->cus->version != dwp_file->tus->version)
10407     {
10408       /* Technically speaking, we should try to limp along, but this is
10409          pretty bizarre.  */
10410       error (_("Dwarf Error: DWP file CU version %d doesn't match"
10411                " TU version %d [in DWP file %s]"),
10412              dwp_file->cus->version, dwp_file->tus->version, dwp_name);
10413     }
10414   dwp_file->version = dwp_file->cus->version;
10415
10416   if (dwp_file->version == 2)
10417     bfd_map_over_sections (dbfd, dwarf2_locate_v2_dwp_sections, dwp_file);
10418
10419   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
10420   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
10421
10422   if (dwarf2_read_debug)
10423     {
10424       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
10425       fprintf_unfiltered (gdb_stdlog,
10426                           "    %s CUs, %s TUs\n",
10427                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
10428                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
10429     }
10430
10431   return dwp_file;
10432 }
10433
10434 /* Wrapper around open_and_init_dwp_file, only open it once.  */
10435
10436 static struct dwp_file *
10437 get_dwp_file (void)
10438 {
10439   if (! dwarf2_per_objfile->dwp_checked)
10440     {
10441       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
10442       dwarf2_per_objfile->dwp_checked = 1;
10443     }
10444   return dwarf2_per_objfile->dwp_file;
10445 }
10446
10447 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
10448    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
10449    or in the DWP file for the objfile, referenced by THIS_UNIT.
10450    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
10451    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
10452
10453    This is called, for example, when wanting to read a variable with a
10454    complex location.  Therefore we don't want to do file i/o for every call.
10455    Therefore we don't want to look for a DWO file on every call.
10456    Therefore we first see if we've already seen SIGNATURE in a DWP file,
10457    then we check if we've already seen DWO_NAME, and only THEN do we check
10458    for a DWO file.
10459
10460    The result is a pointer to the dwo_unit object or NULL if we didn't find it
10461    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
10462
10463 static struct dwo_unit *
10464 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
10465                  const char *dwo_name, const char *comp_dir,
10466                  ULONGEST signature, int is_debug_types)
10467 {
10468   struct objfile *objfile = dwarf2_per_objfile->objfile;
10469   const char *kind = is_debug_types ? "TU" : "CU";
10470   void **dwo_file_slot;
10471   struct dwo_file *dwo_file;
10472   struct dwp_file *dwp_file;
10473
10474   /* First see if there's a DWP file.
10475      If we have a DWP file but didn't find the DWO inside it, don't
10476      look for the original DWO file.  It makes gdb behave differently
10477      depending on whether one is debugging in the build tree.  */
10478
10479   dwp_file = get_dwp_file ();
10480   if (dwp_file != NULL)
10481     {
10482       const struct dwp_hash_table *dwp_htab =
10483         is_debug_types ? dwp_file->tus : dwp_file->cus;
10484
10485       if (dwp_htab != NULL)
10486         {
10487           struct dwo_unit *dwo_cutu =
10488             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
10489                                     signature, is_debug_types);
10490
10491           if (dwo_cutu != NULL)
10492             {
10493               if (dwarf2_read_debug)
10494                 {
10495                   fprintf_unfiltered (gdb_stdlog,
10496                                       "Virtual DWO %s %s found: @%s\n",
10497                                       kind, hex_string (signature),
10498                                       host_address_to_string (dwo_cutu));
10499                 }
10500               return dwo_cutu;
10501             }
10502         }
10503     }
10504   else
10505     {
10506       /* No DWP file, look for the DWO file.  */
10507
10508       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
10509       if (*dwo_file_slot == NULL)
10510         {
10511           /* Read in the file and build a table of the CUs/TUs it contains.  */
10512           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
10513         }
10514       /* NOTE: This will be NULL if unable to open the file.  */
10515       dwo_file = *dwo_file_slot;
10516
10517       if (dwo_file != NULL)
10518         {
10519           struct dwo_unit *dwo_cutu = NULL;
10520
10521           if (is_debug_types && dwo_file->tus)
10522             {
10523               struct dwo_unit find_dwo_cutu;
10524
10525               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
10526               find_dwo_cutu.signature = signature;
10527               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
10528             }
10529           else if (!is_debug_types && dwo_file->cu)
10530             {
10531               if (signature == dwo_file->cu->signature)
10532                 dwo_cutu = dwo_file->cu;
10533             }
10534
10535           if (dwo_cutu != NULL)
10536             {
10537               if (dwarf2_read_debug)
10538                 {
10539                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
10540                                       kind, dwo_name, hex_string (signature),
10541                                       host_address_to_string (dwo_cutu));
10542                 }
10543               return dwo_cutu;
10544             }
10545         }
10546     }
10547
10548   /* We didn't find it.  This could mean a dwo_id mismatch, or
10549      someone deleted the DWO/DWP file, or the search path isn't set up
10550      correctly to find the file.  */
10551
10552   if (dwarf2_read_debug)
10553     {
10554       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
10555                           kind, dwo_name, hex_string (signature));
10556     }
10557
10558   /* This is a warning and not a complaint because it can be caused by
10559      pilot error (e.g., user accidentally deleting the DWO).  */
10560   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
10561              " [in module %s]"),
10562            kind, dwo_name, hex_string (signature),
10563            this_unit->is_debug_types ? "TU" : "CU",
10564            this_unit->offset.sect_off, objfile_name (objfile));
10565   return NULL;
10566 }
10567
10568 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
10569    See lookup_dwo_cutu_unit for details.  */
10570
10571 static struct dwo_unit *
10572 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
10573                       const char *dwo_name, const char *comp_dir,
10574                       ULONGEST signature)
10575 {
10576   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
10577 }
10578
10579 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
10580    See lookup_dwo_cutu_unit for details.  */
10581
10582 static struct dwo_unit *
10583 lookup_dwo_type_unit (struct signatured_type *this_tu,
10584                       const char *dwo_name, const char *comp_dir)
10585 {
10586   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
10587 }
10588
10589 /* Traversal function for queue_and_load_all_dwo_tus.  */
10590
10591 static int
10592 queue_and_load_dwo_tu (void **slot, void *info)
10593 {
10594   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
10595   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
10596   ULONGEST signature = dwo_unit->signature;
10597   struct signatured_type *sig_type =
10598     lookup_dwo_signatured_type (per_cu->cu, signature);
10599
10600   if (sig_type != NULL)
10601     {
10602       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
10603
10604       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
10605          a real dependency of PER_CU on SIG_TYPE.  That is detected later
10606          while processing PER_CU.  */
10607       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
10608         load_full_type_unit (sig_cu);
10609       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
10610     }
10611
10612   return 1;
10613 }
10614
10615 /* Queue all TUs contained in the DWO of PER_CU to be read in.
10616    The DWO may have the only definition of the type, though it may not be
10617    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
10618    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
10619
10620 static void
10621 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
10622 {
10623   struct dwo_unit *dwo_unit;
10624   struct dwo_file *dwo_file;
10625
10626   gdb_assert (!per_cu->is_debug_types);
10627   gdb_assert (get_dwp_file () == NULL);
10628   gdb_assert (per_cu->cu != NULL);
10629
10630   dwo_unit = per_cu->cu->dwo_unit;
10631   gdb_assert (dwo_unit != NULL);
10632
10633   dwo_file = dwo_unit->dwo_file;
10634   if (dwo_file->tus != NULL)
10635     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
10636 }
10637
10638 /* Free all resources associated with DWO_FILE.
10639    Close the DWO file and munmap the sections.
10640    All memory should be on the objfile obstack.  */
10641
10642 static void
10643 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
10644 {
10645   int ix;
10646   struct dwarf2_section_info *section;
10647
10648   /* Note: dbfd is NULL for virtual DWO files.  */
10649   gdb_bfd_unref (dwo_file->dbfd);
10650
10651   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
10652 }
10653
10654 /* Wrapper for free_dwo_file for use in cleanups.  */
10655
10656 static void
10657 free_dwo_file_cleanup (void *arg)
10658 {
10659   struct dwo_file *dwo_file = (struct dwo_file *) arg;
10660   struct objfile *objfile = dwarf2_per_objfile->objfile;
10661
10662   free_dwo_file (dwo_file, objfile);
10663 }
10664
10665 /* Traversal function for free_dwo_files.  */
10666
10667 static int
10668 free_dwo_file_from_slot (void **slot, void *info)
10669 {
10670   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
10671   struct objfile *objfile = (struct objfile *) info;
10672
10673   free_dwo_file (dwo_file, objfile);
10674
10675   return 1;
10676 }
10677
10678 /* Free all resources associated with DWO_FILES.  */
10679
10680 static void
10681 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
10682 {
10683   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
10684 }
10685 \f
10686 /* Read in various DIEs.  */
10687
10688 /* qsort helper for inherit_abstract_dies.  */
10689
10690 static int
10691 unsigned_int_compar (const void *ap, const void *bp)
10692 {
10693   unsigned int a = *(unsigned int *) ap;
10694   unsigned int b = *(unsigned int *) bp;
10695
10696   return (a > b) - (b > a);
10697 }
10698
10699 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
10700    Inherit only the children of the DW_AT_abstract_origin DIE not being
10701    already referenced by DW_AT_abstract_origin from the children of the
10702    current DIE.  */
10703
10704 static void
10705 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
10706 {
10707   struct die_info *child_die;
10708   unsigned die_children_count;
10709   /* CU offsets which were referenced by children of the current DIE.  */
10710   sect_offset *offsets;
10711   sect_offset *offsets_end, *offsetp;
10712   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
10713   struct die_info *origin_die;
10714   /* Iterator of the ORIGIN_DIE children.  */
10715   struct die_info *origin_child_die;
10716   struct cleanup *cleanups;
10717   struct attribute *attr;
10718   struct dwarf2_cu *origin_cu;
10719   struct pending **origin_previous_list_in_scope;
10720
10721   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10722   if (!attr)
10723     return;
10724
10725   /* Note that following die references may follow to a die in a
10726      different cu.  */
10727
10728   origin_cu = cu;
10729   origin_die = follow_die_ref (die, attr, &origin_cu);
10730
10731   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
10732      symbols in.  */
10733   origin_previous_list_in_scope = origin_cu->list_in_scope;
10734   origin_cu->list_in_scope = cu->list_in_scope;
10735
10736   if (die->tag != origin_die->tag
10737       && !(die->tag == DW_TAG_inlined_subroutine
10738            && origin_die->tag == DW_TAG_subprogram))
10739     complaint (&symfile_complaints,
10740                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
10741                die->offset.sect_off, origin_die->offset.sect_off);
10742
10743   child_die = die->child;
10744   die_children_count = 0;
10745   while (child_die && child_die->tag)
10746     {
10747       child_die = sibling_die (child_die);
10748       die_children_count++;
10749     }
10750   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10751   cleanups = make_cleanup (xfree, offsets);
10752
10753   offsets_end = offsets;
10754   child_die = die->child;
10755   while (child_die && child_die->tag)
10756     {
10757       /* For each CHILD_DIE, find the corresponding child of
10758          ORIGIN_DIE.  If there is more than one layer of
10759          DW_AT_abstract_origin, follow them all; there shouldn't be,
10760          but GCC versions at least through 4.4 generate this (GCC PR
10761          40573).  */
10762       struct die_info *child_origin_die = child_die;
10763       struct dwarf2_cu *child_origin_cu = cu;
10764
10765       while (1)
10766         {
10767           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10768                               child_origin_cu);
10769           if (attr == NULL)
10770             break;
10771           child_origin_die = follow_die_ref (child_origin_die, attr,
10772                                              &child_origin_cu);
10773         }
10774
10775       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10776          counterpart may exist.  */
10777       if (child_origin_die != child_die)
10778         {
10779           if (child_die->tag != child_origin_die->tag
10780               && !(child_die->tag == DW_TAG_inlined_subroutine
10781                    && child_origin_die->tag == DW_TAG_subprogram))
10782             complaint (&symfile_complaints,
10783                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10784                          "different tags"), child_die->offset.sect_off,
10785                        child_origin_die->offset.sect_off);
10786           if (child_origin_die->parent != origin_die)
10787             complaint (&symfile_complaints,
10788                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10789                          "different parents"), child_die->offset.sect_off,
10790                        child_origin_die->offset.sect_off);
10791           else
10792             *offsets_end++ = child_origin_die->offset;
10793         }
10794       child_die = sibling_die (child_die);
10795     }
10796   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10797          unsigned_int_compar);
10798   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10799     if (offsetp[-1].sect_off == offsetp->sect_off)
10800       complaint (&symfile_complaints,
10801                  _("Multiple children of DIE 0x%x refer "
10802                    "to DIE 0x%x as their abstract origin"),
10803                  die->offset.sect_off, offsetp->sect_off);
10804
10805   offsetp = offsets;
10806   origin_child_die = origin_die->child;
10807   while (origin_child_die && origin_child_die->tag)
10808     {
10809       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10810       while (offsetp < offsets_end
10811              && offsetp->sect_off < origin_child_die->offset.sect_off)
10812         offsetp++;
10813       if (offsetp >= offsets_end
10814           || offsetp->sect_off > origin_child_die->offset.sect_off)
10815         {
10816           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10817           process_die (origin_child_die, origin_cu);
10818         }
10819       origin_child_die = sibling_die (origin_child_die);
10820     }
10821   origin_cu->list_in_scope = origin_previous_list_in_scope;
10822
10823   do_cleanups (cleanups);
10824 }
10825
10826 static void
10827 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10828 {
10829   struct objfile *objfile = cu->objfile;
10830   struct context_stack *new;
10831   CORE_ADDR lowpc;
10832   CORE_ADDR highpc;
10833   struct die_info *child_die;
10834   struct attribute *attr, *call_line, *call_file;
10835   const char *name;
10836   CORE_ADDR baseaddr;
10837   struct block *block;
10838   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10839   VEC (symbolp) *template_args = NULL;
10840   struct template_symbol *templ_func = NULL;
10841
10842   if (inlined_func)
10843     {
10844       /* If we do not have call site information, we can't show the
10845          caller of this inlined function.  That's too confusing, so
10846          only use the scope for local variables.  */
10847       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10848       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10849       if (call_line == NULL || call_file == NULL)
10850         {
10851           read_lexical_block_scope (die, cu);
10852           return;
10853         }
10854     }
10855
10856   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10857
10858   name = dwarf2_name (die, cu);
10859
10860   /* Ignore functions with missing or empty names.  These are actually
10861      illegal according to the DWARF standard.  */
10862   if (name == NULL)
10863     {
10864       complaint (&symfile_complaints,
10865                  _("missing name for subprogram DIE at %d"),
10866                  die->offset.sect_off);
10867       return;
10868     }
10869
10870   /* Ignore functions with missing or invalid low and high pc attributes.  */
10871   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10872     {
10873       attr = dwarf2_attr (die, DW_AT_external, cu);
10874       if (!attr || !DW_UNSND (attr))
10875         complaint (&symfile_complaints,
10876                    _("cannot get low and high bounds "
10877                      "for subprogram DIE at %d"),
10878                    die->offset.sect_off);
10879       return;
10880     }
10881
10882   lowpc += baseaddr;
10883   highpc += baseaddr;
10884
10885   /* If we have any template arguments, then we must allocate a
10886      different sort of symbol.  */
10887   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10888     {
10889       if (child_die->tag == DW_TAG_template_type_param
10890           || child_die->tag == DW_TAG_template_value_param)
10891         {
10892           templ_func = allocate_template_symbol (objfile);
10893           templ_func->base.is_cplus_template_function = 1;
10894           break;
10895         }
10896     }
10897
10898   new = push_context (0, lowpc);
10899   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10900                                (struct symbol *) templ_func);
10901
10902   /* If there is a location expression for DW_AT_frame_base, record
10903      it.  */
10904   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10905   if (attr)
10906     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10907
10908   cu->list_in_scope = &local_symbols;
10909
10910   if (die->child != NULL)
10911     {
10912       child_die = die->child;
10913       while (child_die && child_die->tag)
10914         {
10915           if (child_die->tag == DW_TAG_template_type_param
10916               || child_die->tag == DW_TAG_template_value_param)
10917             {
10918               struct symbol *arg = new_symbol (child_die, NULL, cu);
10919
10920               if (arg != NULL)
10921                 VEC_safe_push (symbolp, template_args, arg);
10922             }
10923           else
10924             process_die (child_die, cu);
10925           child_die = sibling_die (child_die);
10926         }
10927     }
10928
10929   inherit_abstract_dies (die, cu);
10930
10931   /* If we have a DW_AT_specification, we might need to import using
10932      directives from the context of the specification DIE.  See the
10933      comment in determine_prefix.  */
10934   if (cu->language == language_cplus
10935       && dwarf2_attr (die, DW_AT_specification, cu))
10936     {
10937       struct dwarf2_cu *spec_cu = cu;
10938       struct die_info *spec_die = die_specification (die, &spec_cu);
10939
10940       while (spec_die)
10941         {
10942           child_die = spec_die->child;
10943           while (child_die && child_die->tag)
10944             {
10945               if (child_die->tag == DW_TAG_imported_module)
10946                 process_die (child_die, spec_cu);
10947               child_die = sibling_die (child_die);
10948             }
10949
10950           /* In some cases, GCC generates specification DIEs that
10951              themselves contain DW_AT_specification attributes.  */
10952           spec_die = die_specification (spec_die, &spec_cu);
10953         }
10954     }
10955
10956   new = pop_context ();
10957   /* Make a block for the local symbols within.  */
10958   block = finish_block (new->name, &local_symbols, new->old_blocks,
10959                         lowpc, highpc, objfile);
10960
10961   /* For C++, set the block's scope.  */
10962   if ((cu->language == language_cplus || cu->language == language_fortran)
10963       && cu->processing_has_namespace_info)
10964     block_set_scope (block, determine_prefix (die, cu),
10965                      &objfile->objfile_obstack);
10966
10967   /* If we have address ranges, record them.  */
10968   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10969
10970   /* Attach template arguments to function.  */
10971   if (! VEC_empty (symbolp, template_args))
10972     {
10973       gdb_assert (templ_func != NULL);
10974
10975       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10976       templ_func->template_arguments
10977         = obstack_alloc (&objfile->objfile_obstack,
10978                          (templ_func->n_template_arguments
10979                           * sizeof (struct symbol *)));
10980       memcpy (templ_func->template_arguments,
10981               VEC_address (symbolp, template_args),
10982               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10983       VEC_free (symbolp, template_args);
10984     }
10985
10986   /* In C++, we can have functions nested inside functions (e.g., when
10987      a function declares a class that has methods).  This means that
10988      when we finish processing a function scope, we may need to go
10989      back to building a containing block's symbol lists.  */
10990   local_symbols = new->locals;
10991   using_directives = new->using_directives;
10992
10993   /* If we've finished processing a top-level function, subsequent
10994      symbols go in the file symbol list.  */
10995   if (outermost_context_p ())
10996     cu->list_in_scope = &file_symbols;
10997 }
10998
10999 /* Process all the DIES contained within a lexical block scope.  Start
11000    a new scope, process the dies, and then close the scope.  */
11001
11002 static void
11003 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11004 {
11005   struct objfile *objfile = cu->objfile;
11006   struct context_stack *new;
11007   CORE_ADDR lowpc, highpc;
11008   struct die_info *child_die;
11009   CORE_ADDR baseaddr;
11010
11011   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11012
11013   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11014   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11015      as multiple lexical blocks?  Handling children in a sane way would
11016      be nasty.  Might be easier to properly extend generic blocks to
11017      describe ranges.  */
11018   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11019     return;
11020   lowpc += baseaddr;
11021   highpc += baseaddr;
11022
11023   push_context (0, lowpc);
11024   if (die->child != NULL)
11025     {
11026       child_die = die->child;
11027       while (child_die && child_die->tag)
11028         {
11029           process_die (child_die, cu);
11030           child_die = sibling_die (child_die);
11031         }
11032     }
11033   new = pop_context ();
11034
11035   if (local_symbols != NULL || using_directives != NULL)
11036     {
11037       struct block *block
11038         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
11039                         highpc, objfile);
11040
11041       /* Note that recording ranges after traversing children, as we
11042          do here, means that recording a parent's ranges entails
11043          walking across all its children's ranges as they appear in
11044          the address map, which is quadratic behavior.
11045
11046          It would be nicer to record the parent's ranges before
11047          traversing its children, simply overriding whatever you find
11048          there.  But since we don't even decide whether to create a
11049          block until after we've traversed its children, that's hard
11050          to do.  */
11051       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11052     }
11053   local_symbols = new->locals;
11054   using_directives = new->using_directives;
11055 }
11056
11057 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
11058
11059 static void
11060 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11061 {
11062   struct objfile *objfile = cu->objfile;
11063   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11064   CORE_ADDR pc, baseaddr;
11065   struct attribute *attr;
11066   struct call_site *call_site, call_site_local;
11067   void **slot;
11068   int nparams;
11069   struct die_info *child_die;
11070
11071   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11072
11073   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11074   if (!attr)
11075     {
11076       complaint (&symfile_complaints,
11077                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
11078                    "DIE 0x%x [in module %s]"),
11079                  die->offset.sect_off, objfile_name (objfile));
11080       return;
11081     }
11082   pc = DW_ADDR (attr) + baseaddr;
11083
11084   if (cu->call_site_htab == NULL)
11085     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11086                                                NULL, &objfile->objfile_obstack,
11087                                                hashtab_obstack_allocate, NULL);
11088   call_site_local.pc = pc;
11089   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11090   if (*slot != NULL)
11091     {
11092       complaint (&symfile_complaints,
11093                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
11094                    "DIE 0x%x [in module %s]"),
11095                  paddress (gdbarch, pc), die->offset.sect_off,
11096                  objfile_name (objfile));
11097       return;
11098     }
11099
11100   /* Count parameters at the caller.  */
11101
11102   nparams = 0;
11103   for (child_die = die->child; child_die && child_die->tag;
11104        child_die = sibling_die (child_die))
11105     {
11106       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11107         {
11108           complaint (&symfile_complaints,
11109                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
11110                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11111                      child_die->tag, child_die->offset.sect_off,
11112                      objfile_name (objfile));
11113           continue;
11114         }
11115
11116       nparams++;
11117     }
11118
11119   call_site = obstack_alloc (&objfile->objfile_obstack,
11120                              (sizeof (*call_site)
11121                               + (sizeof (*call_site->parameter)
11122                                  * (nparams - 1))));
11123   *slot = call_site;
11124   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11125   call_site->pc = pc;
11126
11127   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11128     {
11129       struct die_info *func_die;
11130
11131       /* Skip also over DW_TAG_inlined_subroutine.  */
11132       for (func_die = die->parent;
11133            func_die && func_die->tag != DW_TAG_subprogram
11134            && func_die->tag != DW_TAG_subroutine_type;
11135            func_die = func_die->parent);
11136
11137       /* DW_AT_GNU_all_call_sites is a superset
11138          of DW_AT_GNU_all_tail_call_sites.  */
11139       if (func_die
11140           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11141           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11142         {
11143           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11144              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11145              both the initial caller containing the real return address PC and
11146              the final callee containing the current PC of a chain of tail
11147              calls do not need to have the tail call list complete.  But any
11148              function candidate for a virtual tail call frame searched via
11149              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11150              determined unambiguously.  */
11151         }
11152       else
11153         {
11154           struct type *func_type = NULL;
11155
11156           if (func_die)
11157             func_type = get_die_type (func_die, cu);
11158           if (func_type != NULL)
11159             {
11160               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11161
11162               /* Enlist this call site to the function.  */
11163               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11164               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11165             }
11166           else
11167             complaint (&symfile_complaints,
11168                        _("Cannot find function owning DW_TAG_GNU_call_site "
11169                          "DIE 0x%x [in module %s]"),
11170                        die->offset.sect_off, objfile_name (objfile));
11171         }
11172     }
11173
11174   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11175   if (attr == NULL)
11176     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11177   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11178   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11179     /* Keep NULL DWARF_BLOCK.  */;
11180   else if (attr_form_is_block (attr))
11181     {
11182       struct dwarf2_locexpr_baton *dlbaton;
11183
11184       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
11185       dlbaton->data = DW_BLOCK (attr)->data;
11186       dlbaton->size = DW_BLOCK (attr)->size;
11187       dlbaton->per_cu = cu->per_cu;
11188
11189       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11190     }
11191   else if (attr_form_is_ref (attr))
11192     {
11193       struct dwarf2_cu *target_cu = cu;
11194       struct die_info *target_die;
11195
11196       target_die = follow_die_ref (die, attr, &target_cu);
11197       gdb_assert (target_cu->objfile == objfile);
11198       if (die_is_declaration (target_die, target_cu))
11199         {
11200           const char *target_physname = NULL;
11201           struct attribute *target_attr;
11202
11203           /* Prefer the mangled name; otherwise compute the demangled one.  */
11204           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
11205           if (target_attr == NULL)
11206             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
11207                                        target_cu);
11208           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
11209             target_physname = DW_STRING (target_attr);
11210           else
11211             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11212           if (target_physname == NULL)
11213             complaint (&symfile_complaints,
11214                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11215                          "physname, for referencing DIE 0x%x [in module %s]"),
11216                        die->offset.sect_off, objfile_name (objfile));
11217           else
11218             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11219         }
11220       else
11221         {
11222           CORE_ADDR lowpc;
11223
11224           /* DW_AT_entry_pc should be preferred.  */
11225           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
11226             complaint (&symfile_complaints,
11227                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11228                          "low pc, for referencing DIE 0x%x [in module %s]"),
11229                        die->offset.sect_off, objfile_name (objfile));
11230           else
11231             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
11232         }
11233     }
11234   else
11235     complaint (&symfile_complaints,
11236                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
11237                  "block nor reference, for DIE 0x%x [in module %s]"),
11238                die->offset.sect_off, objfile_name (objfile));
11239
11240   call_site->per_cu = cu->per_cu;
11241
11242   for (child_die = die->child;
11243        child_die && child_die->tag;
11244        child_die = sibling_die (child_die))
11245     {
11246       struct call_site_parameter *parameter;
11247       struct attribute *loc, *origin;
11248
11249       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11250         {
11251           /* Already printed the complaint above.  */
11252           continue;
11253         }
11254
11255       gdb_assert (call_site->parameter_count < nparams);
11256       parameter = &call_site->parameter[call_site->parameter_count];
11257
11258       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11259          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11260          register is contained in DW_AT_GNU_call_site_value.  */
11261
11262       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11263       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11264       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11265         {
11266           sect_offset offset;
11267
11268           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11269           offset = dwarf2_get_ref_die_offset (origin);
11270           if (!offset_in_cu_p (&cu->header, offset))
11271             {
11272               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11273                  binding can be done only inside one CU.  Such referenced DIE
11274                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11275               complaint (&symfile_complaints,
11276                          _("DW_AT_abstract_origin offset is not in CU for "
11277                            "DW_TAG_GNU_call_site child DIE 0x%x "
11278                            "[in module %s]"),
11279                          child_die->offset.sect_off, objfile_name (objfile));
11280               continue;
11281             }
11282           parameter->u.param_offset.cu_off = (offset.sect_off
11283                                               - cu->header.offset.sect_off);
11284         }
11285       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11286         {
11287           complaint (&symfile_complaints,
11288                      _("No DW_FORM_block* DW_AT_location for "
11289                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11290                      child_die->offset.sect_off, objfile_name (objfile));
11291           continue;
11292         }
11293       else
11294         {
11295           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
11296             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
11297           if (parameter->u.dwarf_reg != -1)
11298             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
11299           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
11300                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
11301                                              &parameter->u.fb_offset))
11302             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
11303           else
11304             {
11305               complaint (&symfile_complaints,
11306                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
11307                            "for DW_FORM_block* DW_AT_location is supported for "
11308                            "DW_TAG_GNU_call_site child DIE 0x%x "
11309                            "[in module %s]"),
11310                          child_die->offset.sect_off, objfile_name (objfile));
11311               continue;
11312             }
11313         }
11314
11315       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
11316       if (!attr_form_is_block (attr))
11317         {
11318           complaint (&symfile_complaints,
11319                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
11320                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11321                      child_die->offset.sect_off, objfile_name (objfile));
11322           continue;
11323         }
11324       parameter->value = DW_BLOCK (attr)->data;
11325       parameter->value_size = DW_BLOCK (attr)->size;
11326
11327       /* Parameters are not pre-cleared by memset above.  */
11328       parameter->data_value = NULL;
11329       parameter->data_value_size = 0;
11330       call_site->parameter_count++;
11331
11332       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
11333       if (attr)
11334         {
11335           if (!attr_form_is_block (attr))
11336             complaint (&symfile_complaints,
11337                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
11338                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11339                        child_die->offset.sect_off, objfile_name (objfile));
11340           else
11341             {
11342               parameter->data_value = DW_BLOCK (attr)->data;
11343               parameter->data_value_size = DW_BLOCK (attr)->size;
11344             }
11345         }
11346     }
11347 }
11348
11349 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
11350    Return 1 if the attributes are present and valid, otherwise, return 0.
11351    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
11352
11353 static int
11354 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
11355                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
11356                     struct partial_symtab *ranges_pst)
11357 {
11358   struct objfile *objfile = cu->objfile;
11359   struct comp_unit_head *cu_header = &cu->header;
11360   bfd *obfd = objfile->obfd;
11361   unsigned int addr_size = cu_header->addr_size;
11362   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11363   /* Base address selection entry.  */
11364   CORE_ADDR base;
11365   int found_base;
11366   unsigned int dummy;
11367   const gdb_byte *buffer;
11368   CORE_ADDR marker;
11369   int low_set;
11370   CORE_ADDR low = 0;
11371   CORE_ADDR high = 0;
11372   CORE_ADDR baseaddr;
11373
11374   found_base = cu->base_known;
11375   base = cu->base_address;
11376
11377   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11378   if (offset >= dwarf2_per_objfile->ranges.size)
11379     {
11380       complaint (&symfile_complaints,
11381                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
11382                  offset);
11383       return 0;
11384     }
11385   buffer = dwarf2_per_objfile->ranges.buffer + offset;
11386
11387   /* Read in the largest possible address.  */
11388   marker = read_address (obfd, buffer, cu, &dummy);
11389   if ((marker & mask) == mask)
11390     {
11391       /* If we found the largest possible address, then
11392          read the base address.  */
11393       base = read_address (obfd, buffer + addr_size, cu, &dummy);
11394       buffer += 2 * addr_size;
11395       offset += 2 * addr_size;
11396       found_base = 1;
11397     }
11398
11399   low_set = 0;
11400
11401   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11402
11403   while (1)
11404     {
11405       CORE_ADDR range_beginning, range_end;
11406
11407       range_beginning = read_address (obfd, buffer, cu, &dummy);
11408       buffer += addr_size;
11409       range_end = read_address (obfd, buffer, cu, &dummy);
11410       buffer += addr_size;
11411       offset += 2 * addr_size;
11412
11413       /* An end of list marker is a pair of zero addresses.  */
11414       if (range_beginning == 0 && range_end == 0)
11415         /* Found the end of list entry.  */
11416         break;
11417
11418       /* Each base address selection entry is a pair of 2 values.
11419          The first is the largest possible address, the second is
11420          the base address.  Check for a base address here.  */
11421       if ((range_beginning & mask) == mask)
11422         {
11423           /* If we found the largest possible address, then
11424              read the base address.  */
11425           base = read_address (obfd, buffer + addr_size, cu, &dummy);
11426           found_base = 1;
11427           continue;
11428         }
11429
11430       if (!found_base)
11431         {
11432           /* We have no valid base address for the ranges
11433              data.  */
11434           complaint (&symfile_complaints,
11435                      _("Invalid .debug_ranges data (no base address)"));
11436           return 0;
11437         }
11438
11439       if (range_beginning > range_end)
11440         {
11441           /* Inverted range entries are invalid.  */
11442           complaint (&symfile_complaints,
11443                      _("Invalid .debug_ranges data (inverted range)"));
11444           return 0;
11445         }
11446
11447       /* Empty range entries have no effect.  */
11448       if (range_beginning == range_end)
11449         continue;
11450
11451       range_beginning += base;
11452       range_end += base;
11453
11454       /* A not-uncommon case of bad debug info.
11455          Don't pollute the addrmap with bad data.  */
11456       if (range_beginning + baseaddr == 0
11457           && !dwarf2_per_objfile->has_section_at_zero)
11458         {
11459           complaint (&symfile_complaints,
11460                      _(".debug_ranges entry has start address of zero"
11461                        " [in module %s]"), objfile_name (objfile));
11462           continue;
11463         }
11464
11465       if (ranges_pst != NULL)
11466         addrmap_set_empty (objfile->psymtabs_addrmap,
11467                            range_beginning + baseaddr,
11468                            range_end - 1 + baseaddr,
11469                            ranges_pst);
11470
11471       /* FIXME: This is recording everything as a low-high
11472          segment of consecutive addresses.  We should have a
11473          data structure for discontiguous block ranges
11474          instead.  */
11475       if (! low_set)
11476         {
11477           low = range_beginning;
11478           high = range_end;
11479           low_set = 1;
11480         }
11481       else
11482         {
11483           if (range_beginning < low)
11484             low = range_beginning;
11485           if (range_end > high)
11486             high = range_end;
11487         }
11488     }
11489
11490   if (! low_set)
11491     /* If the first entry is an end-of-list marker, the range
11492        describes an empty scope, i.e. no instructions.  */
11493     return 0;
11494
11495   if (low_return)
11496     *low_return = low;
11497   if (high_return)
11498     *high_return = high;
11499   return 1;
11500 }
11501
11502 /* Get low and high pc attributes from a die.  Return 1 if the attributes
11503    are present and valid, otherwise, return 0.  Return -1 if the range is
11504    discontinuous, i.e. derived from DW_AT_ranges information.  */
11505
11506 static int
11507 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
11508                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
11509                       struct partial_symtab *pst)
11510 {
11511   struct attribute *attr;
11512   struct attribute *attr_high;
11513   CORE_ADDR low = 0;
11514   CORE_ADDR high = 0;
11515   int ret = 0;
11516
11517   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11518   if (attr_high)
11519     {
11520       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11521       if (attr)
11522         {
11523           low = DW_ADDR (attr);
11524           if (attr_high->form == DW_FORM_addr
11525               || attr_high->form == DW_FORM_GNU_addr_index)
11526             high = DW_ADDR (attr_high);
11527           else
11528             high = low + DW_UNSND (attr_high);
11529         }
11530       else
11531         /* Found high w/o low attribute.  */
11532         return 0;
11533
11534       /* Found consecutive range of addresses.  */
11535       ret = 1;
11536     }
11537   else
11538     {
11539       attr = dwarf2_attr (die, DW_AT_ranges, cu);
11540       if (attr != NULL)
11541         {
11542           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11543              We take advantage of the fact that DW_AT_ranges does not appear
11544              in DW_TAG_compile_unit of DWO files.  */
11545           int need_ranges_base = die->tag != DW_TAG_compile_unit;
11546           unsigned int ranges_offset = (DW_UNSND (attr)
11547                                         + (need_ranges_base
11548                                            ? cu->ranges_base
11549                                            : 0));
11550
11551           /* Value of the DW_AT_ranges attribute is the offset in the
11552              .debug_ranges section.  */
11553           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
11554             return 0;
11555           /* Found discontinuous range of addresses.  */
11556           ret = -1;
11557         }
11558     }
11559
11560   /* read_partial_die has also the strict LOW < HIGH requirement.  */
11561   if (high <= low)
11562     return 0;
11563
11564   /* When using the GNU linker, .gnu.linkonce. sections are used to
11565      eliminate duplicate copies of functions and vtables and such.
11566      The linker will arbitrarily choose one and discard the others.
11567      The AT_*_pc values for such functions refer to local labels in
11568      these sections.  If the section from that file was discarded, the
11569      labels are not in the output, so the relocs get a value of 0.
11570      If this is a discarded function, mark the pc bounds as invalid,
11571      so that GDB will ignore it.  */
11572   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
11573     return 0;
11574
11575   *lowpc = low;
11576   if (highpc)
11577     *highpc = high;
11578   return ret;
11579 }
11580
11581 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
11582    its low and high PC addresses.  Do nothing if these addresses could not
11583    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
11584    and HIGHPC to the high address if greater than HIGHPC.  */
11585
11586 static void
11587 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
11588                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
11589                                  struct dwarf2_cu *cu)
11590 {
11591   CORE_ADDR low, high;
11592   struct die_info *child = die->child;
11593
11594   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
11595     {
11596       *lowpc = min (*lowpc, low);
11597       *highpc = max (*highpc, high);
11598     }
11599
11600   /* If the language does not allow nested subprograms (either inside
11601      subprograms or lexical blocks), we're done.  */
11602   if (cu->language != language_ada)
11603     return;
11604
11605   /* Check all the children of the given DIE.  If it contains nested
11606      subprograms, then check their pc bounds.  Likewise, we need to
11607      check lexical blocks as well, as they may also contain subprogram
11608      definitions.  */
11609   while (child && child->tag)
11610     {
11611       if (child->tag == DW_TAG_subprogram
11612           || child->tag == DW_TAG_lexical_block)
11613         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
11614       child = sibling_die (child);
11615     }
11616 }
11617
11618 /* Get the low and high pc's represented by the scope DIE, and store
11619    them in *LOWPC and *HIGHPC.  If the correct values can't be
11620    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
11621
11622 static void
11623 get_scope_pc_bounds (struct die_info *die,
11624                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
11625                      struct dwarf2_cu *cu)
11626 {
11627   CORE_ADDR best_low = (CORE_ADDR) -1;
11628   CORE_ADDR best_high = (CORE_ADDR) 0;
11629   CORE_ADDR current_low, current_high;
11630
11631   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
11632     {
11633       best_low = current_low;
11634       best_high = current_high;
11635     }
11636   else
11637     {
11638       struct die_info *child = die->child;
11639
11640       while (child && child->tag)
11641         {
11642           switch (child->tag) {
11643           case DW_TAG_subprogram:
11644             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
11645             break;
11646           case DW_TAG_namespace:
11647           case DW_TAG_module:
11648             /* FIXME: carlton/2004-01-16: Should we do this for
11649                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
11650                that current GCC's always emit the DIEs corresponding
11651                to definitions of methods of classes as children of a
11652                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
11653                the DIEs giving the declarations, which could be
11654                anywhere).  But I don't see any reason why the
11655                standards says that they have to be there.  */
11656             get_scope_pc_bounds (child, &current_low, &current_high, cu);
11657
11658             if (current_low != ((CORE_ADDR) -1))
11659               {
11660                 best_low = min (best_low, current_low);
11661                 best_high = max (best_high, current_high);
11662               }
11663             break;
11664           default:
11665             /* Ignore.  */
11666             break;
11667           }
11668
11669           child = sibling_die (child);
11670         }
11671     }
11672
11673   *lowpc = best_low;
11674   *highpc = best_high;
11675 }
11676
11677 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
11678    in DIE.  */
11679
11680 static void
11681 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
11682                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
11683 {
11684   struct objfile *objfile = cu->objfile;
11685   struct attribute *attr;
11686   struct attribute *attr_high;
11687
11688   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11689   if (attr_high)
11690     {
11691       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11692       if (attr)
11693         {
11694           CORE_ADDR low = DW_ADDR (attr);
11695           CORE_ADDR high;
11696           if (attr_high->form == DW_FORM_addr
11697               || attr_high->form == DW_FORM_GNU_addr_index)
11698             high = DW_ADDR (attr_high);
11699           else
11700             high = low + DW_UNSND (attr_high);
11701
11702           record_block_range (block, baseaddr + low, baseaddr + high - 1);
11703         }
11704     }
11705
11706   attr = dwarf2_attr (die, DW_AT_ranges, cu);
11707   if (attr)
11708     {
11709       bfd *obfd = objfile->obfd;
11710       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11711          We take advantage of the fact that DW_AT_ranges does not appear
11712          in DW_TAG_compile_unit of DWO files.  */
11713       int need_ranges_base = die->tag != DW_TAG_compile_unit;
11714
11715       /* The value of the DW_AT_ranges attribute is the offset of the
11716          address range list in the .debug_ranges section.  */
11717       unsigned long offset = (DW_UNSND (attr)
11718                               + (need_ranges_base ? cu->ranges_base : 0));
11719       const gdb_byte *buffer;
11720
11721       /* For some target architectures, but not others, the
11722          read_address function sign-extends the addresses it returns.
11723          To recognize base address selection entries, we need a
11724          mask.  */
11725       unsigned int addr_size = cu->header.addr_size;
11726       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11727
11728       /* The base address, to which the next pair is relative.  Note
11729          that this 'base' is a DWARF concept: most entries in a range
11730          list are relative, to reduce the number of relocs against the
11731          debugging information.  This is separate from this function's
11732          'baseaddr' argument, which GDB uses to relocate debugging
11733          information from a shared library based on the address at
11734          which the library was loaded.  */
11735       CORE_ADDR base = cu->base_address;
11736       int base_known = cu->base_known;
11737
11738       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11739       if (offset >= dwarf2_per_objfile->ranges.size)
11740         {
11741           complaint (&symfile_complaints,
11742                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
11743                      offset);
11744           return;
11745         }
11746       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11747
11748       for (;;)
11749         {
11750           unsigned int bytes_read;
11751           CORE_ADDR start, end;
11752
11753           start = read_address (obfd, buffer, cu, &bytes_read);
11754           buffer += bytes_read;
11755           end = read_address (obfd, buffer, cu, &bytes_read);
11756           buffer += bytes_read;
11757
11758           /* Did we find the end of the range list?  */
11759           if (start == 0 && end == 0)
11760             break;
11761
11762           /* Did we find a base address selection entry?  */
11763           else if ((start & base_select_mask) == base_select_mask)
11764             {
11765               base = end;
11766               base_known = 1;
11767             }
11768
11769           /* We found an ordinary address range.  */
11770           else
11771             {
11772               if (!base_known)
11773                 {
11774                   complaint (&symfile_complaints,
11775                              _("Invalid .debug_ranges data "
11776                                "(no base address)"));
11777                   return;
11778                 }
11779
11780               if (start > end)
11781                 {
11782                   /* Inverted range entries are invalid.  */
11783                   complaint (&symfile_complaints,
11784                              _("Invalid .debug_ranges data "
11785                                "(inverted range)"));
11786                   return;
11787                 }
11788
11789               /* Empty range entries have no effect.  */
11790               if (start == end)
11791                 continue;
11792
11793               start += base + baseaddr;
11794               end += base + baseaddr;
11795
11796               /* A not-uncommon case of bad debug info.
11797                  Don't pollute the addrmap with bad data.  */
11798               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11799                 {
11800                   complaint (&symfile_complaints,
11801                              _(".debug_ranges entry has start address of zero"
11802                                " [in module %s]"), objfile_name (objfile));
11803                   continue;
11804                 }
11805
11806               record_block_range (block, start, end - 1);
11807             }
11808         }
11809     }
11810 }
11811
11812 /* Check whether the producer field indicates either of GCC < 4.6, or the
11813    Intel C/C++ compiler, and cache the result in CU.  */
11814
11815 static void
11816 check_producer (struct dwarf2_cu *cu)
11817 {
11818   const char *cs;
11819   int major, minor, release;
11820
11821   if (cu->producer == NULL)
11822     {
11823       /* For unknown compilers expect their behavior is DWARF version
11824          compliant.
11825
11826          GCC started to support .debug_types sections by -gdwarf-4 since
11827          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11828          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11829          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11830          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11831     }
11832   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11833     {
11834       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11835
11836       cs = &cu->producer[strlen ("GNU ")];
11837       while (*cs && !isdigit (*cs))
11838         cs++;
11839       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11840         {
11841           /* Not recognized as GCC.  */
11842         }
11843       else
11844         {
11845           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11846           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11847         }
11848     }
11849   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11850     cu->producer_is_icc = 1;
11851   else
11852     {
11853       /* For other non-GCC compilers, expect their behavior is DWARF version
11854          compliant.  */
11855     }
11856
11857   cu->checked_producer = 1;
11858 }
11859
11860 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11861    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11862    during 4.6.0 experimental.  */
11863
11864 static int
11865 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11866 {
11867   if (!cu->checked_producer)
11868     check_producer (cu);
11869
11870   return cu->producer_is_gxx_lt_4_6;
11871 }
11872
11873 /* Return the default accessibility type if it is not overriden by
11874    DW_AT_accessibility.  */
11875
11876 static enum dwarf_access_attribute
11877 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11878 {
11879   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11880     {
11881       /* The default DWARF 2 accessibility for members is public, the default
11882          accessibility for inheritance is private.  */
11883
11884       if (die->tag != DW_TAG_inheritance)
11885         return DW_ACCESS_public;
11886       else
11887         return DW_ACCESS_private;
11888     }
11889   else
11890     {
11891       /* DWARF 3+ defines the default accessibility a different way.  The same
11892          rules apply now for DW_TAG_inheritance as for the members and it only
11893          depends on the container kind.  */
11894
11895       if (die->parent->tag == DW_TAG_class_type)
11896         return DW_ACCESS_private;
11897       else
11898         return DW_ACCESS_public;
11899     }
11900 }
11901
11902 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11903    offset.  If the attribute was not found return 0, otherwise return
11904    1.  If it was found but could not properly be handled, set *OFFSET
11905    to 0.  */
11906
11907 static int
11908 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11909                              LONGEST *offset)
11910 {
11911   struct attribute *attr;
11912
11913   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11914   if (attr != NULL)
11915     {
11916       *offset = 0;
11917
11918       /* Note that we do not check for a section offset first here.
11919          This is because DW_AT_data_member_location is new in DWARF 4,
11920          so if we see it, we can assume that a constant form is really
11921          a constant and not a section offset.  */
11922       if (attr_form_is_constant (attr))
11923         *offset = dwarf2_get_attr_constant_value (attr, 0);
11924       else if (attr_form_is_section_offset (attr))
11925         dwarf2_complex_location_expr_complaint ();
11926       else if (attr_form_is_block (attr))
11927         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11928       else
11929         dwarf2_complex_location_expr_complaint ();
11930
11931       return 1;
11932     }
11933
11934   return 0;
11935 }
11936
11937 /* Add an aggregate field to the field list.  */
11938
11939 static void
11940 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11941                   struct dwarf2_cu *cu)
11942 {
11943   struct objfile *objfile = cu->objfile;
11944   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11945   struct nextfield *new_field;
11946   struct attribute *attr;
11947   struct field *fp;
11948   const char *fieldname = "";
11949
11950   /* Allocate a new field list entry and link it in.  */
11951   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11952   make_cleanup (xfree, new_field);
11953   memset (new_field, 0, sizeof (struct nextfield));
11954
11955   if (die->tag == DW_TAG_inheritance)
11956     {
11957       new_field->next = fip->baseclasses;
11958       fip->baseclasses = new_field;
11959     }
11960   else
11961     {
11962       new_field->next = fip->fields;
11963       fip->fields = new_field;
11964     }
11965   fip->nfields++;
11966
11967   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11968   if (attr)
11969     new_field->accessibility = DW_UNSND (attr);
11970   else
11971     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11972   if (new_field->accessibility != DW_ACCESS_public)
11973     fip->non_public_fields = 1;
11974
11975   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11976   if (attr)
11977     new_field->virtuality = DW_UNSND (attr);
11978   else
11979     new_field->virtuality = DW_VIRTUALITY_none;
11980
11981   fp = &new_field->field;
11982
11983   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11984     {
11985       LONGEST offset;
11986
11987       /* Data member other than a C++ static data member.  */
11988
11989       /* Get type of field.  */
11990       fp->type = die_type (die, cu);
11991
11992       SET_FIELD_BITPOS (*fp, 0);
11993
11994       /* Get bit size of field (zero if none).  */
11995       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11996       if (attr)
11997         {
11998           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11999         }
12000       else
12001         {
12002           FIELD_BITSIZE (*fp) = 0;
12003         }
12004
12005       /* Get bit offset of field.  */
12006       if (handle_data_member_location (die, cu, &offset))
12007         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12008       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12009       if (attr)
12010         {
12011           if (gdbarch_bits_big_endian (gdbarch))
12012             {
12013               /* For big endian bits, the DW_AT_bit_offset gives the
12014                  additional bit offset from the MSB of the containing
12015                  anonymous object to the MSB of the field.  We don't
12016                  have to do anything special since we don't need to
12017                  know the size of the anonymous object.  */
12018               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12019             }
12020           else
12021             {
12022               /* For little endian bits, compute the bit offset to the
12023                  MSB of the anonymous object, subtract off the number of
12024                  bits from the MSB of the field to the MSB of the
12025                  object, and then subtract off the number of bits of
12026                  the field itself.  The result is the bit offset of
12027                  the LSB of the field.  */
12028               int anonymous_size;
12029               int bit_offset = DW_UNSND (attr);
12030
12031               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12032               if (attr)
12033                 {
12034                   /* The size of the anonymous object containing
12035                      the bit field is explicit, so use the
12036                      indicated size (in bytes).  */
12037                   anonymous_size = DW_UNSND (attr);
12038                 }
12039               else
12040                 {
12041                   /* The size of the anonymous object containing
12042                      the bit field must be inferred from the type
12043                      attribute of the data member containing the
12044                      bit field.  */
12045                   anonymous_size = TYPE_LENGTH (fp->type);
12046                 }
12047               SET_FIELD_BITPOS (*fp,
12048                                 (FIELD_BITPOS (*fp)
12049                                  + anonymous_size * bits_per_byte
12050                                  - bit_offset - FIELD_BITSIZE (*fp)));
12051             }
12052         }
12053
12054       /* Get name of field.  */
12055       fieldname = dwarf2_name (die, cu);
12056       if (fieldname == NULL)
12057         fieldname = "";
12058
12059       /* The name is already allocated along with this objfile, so we don't
12060          need to duplicate it for the type.  */
12061       fp->name = fieldname;
12062
12063       /* Change accessibility for artificial fields (e.g. virtual table
12064          pointer or virtual base class pointer) to private.  */
12065       if (dwarf2_attr (die, DW_AT_artificial, cu))
12066         {
12067           FIELD_ARTIFICIAL (*fp) = 1;
12068           new_field->accessibility = DW_ACCESS_private;
12069           fip->non_public_fields = 1;
12070         }
12071     }
12072   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12073     {
12074       /* C++ static member.  */
12075
12076       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12077          is a declaration, but all versions of G++ as of this writing
12078          (so through at least 3.2.1) incorrectly generate
12079          DW_TAG_variable tags.  */
12080
12081       const char *physname;
12082
12083       /* Get name of field.  */
12084       fieldname = dwarf2_name (die, cu);
12085       if (fieldname == NULL)
12086         return;
12087
12088       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12089       if (attr
12090           /* Only create a symbol if this is an external value.
12091              new_symbol checks this and puts the value in the global symbol
12092              table, which we want.  If it is not external, new_symbol
12093              will try to put the value in cu->list_in_scope which is wrong.  */
12094           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12095         {
12096           /* A static const member, not much different than an enum as far as
12097              we're concerned, except that we can support more types.  */
12098           new_symbol (die, NULL, cu);
12099         }
12100
12101       /* Get physical name.  */
12102       physname = dwarf2_physname (fieldname, die, cu);
12103
12104       /* The name is already allocated along with this objfile, so we don't
12105          need to duplicate it for the type.  */
12106       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12107       FIELD_TYPE (*fp) = die_type (die, cu);
12108       FIELD_NAME (*fp) = fieldname;
12109     }
12110   else if (die->tag == DW_TAG_inheritance)
12111     {
12112       LONGEST offset;
12113
12114       /* C++ base class field.  */
12115       if (handle_data_member_location (die, cu, &offset))
12116         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12117       FIELD_BITSIZE (*fp) = 0;
12118       FIELD_TYPE (*fp) = die_type (die, cu);
12119       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12120       fip->nbaseclasses++;
12121     }
12122 }
12123
12124 /* Add a typedef defined in the scope of the FIP's class.  */
12125
12126 static void
12127 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12128                     struct dwarf2_cu *cu)
12129 {
12130   struct objfile *objfile = cu->objfile;
12131   struct typedef_field_list *new_field;
12132   struct attribute *attr;
12133   struct typedef_field *fp;
12134   char *fieldname = "";
12135
12136   /* Allocate a new field list entry and link it in.  */
12137   new_field = xzalloc (sizeof (*new_field));
12138   make_cleanup (xfree, new_field);
12139
12140   gdb_assert (die->tag == DW_TAG_typedef);
12141
12142   fp = &new_field->field;
12143
12144   /* Get name of field.  */
12145   fp->name = dwarf2_name (die, cu);
12146   if (fp->name == NULL)
12147     return;
12148
12149   fp->type = read_type_die (die, cu);
12150
12151   new_field->next = fip->typedef_field_list;
12152   fip->typedef_field_list = new_field;
12153   fip->typedef_field_list_count++;
12154 }
12155
12156 /* Create the vector of fields, and attach it to the type.  */
12157
12158 static void
12159 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12160                               struct dwarf2_cu *cu)
12161 {
12162   int nfields = fip->nfields;
12163
12164   /* Record the field count, allocate space for the array of fields,
12165      and create blank accessibility bitfields if necessary.  */
12166   TYPE_NFIELDS (type) = nfields;
12167   TYPE_FIELDS (type) = (struct field *)
12168     TYPE_ALLOC (type, sizeof (struct field) * nfields);
12169   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
12170
12171   if (fip->non_public_fields && cu->language != language_ada)
12172     {
12173       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12174
12175       TYPE_FIELD_PRIVATE_BITS (type) =
12176         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12177       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
12178
12179       TYPE_FIELD_PROTECTED_BITS (type) =
12180         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12181       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
12182
12183       TYPE_FIELD_IGNORE_BITS (type) =
12184         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12185       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
12186     }
12187
12188   /* If the type has baseclasses, allocate and clear a bit vector for
12189      TYPE_FIELD_VIRTUAL_BITS.  */
12190   if (fip->nbaseclasses && cu->language != language_ada)
12191     {
12192       int num_bytes = B_BYTES (fip->nbaseclasses);
12193       unsigned char *pointer;
12194
12195       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12196       pointer = TYPE_ALLOC (type, num_bytes);
12197       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
12198       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
12199       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
12200     }
12201
12202   /* Copy the saved-up fields into the field vector.  Start from the head of
12203      the list, adding to the tail of the field array, so that they end up in
12204      the same order in the array in which they were added to the list.  */
12205   while (nfields-- > 0)
12206     {
12207       struct nextfield *fieldp;
12208
12209       if (fip->fields)
12210         {
12211           fieldp = fip->fields;
12212           fip->fields = fieldp->next;
12213         }
12214       else
12215         {
12216           fieldp = fip->baseclasses;
12217           fip->baseclasses = fieldp->next;
12218         }
12219
12220       TYPE_FIELD (type, nfields) = fieldp->field;
12221       switch (fieldp->accessibility)
12222         {
12223         case DW_ACCESS_private:
12224           if (cu->language != language_ada)
12225             SET_TYPE_FIELD_PRIVATE (type, nfields);
12226           break;
12227
12228         case DW_ACCESS_protected:
12229           if (cu->language != language_ada)
12230             SET_TYPE_FIELD_PROTECTED (type, nfields);
12231           break;
12232
12233         case DW_ACCESS_public:
12234           break;
12235
12236         default:
12237           /* Unknown accessibility.  Complain and treat it as public.  */
12238           {
12239             complaint (&symfile_complaints, _("unsupported accessibility %d"),
12240                        fieldp->accessibility);
12241           }
12242           break;
12243         }
12244       if (nfields < fip->nbaseclasses)
12245         {
12246           switch (fieldp->virtuality)
12247             {
12248             case DW_VIRTUALITY_virtual:
12249             case DW_VIRTUALITY_pure_virtual:
12250               if (cu->language == language_ada)
12251                 error (_("unexpected virtuality in component of Ada type"));
12252               SET_TYPE_FIELD_VIRTUAL (type, nfields);
12253               break;
12254             }
12255         }
12256     }
12257 }
12258
12259 /* Return true if this member function is a constructor, false
12260    otherwise.  */
12261
12262 static int
12263 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
12264 {
12265   const char *fieldname;
12266   const char *typename;
12267   int len;
12268
12269   if (die->parent == NULL)
12270     return 0;
12271
12272   if (die->parent->tag != DW_TAG_structure_type
12273       && die->parent->tag != DW_TAG_union_type
12274       && die->parent->tag != DW_TAG_class_type)
12275     return 0;
12276
12277   fieldname = dwarf2_name (die, cu);
12278   typename = dwarf2_name (die->parent, cu);
12279   if (fieldname == NULL || typename == NULL)
12280     return 0;
12281
12282   len = strlen (fieldname);
12283   return (strncmp (fieldname, typename, len) == 0
12284           && (typename[len] == '\0' || typename[len] == '<'));
12285 }
12286
12287 /* Add a member function to the proper fieldlist.  */
12288
12289 static void
12290 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
12291                       struct type *type, struct dwarf2_cu *cu)
12292 {
12293   struct objfile *objfile = cu->objfile;
12294   struct attribute *attr;
12295   struct fnfieldlist *flp;
12296   int i;
12297   struct fn_field *fnp;
12298   const char *fieldname;
12299   struct nextfnfield *new_fnfield;
12300   struct type *this_type;
12301   enum dwarf_access_attribute accessibility;
12302
12303   if (cu->language == language_ada)
12304     error (_("unexpected member function in Ada type"));
12305
12306   /* Get name of member function.  */
12307   fieldname = dwarf2_name (die, cu);
12308   if (fieldname == NULL)
12309     return;
12310
12311   /* Look up member function name in fieldlist.  */
12312   for (i = 0; i < fip->nfnfields; i++)
12313     {
12314       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
12315         break;
12316     }
12317
12318   /* Create new list element if necessary.  */
12319   if (i < fip->nfnfields)
12320     flp = &fip->fnfieldlists[i];
12321   else
12322     {
12323       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
12324         {
12325           fip->fnfieldlists = (struct fnfieldlist *)
12326             xrealloc (fip->fnfieldlists,
12327                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
12328                       * sizeof (struct fnfieldlist));
12329           if (fip->nfnfields == 0)
12330             make_cleanup (free_current_contents, &fip->fnfieldlists);
12331         }
12332       flp = &fip->fnfieldlists[fip->nfnfields];
12333       flp->name = fieldname;
12334       flp->length = 0;
12335       flp->head = NULL;
12336       i = fip->nfnfields++;
12337     }
12338
12339   /* Create a new member function field and chain it to the field list
12340      entry.  */
12341   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
12342   make_cleanup (xfree, new_fnfield);
12343   memset (new_fnfield, 0, sizeof (struct nextfnfield));
12344   new_fnfield->next = flp->head;
12345   flp->head = new_fnfield;
12346   flp->length++;
12347
12348   /* Fill in the member function field info.  */
12349   fnp = &new_fnfield->fnfield;
12350
12351   /* Delay processing of the physname until later.  */
12352   if (cu->language == language_cplus || cu->language == language_java)
12353     {
12354       add_to_method_list (type, i, flp->length - 1, fieldname,
12355                           die, cu);
12356     }
12357   else
12358     {
12359       const char *physname = dwarf2_physname (fieldname, die, cu);
12360       fnp->physname = physname ? physname : "";
12361     }
12362
12363   fnp->type = alloc_type (objfile);
12364   this_type = read_type_die (die, cu);
12365   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
12366     {
12367       int nparams = TYPE_NFIELDS (this_type);
12368
12369       /* TYPE is the domain of this method, and THIS_TYPE is the type
12370            of the method itself (TYPE_CODE_METHOD).  */
12371       smash_to_method_type (fnp->type, type,
12372                             TYPE_TARGET_TYPE (this_type),
12373                             TYPE_FIELDS (this_type),
12374                             TYPE_NFIELDS (this_type),
12375                             TYPE_VARARGS (this_type));
12376
12377       /* Handle static member functions.
12378          Dwarf2 has no clean way to discern C++ static and non-static
12379          member functions.  G++ helps GDB by marking the first
12380          parameter for non-static member functions (which is the this
12381          pointer) as artificial.  We obtain this information from
12382          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
12383       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
12384         fnp->voffset = VOFFSET_STATIC;
12385     }
12386   else
12387     complaint (&symfile_complaints, _("member function type missing for '%s'"),
12388                dwarf2_full_name (fieldname, die, cu));
12389
12390   /* Get fcontext from DW_AT_containing_type if present.  */
12391   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12392     fnp->fcontext = die_containing_type (die, cu);
12393
12394   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
12395      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
12396
12397   /* Get accessibility.  */
12398   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12399   if (attr)
12400     accessibility = DW_UNSND (attr);
12401   else
12402     accessibility = dwarf2_default_access_attribute (die, cu);
12403   switch (accessibility)
12404     {
12405     case DW_ACCESS_private:
12406       fnp->is_private = 1;
12407       break;
12408     case DW_ACCESS_protected:
12409       fnp->is_protected = 1;
12410       break;
12411     }
12412
12413   /* Check for artificial methods.  */
12414   attr = dwarf2_attr (die, DW_AT_artificial, cu);
12415   if (attr && DW_UNSND (attr) != 0)
12416     fnp->is_artificial = 1;
12417
12418   fnp->is_constructor = dwarf2_is_constructor (die, cu);
12419
12420   /* Get index in virtual function table if it is a virtual member
12421      function.  For older versions of GCC, this is an offset in the
12422      appropriate virtual table, as specified by DW_AT_containing_type.
12423      For everyone else, it is an expression to be evaluated relative
12424      to the object address.  */
12425
12426   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
12427   if (attr)
12428     {
12429       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
12430         {
12431           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
12432             {
12433               /* Old-style GCC.  */
12434               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
12435             }
12436           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
12437                    || (DW_BLOCK (attr)->size > 1
12438                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
12439                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
12440             {
12441               struct dwarf_block blk;
12442               int offset;
12443
12444               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
12445                         ? 1 : 2);
12446               blk.size = DW_BLOCK (attr)->size - offset;
12447               blk.data = DW_BLOCK (attr)->data + offset;
12448               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
12449               if ((fnp->voffset % cu->header.addr_size) != 0)
12450                 dwarf2_complex_location_expr_complaint ();
12451               else
12452                 fnp->voffset /= cu->header.addr_size;
12453               fnp->voffset += 2;
12454             }
12455           else
12456             dwarf2_complex_location_expr_complaint ();
12457
12458           if (!fnp->fcontext)
12459             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
12460         }
12461       else if (attr_form_is_section_offset (attr))
12462         {
12463           dwarf2_complex_location_expr_complaint ();
12464         }
12465       else
12466         {
12467           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
12468                                                  fieldname);
12469         }
12470     }
12471   else
12472     {
12473       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12474       if (attr && DW_UNSND (attr))
12475         {
12476           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
12477           complaint (&symfile_complaints,
12478                      _("Member function \"%s\" (offset %d) is virtual "
12479                        "but the vtable offset is not specified"),
12480                      fieldname, die->offset.sect_off);
12481           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12482           TYPE_CPLUS_DYNAMIC (type) = 1;
12483         }
12484     }
12485 }
12486
12487 /* Create the vector of member function fields, and attach it to the type.  */
12488
12489 static void
12490 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
12491                                  struct dwarf2_cu *cu)
12492 {
12493   struct fnfieldlist *flp;
12494   int i;
12495
12496   if (cu->language == language_ada)
12497     error (_("unexpected member functions in Ada type"));
12498
12499   ALLOCATE_CPLUS_STRUCT_TYPE (type);
12500   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
12501     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
12502
12503   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
12504     {
12505       struct nextfnfield *nfp = flp->head;
12506       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
12507       int k;
12508
12509       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
12510       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
12511       fn_flp->fn_fields = (struct fn_field *)
12512         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
12513       for (k = flp->length; (k--, nfp); nfp = nfp->next)
12514         fn_flp->fn_fields[k] = nfp->fnfield;
12515     }
12516
12517   TYPE_NFN_FIELDS (type) = fip->nfnfields;
12518 }
12519
12520 /* Returns non-zero if NAME is the name of a vtable member in CU's
12521    language, zero otherwise.  */
12522 static int
12523 is_vtable_name (const char *name, struct dwarf2_cu *cu)
12524 {
12525   static const char vptr[] = "_vptr";
12526   static const char vtable[] = "vtable";
12527
12528   /* Look for the C++ and Java forms of the vtable.  */
12529   if ((cu->language == language_java
12530        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
12531        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
12532        && is_cplus_marker (name[sizeof (vptr) - 1])))
12533     return 1;
12534
12535   return 0;
12536 }
12537
12538 /* GCC outputs unnamed structures that are really pointers to member
12539    functions, with the ABI-specified layout.  If TYPE describes
12540    such a structure, smash it into a member function type.
12541
12542    GCC shouldn't do this; it should just output pointer to member DIEs.
12543    This is GCC PR debug/28767.  */
12544
12545 static void
12546 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
12547 {
12548   struct type *pfn_type, *domain_type, *new_type;
12549
12550   /* Check for a structure with no name and two children.  */
12551   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
12552     return;
12553
12554   /* Check for __pfn and __delta members.  */
12555   if (TYPE_FIELD_NAME (type, 0) == NULL
12556       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
12557       || TYPE_FIELD_NAME (type, 1) == NULL
12558       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
12559     return;
12560
12561   /* Find the type of the method.  */
12562   pfn_type = TYPE_FIELD_TYPE (type, 0);
12563   if (pfn_type == NULL
12564       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
12565       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
12566     return;
12567
12568   /* Look for the "this" argument.  */
12569   pfn_type = TYPE_TARGET_TYPE (pfn_type);
12570   if (TYPE_NFIELDS (pfn_type) == 0
12571       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
12572       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
12573     return;
12574
12575   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
12576   new_type = alloc_type (objfile);
12577   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
12578                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
12579                         TYPE_VARARGS (pfn_type));
12580   smash_to_methodptr_type (type, new_type);
12581 }
12582
12583 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
12584    (icc).  */
12585
12586 static int
12587 producer_is_icc (struct dwarf2_cu *cu)
12588 {
12589   if (!cu->checked_producer)
12590     check_producer (cu);
12591
12592   return cu->producer_is_icc;
12593 }
12594
12595 /* Called when we find the DIE that starts a structure or union scope
12596    (definition) to create a type for the structure or union.  Fill in
12597    the type's name and general properties; the members will not be
12598    processed until process_structure_scope.
12599
12600    NOTE: we need to call these functions regardless of whether or not the
12601    DIE has a DW_AT_name attribute, since it might be an anonymous
12602    structure or union.  This gets the type entered into our set of
12603    user defined types.
12604
12605    However, if the structure is incomplete (an opaque struct/union)
12606    then suppress creating a symbol table entry for it since gdb only
12607    wants to find the one with the complete definition.  Note that if
12608    it is complete, we just call new_symbol, which does it's own
12609    checking about whether the struct/union is anonymous or not (and
12610    suppresses creating a symbol table entry itself).  */
12611
12612 static struct type *
12613 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
12614 {
12615   struct objfile *objfile = cu->objfile;
12616   struct type *type;
12617   struct attribute *attr;
12618   const char *name;
12619
12620   /* If the definition of this type lives in .debug_types, read that type.
12621      Don't follow DW_AT_specification though, that will take us back up
12622      the chain and we want to go down.  */
12623   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12624   if (attr)
12625     {
12626       type = get_DW_AT_signature_type (die, attr, cu);
12627
12628       /* The type's CU may not be the same as CU.
12629          Ensure TYPE is recorded with CU in die_type_hash.  */
12630       return set_die_type (die, type, cu);
12631     }
12632
12633   type = alloc_type (objfile);
12634   INIT_CPLUS_SPECIFIC (type);
12635
12636   name = dwarf2_name (die, cu);
12637   if (name != NULL)
12638     {
12639       if (cu->language == language_cplus
12640           || cu->language == language_java)
12641         {
12642           const char *full_name = dwarf2_full_name (name, die, cu);
12643
12644           /* dwarf2_full_name might have already finished building the DIE's
12645              type.  If so, there is no need to continue.  */
12646           if (get_die_type (die, cu) != NULL)
12647             return get_die_type (die, cu);
12648
12649           TYPE_TAG_NAME (type) = full_name;
12650           if (die->tag == DW_TAG_structure_type
12651               || die->tag == DW_TAG_class_type)
12652             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12653         }
12654       else
12655         {
12656           /* The name is already allocated along with this objfile, so
12657              we don't need to duplicate it for the type.  */
12658           TYPE_TAG_NAME (type) = name;
12659           if (die->tag == DW_TAG_class_type)
12660             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12661         }
12662     }
12663
12664   if (die->tag == DW_TAG_structure_type)
12665     {
12666       TYPE_CODE (type) = TYPE_CODE_STRUCT;
12667     }
12668   else if (die->tag == DW_TAG_union_type)
12669     {
12670       TYPE_CODE (type) = TYPE_CODE_UNION;
12671     }
12672   else
12673     {
12674       TYPE_CODE (type) = TYPE_CODE_CLASS;
12675     }
12676
12677   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
12678     TYPE_DECLARED_CLASS (type) = 1;
12679
12680   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12681   if (attr)
12682     {
12683       TYPE_LENGTH (type) = DW_UNSND (attr);
12684     }
12685   else
12686     {
12687       TYPE_LENGTH (type) = 0;
12688     }
12689
12690   if (producer_is_icc (cu))
12691     {
12692       /* ICC does not output the required DW_AT_declaration
12693          on incomplete types, but gives them a size of zero.  */
12694     }
12695   else
12696     TYPE_STUB_SUPPORTED (type) = 1;
12697
12698   if (die_is_declaration (die, cu))
12699     TYPE_STUB (type) = 1;
12700   else if (attr == NULL && die->child == NULL
12701            && producer_is_realview (cu->producer))
12702     /* RealView does not output the required DW_AT_declaration
12703        on incomplete types.  */
12704     TYPE_STUB (type) = 1;
12705
12706   /* We need to add the type field to the die immediately so we don't
12707      infinitely recurse when dealing with pointers to the structure
12708      type within the structure itself.  */
12709   set_die_type (die, type, cu);
12710
12711   /* set_die_type should be already done.  */
12712   set_descriptive_type (type, die, cu);
12713
12714   return type;
12715 }
12716
12717 /* Finish creating a structure or union type, including filling in
12718    its members and creating a symbol for it.  */
12719
12720 static void
12721 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
12722 {
12723   struct objfile *objfile = cu->objfile;
12724   struct die_info *child_die = die->child;
12725   struct type *type;
12726
12727   type = get_die_type (die, cu);
12728   if (type == NULL)
12729     type = read_structure_type (die, cu);
12730
12731   if (die->child != NULL && ! die_is_declaration (die, cu))
12732     {
12733       struct field_info fi;
12734       struct die_info *child_die;
12735       VEC (symbolp) *template_args = NULL;
12736       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
12737
12738       memset (&fi, 0, sizeof (struct field_info));
12739
12740       child_die = die->child;
12741
12742       while (child_die && child_die->tag)
12743         {
12744           if (child_die->tag == DW_TAG_member
12745               || child_die->tag == DW_TAG_variable)
12746             {
12747               /* NOTE: carlton/2002-11-05: A C++ static data member
12748                  should be a DW_TAG_member that is a declaration, but
12749                  all versions of G++ as of this writing (so through at
12750                  least 3.2.1) incorrectly generate DW_TAG_variable
12751                  tags for them instead.  */
12752               dwarf2_add_field (&fi, child_die, cu);
12753             }
12754           else if (child_die->tag == DW_TAG_subprogram)
12755             {
12756               /* C++ member function.  */
12757               dwarf2_add_member_fn (&fi, child_die, type, cu);
12758             }
12759           else if (child_die->tag == DW_TAG_inheritance)
12760             {
12761               /* C++ base class field.  */
12762               dwarf2_add_field (&fi, child_die, cu);
12763             }
12764           else if (child_die->tag == DW_TAG_typedef)
12765             dwarf2_add_typedef (&fi, child_die, cu);
12766           else if (child_die->tag == DW_TAG_template_type_param
12767                    || child_die->tag == DW_TAG_template_value_param)
12768             {
12769               struct symbol *arg = new_symbol (child_die, NULL, cu);
12770
12771               if (arg != NULL)
12772                 VEC_safe_push (symbolp, template_args, arg);
12773             }
12774
12775           child_die = sibling_die (child_die);
12776         }
12777
12778       /* Attach template arguments to type.  */
12779       if (! VEC_empty (symbolp, template_args))
12780         {
12781           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12782           TYPE_N_TEMPLATE_ARGUMENTS (type)
12783             = VEC_length (symbolp, template_args);
12784           TYPE_TEMPLATE_ARGUMENTS (type)
12785             = obstack_alloc (&objfile->objfile_obstack,
12786                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12787                               * sizeof (struct symbol *)));
12788           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12789                   VEC_address (symbolp, template_args),
12790                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12791                    * sizeof (struct symbol *)));
12792           VEC_free (symbolp, template_args);
12793         }
12794
12795       /* Attach fields and member functions to the type.  */
12796       if (fi.nfields)
12797         dwarf2_attach_fields_to_type (&fi, type, cu);
12798       if (fi.nfnfields)
12799         {
12800           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12801
12802           /* Get the type which refers to the base class (possibly this
12803              class itself) which contains the vtable pointer for the current
12804              class from the DW_AT_containing_type attribute.  This use of
12805              DW_AT_containing_type is a GNU extension.  */
12806
12807           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12808             {
12809               struct type *t = die_containing_type (die, cu);
12810
12811               TYPE_VPTR_BASETYPE (type) = t;
12812               if (type == t)
12813                 {
12814                   int i;
12815
12816                   /* Our own class provides vtbl ptr.  */
12817                   for (i = TYPE_NFIELDS (t) - 1;
12818                        i >= TYPE_N_BASECLASSES (t);
12819                        --i)
12820                     {
12821                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12822
12823                       if (is_vtable_name (fieldname, cu))
12824                         {
12825                           TYPE_VPTR_FIELDNO (type) = i;
12826                           break;
12827                         }
12828                     }
12829
12830                   /* Complain if virtual function table field not found.  */
12831                   if (i < TYPE_N_BASECLASSES (t))
12832                     complaint (&symfile_complaints,
12833                                _("virtual function table pointer "
12834                                  "not found when defining class '%s'"),
12835                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12836                                "");
12837                 }
12838               else
12839                 {
12840                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12841                 }
12842             }
12843           else if (cu->producer
12844                    && strncmp (cu->producer,
12845                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12846             {
12847               /* The IBM XLC compiler does not provide direct indication
12848                  of the containing type, but the vtable pointer is
12849                  always named __vfp.  */
12850
12851               int i;
12852
12853               for (i = TYPE_NFIELDS (type) - 1;
12854                    i >= TYPE_N_BASECLASSES (type);
12855                    --i)
12856                 {
12857                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12858                     {
12859                       TYPE_VPTR_FIELDNO (type) = i;
12860                       TYPE_VPTR_BASETYPE (type) = type;
12861                       break;
12862                     }
12863                 }
12864             }
12865         }
12866
12867       /* Copy fi.typedef_field_list linked list elements content into the
12868          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12869       if (fi.typedef_field_list)
12870         {
12871           int i = fi.typedef_field_list_count;
12872
12873           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12874           TYPE_TYPEDEF_FIELD_ARRAY (type)
12875             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12876           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12877
12878           /* Reverse the list order to keep the debug info elements order.  */
12879           while (--i >= 0)
12880             {
12881               struct typedef_field *dest, *src;
12882
12883               dest = &TYPE_TYPEDEF_FIELD (type, i);
12884               src = &fi.typedef_field_list->field;
12885               fi.typedef_field_list = fi.typedef_field_list->next;
12886               *dest = *src;
12887             }
12888         }
12889
12890       do_cleanups (back_to);
12891
12892       if (HAVE_CPLUS_STRUCT (type))
12893         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12894     }
12895
12896   quirk_gcc_member_function_pointer (type, objfile);
12897
12898   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12899      snapshots) has been known to create a die giving a declaration
12900      for a class that has, as a child, a die giving a definition for a
12901      nested class.  So we have to process our children even if the
12902      current die is a declaration.  Normally, of course, a declaration
12903      won't have any children at all.  */
12904
12905   while (child_die != NULL && child_die->tag)
12906     {
12907       if (child_die->tag == DW_TAG_member
12908           || child_die->tag == DW_TAG_variable
12909           || child_die->tag == DW_TAG_inheritance
12910           || child_die->tag == DW_TAG_template_value_param
12911           || child_die->tag == DW_TAG_template_type_param)
12912         {
12913           /* Do nothing.  */
12914         }
12915       else
12916         process_die (child_die, cu);
12917
12918       child_die = sibling_die (child_die);
12919     }
12920
12921   /* Do not consider external references.  According to the DWARF standard,
12922      these DIEs are identified by the fact that they have no byte_size
12923      attribute, and a declaration attribute.  */
12924   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12925       || !die_is_declaration (die, cu))
12926     new_symbol (die, type, cu);
12927 }
12928
12929 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12930    complete the type's fields yet, or create any symbols.  */
12931
12932 static struct type *
12933 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12934 {
12935   struct objfile *objfile = cu->objfile;
12936   struct type *type;
12937   struct attribute *attr;
12938   const char *name;
12939
12940   /* If the definition of this type lives in .debug_types, read that type.
12941      Don't follow DW_AT_specification though, that will take us back up
12942      the chain and we want to go down.  */
12943   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12944   if (attr)
12945     {
12946       type = get_DW_AT_signature_type (die, attr, cu);
12947
12948       /* The type's CU may not be the same as CU.
12949          Ensure TYPE is recorded with CU in die_type_hash.  */
12950       return set_die_type (die, type, cu);
12951     }
12952
12953   type = alloc_type (objfile);
12954
12955   TYPE_CODE (type) = TYPE_CODE_ENUM;
12956   name = dwarf2_full_name (NULL, die, cu);
12957   if (name != NULL)
12958     TYPE_TAG_NAME (type) = name;
12959
12960   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12961   if (attr)
12962     {
12963       TYPE_LENGTH (type) = DW_UNSND (attr);
12964     }
12965   else
12966     {
12967       TYPE_LENGTH (type) = 0;
12968     }
12969
12970   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12971      declared as private in the package spec, and then defined only
12972      inside the package body.  Such types are known as Taft Amendment
12973      Types.  When another package uses such a type, an incomplete DIE
12974      may be generated by the compiler.  */
12975   if (die_is_declaration (die, cu))
12976     TYPE_STUB (type) = 1;
12977
12978   return set_die_type (die, type, cu);
12979 }
12980
12981 /* Given a pointer to a die which begins an enumeration, process all
12982    the dies that define the members of the enumeration, and create the
12983    symbol for the enumeration type.
12984
12985    NOTE: We reverse the order of the element list.  */
12986
12987 static void
12988 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12989 {
12990   struct type *this_type;
12991
12992   this_type = get_die_type (die, cu);
12993   if (this_type == NULL)
12994     this_type = read_enumeration_type (die, cu);
12995
12996   if (die->child != NULL)
12997     {
12998       struct die_info *child_die;
12999       struct symbol *sym;
13000       struct field *fields = NULL;
13001       int num_fields = 0;
13002       int unsigned_enum = 1;
13003       const char *name;
13004       int flag_enum = 1;
13005       ULONGEST mask = 0;
13006
13007       child_die = die->child;
13008       while (child_die && child_die->tag)
13009         {
13010           if (child_die->tag != DW_TAG_enumerator)
13011             {
13012               process_die (child_die, cu);
13013             }
13014           else
13015             {
13016               name = dwarf2_name (child_die, cu);
13017               if (name)
13018                 {
13019                   sym = new_symbol (child_die, this_type, cu);
13020                   if (SYMBOL_VALUE (sym) < 0)
13021                     {
13022                       unsigned_enum = 0;
13023                       flag_enum = 0;
13024                     }
13025                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
13026                     flag_enum = 0;
13027                   else
13028                     mask |= SYMBOL_VALUE (sym);
13029
13030                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13031                     {
13032                       fields = (struct field *)
13033                         xrealloc (fields,
13034                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13035                                   * sizeof (struct field));
13036                     }
13037
13038                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13039                   FIELD_TYPE (fields[num_fields]) = NULL;
13040                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13041                   FIELD_BITSIZE (fields[num_fields]) = 0;
13042
13043                   num_fields++;
13044                 }
13045             }
13046
13047           child_die = sibling_die (child_die);
13048         }
13049
13050       if (num_fields)
13051         {
13052           TYPE_NFIELDS (this_type) = num_fields;
13053           TYPE_FIELDS (this_type) = (struct field *)
13054             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13055           memcpy (TYPE_FIELDS (this_type), fields,
13056                   sizeof (struct field) * num_fields);
13057           xfree (fields);
13058         }
13059       if (unsigned_enum)
13060         TYPE_UNSIGNED (this_type) = 1;
13061       if (flag_enum)
13062         TYPE_FLAG_ENUM (this_type) = 1;
13063     }
13064
13065   /* If we are reading an enum from a .debug_types unit, and the enum
13066      is a declaration, and the enum is not the signatured type in the
13067      unit, then we do not want to add a symbol for it.  Adding a
13068      symbol would in some cases obscure the true definition of the
13069      enum, giving users an incomplete type when the definition is
13070      actually available.  Note that we do not want to do this for all
13071      enums which are just declarations, because C++0x allows forward
13072      enum declarations.  */
13073   if (cu->per_cu->is_debug_types
13074       && die_is_declaration (die, cu))
13075     {
13076       struct signatured_type *sig_type;
13077
13078       sig_type = (struct signatured_type *) cu->per_cu;
13079       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
13080       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
13081         return;
13082     }
13083
13084   new_symbol (die, this_type, cu);
13085 }
13086
13087 /* Extract all information from a DW_TAG_array_type DIE and put it in
13088    the DIE's type field.  For now, this only handles one dimensional
13089    arrays.  */
13090
13091 static struct type *
13092 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
13093 {
13094   struct objfile *objfile = cu->objfile;
13095   struct die_info *child_die;
13096   struct type *type;
13097   struct type *element_type, *range_type, *index_type;
13098   struct type **range_types = NULL;
13099   struct attribute *attr;
13100   int ndim = 0;
13101   struct cleanup *back_to;
13102   const char *name;
13103
13104   element_type = die_type (die, cu);
13105
13106   /* The die_type call above may have already set the type for this DIE.  */
13107   type = get_die_type (die, cu);
13108   if (type)
13109     return type;
13110
13111   /* Irix 6.2 native cc creates array types without children for
13112      arrays with unspecified length.  */
13113   if (die->child == NULL)
13114     {
13115       index_type = objfile_type (objfile)->builtin_int;
13116       range_type = create_range_type (NULL, index_type, 0, -1);
13117       type = create_array_type (NULL, element_type, range_type);
13118       return set_die_type (die, type, cu);
13119     }
13120
13121   back_to = make_cleanup (null_cleanup, NULL);
13122   child_die = die->child;
13123   while (child_die && child_die->tag)
13124     {
13125       if (child_die->tag == DW_TAG_subrange_type)
13126         {
13127           struct type *child_type = read_type_die (child_die, cu);
13128
13129           if (child_type != NULL)
13130             {
13131               /* The range type was succesfully read.  Save it for the
13132                  array type creation.  */
13133               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
13134                 {
13135                   range_types = (struct type **)
13136                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
13137                               * sizeof (struct type *));
13138                   if (ndim == 0)
13139                     make_cleanup (free_current_contents, &range_types);
13140                 }
13141               range_types[ndim++] = child_type;
13142             }
13143         }
13144       child_die = sibling_die (child_die);
13145     }
13146
13147   /* Dwarf2 dimensions are output from left to right, create the
13148      necessary array types in backwards order.  */
13149
13150   type = element_type;
13151
13152   if (read_array_order (die, cu) == DW_ORD_col_major)
13153     {
13154       int i = 0;
13155
13156       while (i < ndim)
13157         type = create_array_type (NULL, type, range_types[i++]);
13158     }
13159   else
13160     {
13161       while (ndim-- > 0)
13162         type = create_array_type (NULL, type, range_types[ndim]);
13163     }
13164
13165   /* Understand Dwarf2 support for vector types (like they occur on
13166      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
13167      array type.  This is not part of the Dwarf2/3 standard yet, but a
13168      custom vendor extension.  The main difference between a regular
13169      array and the vector variant is that vectors are passed by value
13170      to functions.  */
13171   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
13172   if (attr)
13173     make_vector_type (type);
13174
13175   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
13176      implementation may choose to implement triple vectors using this
13177      attribute.  */
13178   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13179   if (attr)
13180     {
13181       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
13182         TYPE_LENGTH (type) = DW_UNSND (attr);
13183       else
13184         complaint (&symfile_complaints,
13185                    _("DW_AT_byte_size for array type smaller "
13186                      "than the total size of elements"));
13187     }
13188
13189   name = dwarf2_name (die, cu);
13190   if (name)
13191     TYPE_NAME (type) = name;
13192
13193   /* Install the type in the die.  */
13194   set_die_type (die, type, cu);
13195
13196   /* set_die_type should be already done.  */
13197   set_descriptive_type (type, die, cu);
13198
13199   do_cleanups (back_to);
13200
13201   return type;
13202 }
13203
13204 static enum dwarf_array_dim_ordering
13205 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
13206 {
13207   struct attribute *attr;
13208
13209   attr = dwarf2_attr (die, DW_AT_ordering, cu);
13210
13211   if (attr) return DW_SND (attr);
13212
13213   /* GNU F77 is a special case, as at 08/2004 array type info is the
13214      opposite order to the dwarf2 specification, but data is still
13215      laid out as per normal fortran.
13216
13217      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
13218      version checking.  */
13219
13220   if (cu->language == language_fortran
13221       && cu->producer && strstr (cu->producer, "GNU F77"))
13222     {
13223       return DW_ORD_row_major;
13224     }
13225
13226   switch (cu->language_defn->la_array_ordering)
13227     {
13228     case array_column_major:
13229       return DW_ORD_col_major;
13230     case array_row_major:
13231     default:
13232       return DW_ORD_row_major;
13233     };
13234 }
13235
13236 /* Extract all information from a DW_TAG_set_type DIE and put it in
13237    the DIE's type field.  */
13238
13239 static struct type *
13240 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
13241 {
13242   struct type *domain_type, *set_type;
13243   struct attribute *attr;
13244
13245   domain_type = die_type (die, cu);
13246
13247   /* The die_type call above may have already set the type for this DIE.  */
13248   set_type = get_die_type (die, cu);
13249   if (set_type)
13250     return set_type;
13251
13252   set_type = create_set_type (NULL, domain_type);
13253
13254   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13255   if (attr)
13256     TYPE_LENGTH (set_type) = DW_UNSND (attr);
13257
13258   return set_die_type (die, set_type, cu);
13259 }
13260
13261 /* A helper for read_common_block that creates a locexpr baton.
13262    SYM is the symbol which we are marking as computed.
13263    COMMON_DIE is the DIE for the common block.
13264    COMMON_LOC is the location expression attribute for the common
13265    block itself.
13266    MEMBER_LOC is the location expression attribute for the particular
13267    member of the common block that we are processing.
13268    CU is the CU from which the above come.  */
13269
13270 static void
13271 mark_common_block_symbol_computed (struct symbol *sym,
13272                                    struct die_info *common_die,
13273                                    struct attribute *common_loc,
13274                                    struct attribute *member_loc,
13275                                    struct dwarf2_cu *cu)
13276 {
13277   struct objfile *objfile = dwarf2_per_objfile->objfile;
13278   struct dwarf2_locexpr_baton *baton;
13279   gdb_byte *ptr;
13280   unsigned int cu_off;
13281   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
13282   LONGEST offset = 0;
13283
13284   gdb_assert (common_loc && member_loc);
13285   gdb_assert (attr_form_is_block (common_loc));
13286   gdb_assert (attr_form_is_block (member_loc)
13287               || attr_form_is_constant (member_loc));
13288
13289   baton = obstack_alloc (&objfile->objfile_obstack,
13290                          sizeof (struct dwarf2_locexpr_baton));
13291   baton->per_cu = cu->per_cu;
13292   gdb_assert (baton->per_cu);
13293
13294   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
13295
13296   if (attr_form_is_constant (member_loc))
13297     {
13298       offset = dwarf2_get_attr_constant_value (member_loc, 0);
13299       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
13300     }
13301   else
13302     baton->size += DW_BLOCK (member_loc)->size;
13303
13304   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
13305   baton->data = ptr;
13306
13307   *ptr++ = DW_OP_call4;
13308   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
13309   store_unsigned_integer (ptr, 4, byte_order, cu_off);
13310   ptr += 4;
13311
13312   if (attr_form_is_constant (member_loc))
13313     {
13314       *ptr++ = DW_OP_addr;
13315       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
13316       ptr += cu->header.addr_size;
13317     }
13318   else
13319     {
13320       /* We have to copy the data here, because DW_OP_call4 will only
13321          use a DW_AT_location attribute.  */
13322       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
13323       ptr += DW_BLOCK (member_loc)->size;
13324     }
13325
13326   *ptr++ = DW_OP_plus;
13327   gdb_assert (ptr - baton->data == baton->size);
13328
13329   SYMBOL_LOCATION_BATON (sym) = baton;
13330   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
13331 }
13332
13333 /* Create appropriate locally-scoped variables for all the
13334    DW_TAG_common_block entries.  Also create a struct common_block
13335    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
13336    is used to sepate the common blocks name namespace from regular
13337    variable names.  */
13338
13339 static void
13340 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
13341 {
13342   struct attribute *attr;
13343
13344   attr = dwarf2_attr (die, DW_AT_location, cu);
13345   if (attr)
13346     {
13347       /* Support the .debug_loc offsets.  */
13348       if (attr_form_is_block (attr))
13349         {
13350           /* Ok.  */
13351         }
13352       else if (attr_form_is_section_offset (attr))
13353         {
13354           dwarf2_complex_location_expr_complaint ();
13355           attr = NULL;
13356         }
13357       else
13358         {
13359           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13360                                                  "common block member");
13361           attr = NULL;
13362         }
13363     }
13364
13365   if (die->child != NULL)
13366     {
13367       struct objfile *objfile = cu->objfile;
13368       struct die_info *child_die;
13369       size_t n_entries = 0, size;
13370       struct common_block *common_block;
13371       struct symbol *sym;
13372
13373       for (child_die = die->child;
13374            child_die && child_die->tag;
13375            child_die = sibling_die (child_die))
13376         ++n_entries;
13377
13378       size = (sizeof (struct common_block)
13379               + (n_entries - 1) * sizeof (struct symbol *));
13380       common_block = obstack_alloc (&objfile->objfile_obstack, size);
13381       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
13382       common_block->n_entries = 0;
13383
13384       for (child_die = die->child;
13385            child_die && child_die->tag;
13386            child_die = sibling_die (child_die))
13387         {
13388           /* Create the symbol in the DW_TAG_common_block block in the current
13389              symbol scope.  */
13390           sym = new_symbol (child_die, NULL, cu);
13391           if (sym != NULL)
13392             {
13393               struct attribute *member_loc;
13394
13395               common_block->contents[common_block->n_entries++] = sym;
13396
13397               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
13398                                         cu);
13399               if (member_loc)
13400                 {
13401                   /* GDB has handled this for a long time, but it is
13402                      not specified by DWARF.  It seems to have been
13403                      emitted by gfortran at least as recently as:
13404                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
13405                   complaint (&symfile_complaints,
13406                              _("Variable in common block has "
13407                                "DW_AT_data_member_location "
13408                                "- DIE at 0x%x [in module %s]"),
13409                              child_die->offset.sect_off,
13410                              objfile_name (cu->objfile));
13411
13412                   if (attr_form_is_section_offset (member_loc))
13413                     dwarf2_complex_location_expr_complaint ();
13414                   else if (attr_form_is_constant (member_loc)
13415                            || attr_form_is_block (member_loc))
13416                     {
13417                       if (attr)
13418                         mark_common_block_symbol_computed (sym, die, attr,
13419                                                            member_loc, cu);
13420                     }
13421                   else
13422                     dwarf2_complex_location_expr_complaint ();
13423                 }
13424             }
13425         }
13426
13427       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
13428       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
13429     }
13430 }
13431
13432 /* Create a type for a C++ namespace.  */
13433
13434 static struct type *
13435 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
13436 {
13437   struct objfile *objfile = cu->objfile;
13438   const char *previous_prefix, *name;
13439   int is_anonymous;
13440   struct type *type;
13441
13442   /* For extensions, reuse the type of the original namespace.  */
13443   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
13444     {
13445       struct die_info *ext_die;
13446       struct dwarf2_cu *ext_cu = cu;
13447
13448       ext_die = dwarf2_extension (die, &ext_cu);
13449       type = read_type_die (ext_die, ext_cu);
13450
13451       /* EXT_CU may not be the same as CU.
13452          Ensure TYPE is recorded with CU in die_type_hash.  */
13453       return set_die_type (die, type, cu);
13454     }
13455
13456   name = namespace_name (die, &is_anonymous, cu);
13457
13458   /* Now build the name of the current namespace.  */
13459
13460   previous_prefix = determine_prefix (die, cu);
13461   if (previous_prefix[0] != '\0')
13462     name = typename_concat (&objfile->objfile_obstack,
13463                             previous_prefix, name, 0, cu);
13464
13465   /* Create the type.  */
13466   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
13467                     objfile);
13468   TYPE_NAME (type) = name;
13469   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13470
13471   return set_die_type (die, type, cu);
13472 }
13473
13474 /* Read a C++ namespace.  */
13475
13476 static void
13477 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
13478 {
13479   struct objfile *objfile = cu->objfile;
13480   int is_anonymous;
13481
13482   /* Add a symbol associated to this if we haven't seen the namespace
13483      before.  Also, add a using directive if it's an anonymous
13484      namespace.  */
13485
13486   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
13487     {
13488       struct type *type;
13489
13490       type = read_type_die (die, cu);
13491       new_symbol (die, type, cu);
13492
13493       namespace_name (die, &is_anonymous, cu);
13494       if (is_anonymous)
13495         {
13496           const char *previous_prefix = determine_prefix (die, cu);
13497
13498           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
13499                                   NULL, NULL, 0, &objfile->objfile_obstack);
13500         }
13501     }
13502
13503   if (die->child != NULL)
13504     {
13505       struct die_info *child_die = die->child;
13506
13507       while (child_die && child_die->tag)
13508         {
13509           process_die (child_die, cu);
13510           child_die = sibling_die (child_die);
13511         }
13512     }
13513 }
13514
13515 /* Read a Fortran module as type.  This DIE can be only a declaration used for
13516    imported module.  Still we need that type as local Fortran "use ... only"
13517    declaration imports depend on the created type in determine_prefix.  */
13518
13519 static struct type *
13520 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
13521 {
13522   struct objfile *objfile = cu->objfile;
13523   const char *module_name;
13524   struct type *type;
13525
13526   module_name = dwarf2_name (die, cu);
13527   if (!module_name)
13528     complaint (&symfile_complaints,
13529                _("DW_TAG_module has no name, offset 0x%x"),
13530                die->offset.sect_off);
13531   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
13532
13533   /* determine_prefix uses TYPE_TAG_NAME.  */
13534   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13535
13536   return set_die_type (die, type, cu);
13537 }
13538
13539 /* Read a Fortran module.  */
13540
13541 static void
13542 read_module (struct die_info *die, struct dwarf2_cu *cu)
13543 {
13544   struct die_info *child_die = die->child;
13545
13546   while (child_die && child_die->tag)
13547     {
13548       process_die (child_die, cu);
13549       child_die = sibling_die (child_die);
13550     }
13551 }
13552
13553 /* Return the name of the namespace represented by DIE.  Set
13554    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
13555    namespace.  */
13556
13557 static const char *
13558 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
13559 {
13560   struct die_info *current_die;
13561   const char *name = NULL;
13562
13563   /* Loop through the extensions until we find a name.  */
13564
13565   for (current_die = die;
13566        current_die != NULL;
13567        current_die = dwarf2_extension (die, &cu))
13568     {
13569       name = dwarf2_name (current_die, cu);
13570       if (name != NULL)
13571         break;
13572     }
13573
13574   /* Is it an anonymous namespace?  */
13575
13576   *is_anonymous = (name == NULL);
13577   if (*is_anonymous)
13578     name = CP_ANONYMOUS_NAMESPACE_STR;
13579
13580   return name;
13581 }
13582
13583 /* Extract all information from a DW_TAG_pointer_type DIE and add to
13584    the user defined type vector.  */
13585
13586 static struct type *
13587 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
13588 {
13589   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
13590   struct comp_unit_head *cu_header = &cu->header;
13591   struct type *type;
13592   struct attribute *attr_byte_size;
13593   struct attribute *attr_address_class;
13594   int byte_size, addr_class;
13595   struct type *target_type;
13596
13597   target_type = die_type (die, cu);
13598
13599   /* The die_type call above may have already set the type for this DIE.  */
13600   type = get_die_type (die, cu);
13601   if (type)
13602     return type;
13603
13604   type = lookup_pointer_type (target_type);
13605
13606   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
13607   if (attr_byte_size)
13608     byte_size = DW_UNSND (attr_byte_size);
13609   else
13610     byte_size = cu_header->addr_size;
13611
13612   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
13613   if (attr_address_class)
13614     addr_class = DW_UNSND (attr_address_class);
13615   else
13616     addr_class = DW_ADDR_none;
13617
13618   /* If the pointer size or address class is different than the
13619      default, create a type variant marked as such and set the
13620      length accordingly.  */
13621   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
13622     {
13623       if (gdbarch_address_class_type_flags_p (gdbarch))
13624         {
13625           int type_flags;
13626
13627           type_flags = gdbarch_address_class_type_flags
13628                          (gdbarch, byte_size, addr_class);
13629           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
13630                       == 0);
13631           type = make_type_with_address_space (type, type_flags);
13632         }
13633       else if (TYPE_LENGTH (type) != byte_size)
13634         {
13635           complaint (&symfile_complaints,
13636                      _("invalid pointer size %d"), byte_size);
13637         }
13638       else
13639         {
13640           /* Should we also complain about unhandled address classes?  */
13641         }
13642     }
13643
13644   TYPE_LENGTH (type) = byte_size;
13645   return set_die_type (die, type, cu);
13646 }
13647
13648 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
13649    the user defined type vector.  */
13650
13651 static struct type *
13652 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
13653 {
13654   struct type *type;
13655   struct type *to_type;
13656   struct type *domain;
13657
13658   to_type = die_type (die, cu);
13659   domain = die_containing_type (die, cu);
13660
13661   /* The calls above may have already set the type for this DIE.  */
13662   type = get_die_type (die, cu);
13663   if (type)
13664     return type;
13665
13666   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
13667     type = lookup_methodptr_type (to_type);
13668   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
13669     {
13670       struct type *new_type = alloc_type (cu->objfile);
13671
13672       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
13673                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
13674                             TYPE_VARARGS (to_type));
13675       type = lookup_methodptr_type (new_type);
13676     }
13677   else
13678     type = lookup_memberptr_type (to_type, domain);
13679
13680   return set_die_type (die, type, cu);
13681 }
13682
13683 /* Extract all information from a DW_TAG_reference_type DIE and add to
13684    the user defined type vector.  */
13685
13686 static struct type *
13687 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
13688 {
13689   struct comp_unit_head *cu_header = &cu->header;
13690   struct type *type, *target_type;
13691   struct attribute *attr;
13692
13693   target_type = die_type (die, cu);
13694
13695   /* The die_type call above may have already set the type for this DIE.  */
13696   type = get_die_type (die, cu);
13697   if (type)
13698     return type;
13699
13700   type = lookup_reference_type (target_type);
13701   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13702   if (attr)
13703     {
13704       TYPE_LENGTH (type) = DW_UNSND (attr);
13705     }
13706   else
13707     {
13708       TYPE_LENGTH (type) = cu_header->addr_size;
13709     }
13710   return set_die_type (die, type, cu);
13711 }
13712
13713 static struct type *
13714 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
13715 {
13716   struct type *base_type, *cv_type;
13717
13718   base_type = die_type (die, cu);
13719
13720   /* The die_type call above may have already set the type for this DIE.  */
13721   cv_type = get_die_type (die, cu);
13722   if (cv_type)
13723     return cv_type;
13724
13725   /* In case the const qualifier is applied to an array type, the element type
13726      is so qualified, not the array type (section 6.7.3 of C99).  */
13727   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
13728     {
13729       struct type *el_type, *inner_array;
13730
13731       base_type = copy_type (base_type);
13732       inner_array = base_type;
13733
13734       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
13735         {
13736           TYPE_TARGET_TYPE (inner_array) =
13737             copy_type (TYPE_TARGET_TYPE (inner_array));
13738           inner_array = TYPE_TARGET_TYPE (inner_array);
13739         }
13740
13741       el_type = TYPE_TARGET_TYPE (inner_array);
13742       TYPE_TARGET_TYPE (inner_array) =
13743         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
13744
13745       return set_die_type (die, base_type, cu);
13746     }
13747
13748   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13749   return set_die_type (die, cv_type, cu);
13750 }
13751
13752 static struct type *
13753 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13754 {
13755   struct type *base_type, *cv_type;
13756
13757   base_type = die_type (die, cu);
13758
13759   /* The die_type call above may have already set the type for this DIE.  */
13760   cv_type = get_die_type (die, cu);
13761   if (cv_type)
13762     return cv_type;
13763
13764   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13765   return set_die_type (die, cv_type, cu);
13766 }
13767
13768 /* Handle DW_TAG_restrict_type.  */
13769
13770 static struct type *
13771 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13772 {
13773   struct type *base_type, *cv_type;
13774
13775   base_type = die_type (die, cu);
13776
13777   /* The die_type call above may have already set the type for this DIE.  */
13778   cv_type = get_die_type (die, cu);
13779   if (cv_type)
13780     return cv_type;
13781
13782   cv_type = make_restrict_type (base_type);
13783   return set_die_type (die, cv_type, cu);
13784 }
13785
13786 /* Extract all information from a DW_TAG_string_type DIE and add to
13787    the user defined type vector.  It isn't really a user defined type,
13788    but it behaves like one, with other DIE's using an AT_user_def_type
13789    attribute to reference it.  */
13790
13791 static struct type *
13792 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13793 {
13794   struct objfile *objfile = cu->objfile;
13795   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13796   struct type *type, *range_type, *index_type, *char_type;
13797   struct attribute *attr;
13798   unsigned int length;
13799
13800   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13801   if (attr)
13802     {
13803       length = DW_UNSND (attr);
13804     }
13805   else
13806     {
13807       /* Check for the DW_AT_byte_size attribute.  */
13808       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13809       if (attr)
13810         {
13811           length = DW_UNSND (attr);
13812         }
13813       else
13814         {
13815           length = 1;
13816         }
13817     }
13818
13819   index_type = objfile_type (objfile)->builtin_int;
13820   range_type = create_range_type (NULL, index_type, 1, length);
13821   char_type = language_string_char_type (cu->language_defn, gdbarch);
13822   type = create_string_type (NULL, char_type, range_type);
13823
13824   return set_die_type (die, type, cu);
13825 }
13826
13827 /* Assuming that DIE corresponds to a function, returns nonzero
13828    if the function is prototyped.  */
13829
13830 static int
13831 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13832 {
13833   struct attribute *attr;
13834
13835   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13836   if (attr && (DW_UNSND (attr) != 0))
13837     return 1;
13838
13839   /* The DWARF standard implies that the DW_AT_prototyped attribute
13840      is only meaninful for C, but the concept also extends to other
13841      languages that allow unprototyped functions (Eg: Objective C).
13842      For all other languages, assume that functions are always
13843      prototyped.  */
13844   if (cu->language != language_c
13845       && cu->language != language_objc
13846       && cu->language != language_opencl)
13847     return 1;
13848
13849   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13850      prototyped and unprototyped functions; default to prototyped,
13851      since that is more common in modern code (and RealView warns
13852      about unprototyped functions).  */
13853   if (producer_is_realview (cu->producer))
13854     return 1;
13855
13856   return 0;
13857 }
13858
13859 /* Handle DIES due to C code like:
13860
13861    struct foo
13862    {
13863    int (*funcp)(int a, long l);
13864    int b;
13865    };
13866
13867    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13868
13869 static struct type *
13870 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13871 {
13872   struct objfile *objfile = cu->objfile;
13873   struct type *type;            /* Type that this function returns.  */
13874   struct type *ftype;           /* Function that returns above type.  */
13875   struct attribute *attr;
13876
13877   type = die_type (die, cu);
13878
13879   /* The die_type call above may have already set the type for this DIE.  */
13880   ftype = get_die_type (die, cu);
13881   if (ftype)
13882     return ftype;
13883
13884   ftype = lookup_function_type (type);
13885
13886   if (prototyped_function_p (die, cu))
13887     TYPE_PROTOTYPED (ftype) = 1;
13888
13889   /* Store the calling convention in the type if it's available in
13890      the subroutine die.  Otherwise set the calling convention to
13891      the default value DW_CC_normal.  */
13892   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13893   if (attr)
13894     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13895   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13896     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13897   else
13898     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13899
13900   /* We need to add the subroutine type to the die immediately so
13901      we don't infinitely recurse when dealing with parameters
13902      declared as the same subroutine type.  */
13903   set_die_type (die, ftype, cu);
13904
13905   if (die->child != NULL)
13906     {
13907       struct type *void_type = objfile_type (objfile)->builtin_void;
13908       struct die_info *child_die;
13909       int nparams, iparams;
13910
13911       /* Count the number of parameters.
13912          FIXME: GDB currently ignores vararg functions, but knows about
13913          vararg member functions.  */
13914       nparams = 0;
13915       child_die = die->child;
13916       while (child_die && child_die->tag)
13917         {
13918           if (child_die->tag == DW_TAG_formal_parameter)
13919             nparams++;
13920           else if (child_die->tag == DW_TAG_unspecified_parameters)
13921             TYPE_VARARGS (ftype) = 1;
13922           child_die = sibling_die (child_die);
13923         }
13924
13925       /* Allocate storage for parameters and fill them in.  */
13926       TYPE_NFIELDS (ftype) = nparams;
13927       TYPE_FIELDS (ftype) = (struct field *)
13928         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13929
13930       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13931          even if we error out during the parameters reading below.  */
13932       for (iparams = 0; iparams < nparams; iparams++)
13933         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13934
13935       iparams = 0;
13936       child_die = die->child;
13937       while (child_die && child_die->tag)
13938         {
13939           if (child_die->tag == DW_TAG_formal_parameter)
13940             {
13941               struct type *arg_type;
13942
13943               /* DWARF version 2 has no clean way to discern C++
13944                  static and non-static member functions.  G++ helps
13945                  GDB by marking the first parameter for non-static
13946                  member functions (which is the this pointer) as
13947                  artificial.  We pass this information to
13948                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13949
13950                  DWARF version 3 added DW_AT_object_pointer, which GCC
13951                  4.5 does not yet generate.  */
13952               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13953               if (attr)
13954                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13955               else
13956                 {
13957                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13958
13959                   /* GCC/43521: In java, the formal parameter
13960                      "this" is sometimes not marked with DW_AT_artificial.  */
13961                   if (cu->language == language_java)
13962                     {
13963                       const char *name = dwarf2_name (child_die, cu);
13964
13965                       if (name && !strcmp (name, "this"))
13966                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13967                     }
13968                 }
13969               arg_type = die_type (child_die, cu);
13970
13971               /* RealView does not mark THIS as const, which the testsuite
13972                  expects.  GCC marks THIS as const in method definitions,
13973                  but not in the class specifications (GCC PR 43053).  */
13974               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13975                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13976                 {
13977                   int is_this = 0;
13978                   struct dwarf2_cu *arg_cu = cu;
13979                   const char *name = dwarf2_name (child_die, cu);
13980
13981                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13982                   if (attr)
13983                     {
13984                       /* If the compiler emits this, use it.  */
13985                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13986                         is_this = 1;
13987                     }
13988                   else if (name && strcmp (name, "this") == 0)
13989                     /* Function definitions will have the argument names.  */
13990                     is_this = 1;
13991                   else if (name == NULL && iparams == 0)
13992                     /* Declarations may not have the names, so like
13993                        elsewhere in GDB, assume an artificial first
13994                        argument is "this".  */
13995                     is_this = 1;
13996
13997                   if (is_this)
13998                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13999                                              arg_type, 0);
14000                 }
14001
14002               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
14003               iparams++;
14004             }
14005           child_die = sibling_die (child_die);
14006         }
14007     }
14008
14009   return ftype;
14010 }
14011
14012 static struct type *
14013 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
14014 {
14015   struct objfile *objfile = cu->objfile;
14016   const char *name = NULL;
14017   struct type *this_type, *target_type;
14018
14019   name = dwarf2_full_name (NULL, die, cu);
14020   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
14021                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
14022   TYPE_NAME (this_type) = name;
14023   set_die_type (die, this_type, cu);
14024   target_type = die_type (die, cu);
14025   if (target_type != this_type)
14026     TYPE_TARGET_TYPE (this_type) = target_type;
14027   else
14028     {
14029       /* Self-referential typedefs are, it seems, not allowed by the DWARF
14030          spec and cause infinite loops in GDB.  */
14031       complaint (&symfile_complaints,
14032                  _("Self-referential DW_TAG_typedef "
14033                    "- DIE at 0x%x [in module %s]"),
14034                  die->offset.sect_off, objfile_name (objfile));
14035       TYPE_TARGET_TYPE (this_type) = NULL;
14036     }
14037   return this_type;
14038 }
14039
14040 /* Find a representation of a given base type and install
14041    it in the TYPE field of the die.  */
14042
14043 static struct type *
14044 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
14045 {
14046   struct objfile *objfile = cu->objfile;
14047   struct type *type;
14048   struct attribute *attr;
14049   int encoding = 0, size = 0;
14050   const char *name;
14051   enum type_code code = TYPE_CODE_INT;
14052   int type_flags = 0;
14053   struct type *target_type = NULL;
14054
14055   attr = dwarf2_attr (die, DW_AT_encoding, cu);
14056   if (attr)
14057     {
14058       encoding = DW_UNSND (attr);
14059     }
14060   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14061   if (attr)
14062     {
14063       size = DW_UNSND (attr);
14064     }
14065   name = dwarf2_name (die, cu);
14066   if (!name)
14067     {
14068       complaint (&symfile_complaints,
14069                  _("DW_AT_name missing from DW_TAG_base_type"));
14070     }
14071
14072   switch (encoding)
14073     {
14074       case DW_ATE_address:
14075         /* Turn DW_ATE_address into a void * pointer.  */
14076         code = TYPE_CODE_PTR;
14077         type_flags |= TYPE_FLAG_UNSIGNED;
14078         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
14079         break;
14080       case DW_ATE_boolean:
14081         code = TYPE_CODE_BOOL;
14082         type_flags |= TYPE_FLAG_UNSIGNED;
14083         break;
14084       case DW_ATE_complex_float:
14085         code = TYPE_CODE_COMPLEX;
14086         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
14087         break;
14088       case DW_ATE_decimal_float:
14089         code = TYPE_CODE_DECFLOAT;
14090         break;
14091       case DW_ATE_float:
14092         code = TYPE_CODE_FLT;
14093         break;
14094       case DW_ATE_signed:
14095         break;
14096       case DW_ATE_unsigned:
14097         type_flags |= TYPE_FLAG_UNSIGNED;
14098         if (cu->language == language_fortran
14099             && name
14100             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
14101           code = TYPE_CODE_CHAR;
14102         break;
14103       case DW_ATE_signed_char:
14104         if (cu->language == language_ada || cu->language == language_m2
14105             || cu->language == language_pascal
14106             || cu->language == language_fortran)
14107           code = TYPE_CODE_CHAR;
14108         break;
14109       case DW_ATE_unsigned_char:
14110         if (cu->language == language_ada || cu->language == language_m2
14111             || cu->language == language_pascal
14112             || cu->language == language_fortran)
14113           code = TYPE_CODE_CHAR;
14114         type_flags |= TYPE_FLAG_UNSIGNED;
14115         break;
14116       case DW_ATE_UTF:
14117         /* We just treat this as an integer and then recognize the
14118            type by name elsewhere.  */
14119         break;
14120
14121       default:
14122         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
14123                    dwarf_type_encoding_name (encoding));
14124         break;
14125     }
14126
14127   type = init_type (code, size, type_flags, NULL, objfile);
14128   TYPE_NAME (type) = name;
14129   TYPE_TARGET_TYPE (type) = target_type;
14130
14131   if (name && strcmp (name, "char") == 0)
14132     TYPE_NOSIGN (type) = 1;
14133
14134   return set_die_type (die, type, cu);
14135 }
14136
14137 /* Read the given DW_AT_subrange DIE.  */
14138
14139 static struct type *
14140 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
14141 {
14142   struct type *base_type, *orig_base_type;
14143   struct type *range_type;
14144   struct attribute *attr;
14145   LONGEST low, high;
14146   int low_default_is_valid;
14147   const char *name;
14148   LONGEST negative_mask;
14149
14150   orig_base_type = die_type (die, cu);
14151   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
14152      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
14153      creating the range type, but we use the result of check_typedef
14154      when examining properties of the type.  */
14155   base_type = check_typedef (orig_base_type);
14156
14157   /* The die_type call above may have already set the type for this DIE.  */
14158   range_type = get_die_type (die, cu);
14159   if (range_type)
14160     return range_type;
14161
14162   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
14163      omitting DW_AT_lower_bound.  */
14164   switch (cu->language)
14165     {
14166     case language_c:
14167     case language_cplus:
14168       low = 0;
14169       low_default_is_valid = 1;
14170       break;
14171     case language_fortran:
14172       low = 1;
14173       low_default_is_valid = 1;
14174       break;
14175     case language_d:
14176     case language_java:
14177     case language_objc:
14178       low = 0;
14179       low_default_is_valid = (cu->header.version >= 4);
14180       break;
14181     case language_ada:
14182     case language_m2:
14183     case language_pascal:
14184       low = 1;
14185       low_default_is_valid = (cu->header.version >= 4);
14186       break;
14187     default:
14188       low = 0;
14189       low_default_is_valid = 0;
14190       break;
14191     }
14192
14193   /* FIXME: For variable sized arrays either of these could be
14194      a variable rather than a constant value.  We'll allow it,
14195      but we don't know how to handle it.  */
14196   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
14197   if (attr)
14198     low = dwarf2_get_attr_constant_value (attr, low);
14199   else if (!low_default_is_valid)
14200     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
14201                                       "- DIE at 0x%x [in module %s]"),
14202                die->offset.sect_off, objfile_name (cu->objfile));
14203
14204   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
14205   if (attr)
14206     {
14207       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
14208         {
14209           /* GCC encodes arrays with unspecified or dynamic length
14210              with a DW_FORM_block1 attribute or a reference attribute.
14211              FIXME: GDB does not yet know how to handle dynamic
14212              arrays properly, treat them as arrays with unspecified
14213              length for now.
14214
14215              FIXME: jimb/2003-09-22: GDB does not really know
14216              how to handle arrays of unspecified length
14217              either; we just represent them as zero-length
14218              arrays.  Choose an appropriate upper bound given
14219              the lower bound we've computed above.  */
14220           high = low - 1;
14221         }
14222       else
14223         high = dwarf2_get_attr_constant_value (attr, 1);
14224     }
14225   else
14226     {
14227       attr = dwarf2_attr (die, DW_AT_count, cu);
14228       if (attr)
14229         {
14230           int count = dwarf2_get_attr_constant_value (attr, 1);
14231           high = low + count - 1;
14232         }
14233       else
14234         {
14235           /* Unspecified array length.  */
14236           high = low - 1;
14237         }
14238     }
14239
14240   /* Dwarf-2 specifications explicitly allows to create subrange types
14241      without specifying a base type.
14242      In that case, the base type must be set to the type of
14243      the lower bound, upper bound or count, in that order, if any of these
14244      three attributes references an object that has a type.
14245      If no base type is found, the Dwarf-2 specifications say that
14246      a signed integer type of size equal to the size of an address should
14247      be used.
14248      For the following C code: `extern char gdb_int [];'
14249      GCC produces an empty range DIE.
14250      FIXME: muller/2010-05-28: Possible references to object for low bound,
14251      high bound or count are not yet handled by this code.  */
14252   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
14253     {
14254       struct objfile *objfile = cu->objfile;
14255       struct gdbarch *gdbarch = get_objfile_arch (objfile);
14256       int addr_size = gdbarch_addr_bit (gdbarch) /8;
14257       struct type *int_type = objfile_type (objfile)->builtin_int;
14258
14259       /* Test "int", "long int", and "long long int" objfile types,
14260          and select the first one having a size above or equal to the
14261          architecture address size.  */
14262       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14263         base_type = int_type;
14264       else
14265         {
14266           int_type = objfile_type (objfile)->builtin_long;
14267           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14268             base_type = int_type;
14269           else
14270             {
14271               int_type = objfile_type (objfile)->builtin_long_long;
14272               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14273                 base_type = int_type;
14274             }
14275         }
14276     }
14277
14278   negative_mask =
14279     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
14280   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
14281     low |= negative_mask;
14282   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
14283     high |= negative_mask;
14284
14285   range_type = create_range_type (NULL, orig_base_type, low, high);
14286
14287   /* Mark arrays with dynamic length at least as an array of unspecified
14288      length.  GDB could check the boundary but before it gets implemented at
14289      least allow accessing the array elements.  */
14290   if (attr && attr_form_is_block (attr))
14291     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14292
14293   /* Ada expects an empty array on no boundary attributes.  */
14294   if (attr == NULL && cu->language != language_ada)
14295     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14296
14297   name = dwarf2_name (die, cu);
14298   if (name)
14299     TYPE_NAME (range_type) = name;
14300
14301   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14302   if (attr)
14303     TYPE_LENGTH (range_type) = DW_UNSND (attr);
14304
14305   set_die_type (die, range_type, cu);
14306
14307   /* set_die_type should be already done.  */
14308   set_descriptive_type (range_type, die, cu);
14309
14310   return range_type;
14311 }
14312
14313 static struct type *
14314 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
14315 {
14316   struct type *type;
14317
14318   /* For now, we only support the C meaning of an unspecified type: void.  */
14319
14320   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
14321   TYPE_NAME (type) = dwarf2_name (die, cu);
14322
14323   return set_die_type (die, type, cu);
14324 }
14325
14326 /* Read a single die and all its descendents.  Set the die's sibling
14327    field to NULL; set other fields in the die correctly, and set all
14328    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
14329    location of the info_ptr after reading all of those dies.  PARENT
14330    is the parent of the die in question.  */
14331
14332 static struct die_info *
14333 read_die_and_children (const struct die_reader_specs *reader,
14334                        const gdb_byte *info_ptr,
14335                        const gdb_byte **new_info_ptr,
14336                        struct die_info *parent)
14337 {
14338   struct die_info *die;
14339   const gdb_byte *cur_ptr;
14340   int has_children;
14341
14342   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
14343   if (die == NULL)
14344     {
14345       *new_info_ptr = cur_ptr;
14346       return NULL;
14347     }
14348   store_in_ref_table (die, reader->cu);
14349
14350   if (has_children)
14351     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
14352   else
14353     {
14354       die->child = NULL;
14355       *new_info_ptr = cur_ptr;
14356     }
14357
14358   die->sibling = NULL;
14359   die->parent = parent;
14360   return die;
14361 }
14362
14363 /* Read a die, all of its descendents, and all of its siblings; set
14364    all of the fields of all of the dies correctly.  Arguments are as
14365    in read_die_and_children.  */
14366
14367 static struct die_info *
14368 read_die_and_siblings_1 (const struct die_reader_specs *reader,
14369                          const gdb_byte *info_ptr,
14370                          const gdb_byte **new_info_ptr,
14371                          struct die_info *parent)
14372 {
14373   struct die_info *first_die, *last_sibling;
14374   const gdb_byte *cur_ptr;
14375
14376   cur_ptr = info_ptr;
14377   first_die = last_sibling = NULL;
14378
14379   while (1)
14380     {
14381       struct die_info *die
14382         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
14383
14384       if (die == NULL)
14385         {
14386           *new_info_ptr = cur_ptr;
14387           return first_die;
14388         }
14389
14390       if (!first_die)
14391         first_die = die;
14392       else
14393         last_sibling->sibling = die;
14394
14395       last_sibling = die;
14396     }
14397 }
14398
14399 /* Read a die, all of its descendents, and all of its siblings; set
14400    all of the fields of all of the dies correctly.  Arguments are as
14401    in read_die_and_children.
14402    This the main entry point for reading a DIE and all its children.  */
14403
14404 static struct die_info *
14405 read_die_and_siblings (const struct die_reader_specs *reader,
14406                        const gdb_byte *info_ptr,
14407                        const gdb_byte **new_info_ptr,
14408                        struct die_info *parent)
14409 {
14410   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
14411                                                   new_info_ptr, parent);
14412
14413   if (dwarf2_die_debug)
14414     {
14415       fprintf_unfiltered (gdb_stdlog,
14416                           "Read die from %s@0x%x of %s:\n",
14417                           get_section_name (reader->die_section),
14418                           (unsigned) (info_ptr - reader->die_section->buffer),
14419                           bfd_get_filename (reader->abfd));
14420       dump_die (die, dwarf2_die_debug);
14421     }
14422
14423   return die;
14424 }
14425
14426 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
14427    attributes.
14428    The caller is responsible for filling in the extra attributes
14429    and updating (*DIEP)->num_attrs.
14430    Set DIEP to point to a newly allocated die with its information,
14431    except for its child, sibling, and parent fields.
14432    Set HAS_CHILDREN to tell whether the die has children or not.  */
14433
14434 static const gdb_byte *
14435 read_full_die_1 (const struct die_reader_specs *reader,
14436                  struct die_info **diep, const gdb_byte *info_ptr,
14437                  int *has_children, int num_extra_attrs)
14438 {
14439   unsigned int abbrev_number, bytes_read, i;
14440   sect_offset offset;
14441   struct abbrev_info *abbrev;
14442   struct die_info *die;
14443   struct dwarf2_cu *cu = reader->cu;
14444   bfd *abfd = reader->abfd;
14445
14446   offset.sect_off = info_ptr - reader->buffer;
14447   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14448   info_ptr += bytes_read;
14449   if (!abbrev_number)
14450     {
14451       *diep = NULL;
14452       *has_children = 0;
14453       return info_ptr;
14454     }
14455
14456   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
14457   if (!abbrev)
14458     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
14459            abbrev_number,
14460            bfd_get_filename (abfd));
14461
14462   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
14463   die->offset = offset;
14464   die->tag = abbrev->tag;
14465   die->abbrev = abbrev_number;
14466
14467   /* Make the result usable.
14468      The caller needs to update num_attrs after adding the extra
14469      attributes.  */
14470   die->num_attrs = abbrev->num_attrs;
14471
14472   for (i = 0; i < abbrev->num_attrs; ++i)
14473     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
14474                                info_ptr);
14475
14476   *diep = die;
14477   *has_children = abbrev->has_children;
14478   return info_ptr;
14479 }
14480
14481 /* Read a die and all its attributes.
14482    Set DIEP to point to a newly allocated die with its information,
14483    except for its child, sibling, and parent fields.
14484    Set HAS_CHILDREN to tell whether the die has children or not.  */
14485
14486 static const gdb_byte *
14487 read_full_die (const struct die_reader_specs *reader,
14488                struct die_info **diep, const gdb_byte *info_ptr,
14489                int *has_children)
14490 {
14491   const gdb_byte *result;
14492
14493   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
14494
14495   if (dwarf2_die_debug)
14496     {
14497       fprintf_unfiltered (gdb_stdlog,
14498                           "Read die from %s@0x%x of %s:\n",
14499                           get_section_name (reader->die_section),
14500                           (unsigned) (info_ptr - reader->die_section->buffer),
14501                           bfd_get_filename (reader->abfd));
14502       dump_die (*diep, dwarf2_die_debug);
14503     }
14504
14505   return result;
14506 }
14507 \f
14508 /* Abbreviation tables.
14509
14510    In DWARF version 2, the description of the debugging information is
14511    stored in a separate .debug_abbrev section.  Before we read any
14512    dies from a section we read in all abbreviations and install them
14513    in a hash table.  */
14514
14515 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
14516
14517 static struct abbrev_info *
14518 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
14519 {
14520   struct abbrev_info *abbrev;
14521
14522   abbrev = (struct abbrev_info *)
14523     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
14524   memset (abbrev, 0, sizeof (struct abbrev_info));
14525   return abbrev;
14526 }
14527
14528 /* Add an abbreviation to the table.  */
14529
14530 static void
14531 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
14532                          unsigned int abbrev_number,
14533                          struct abbrev_info *abbrev)
14534 {
14535   unsigned int hash_number;
14536
14537   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14538   abbrev->next = abbrev_table->abbrevs[hash_number];
14539   abbrev_table->abbrevs[hash_number] = abbrev;
14540 }
14541
14542 /* Look up an abbrev in the table.
14543    Returns NULL if the abbrev is not found.  */
14544
14545 static struct abbrev_info *
14546 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
14547                             unsigned int abbrev_number)
14548 {
14549   unsigned int hash_number;
14550   struct abbrev_info *abbrev;
14551
14552   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14553   abbrev = abbrev_table->abbrevs[hash_number];
14554
14555   while (abbrev)
14556     {
14557       if (abbrev->number == abbrev_number)
14558         return abbrev;
14559       abbrev = abbrev->next;
14560     }
14561   return NULL;
14562 }
14563
14564 /* Read in an abbrev table.  */
14565
14566 static struct abbrev_table *
14567 abbrev_table_read_table (struct dwarf2_section_info *section,
14568                          sect_offset offset)
14569 {
14570   struct objfile *objfile = dwarf2_per_objfile->objfile;
14571   bfd *abfd = get_section_bfd_owner (section);
14572   struct abbrev_table *abbrev_table;
14573   const gdb_byte *abbrev_ptr;
14574   struct abbrev_info *cur_abbrev;
14575   unsigned int abbrev_number, bytes_read, abbrev_name;
14576   unsigned int abbrev_form;
14577   struct attr_abbrev *cur_attrs;
14578   unsigned int allocated_attrs;
14579
14580   abbrev_table = XMALLOC (struct abbrev_table);
14581   abbrev_table->offset = offset;
14582   obstack_init (&abbrev_table->abbrev_obstack);
14583   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
14584                                          (ABBREV_HASH_SIZE
14585                                           * sizeof (struct abbrev_info *)));
14586   memset (abbrev_table->abbrevs, 0,
14587           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
14588
14589   dwarf2_read_section (objfile, section);
14590   abbrev_ptr = section->buffer + offset.sect_off;
14591   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14592   abbrev_ptr += bytes_read;
14593
14594   allocated_attrs = ATTR_ALLOC_CHUNK;
14595   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
14596
14597   /* Loop until we reach an abbrev number of 0.  */
14598   while (abbrev_number)
14599     {
14600       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
14601
14602       /* read in abbrev header */
14603       cur_abbrev->number = abbrev_number;
14604       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14605       abbrev_ptr += bytes_read;
14606       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
14607       abbrev_ptr += 1;
14608
14609       /* now read in declarations */
14610       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14611       abbrev_ptr += bytes_read;
14612       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14613       abbrev_ptr += bytes_read;
14614       while (abbrev_name)
14615         {
14616           if (cur_abbrev->num_attrs == allocated_attrs)
14617             {
14618               allocated_attrs += ATTR_ALLOC_CHUNK;
14619               cur_attrs
14620                 = xrealloc (cur_attrs, (allocated_attrs
14621                                         * sizeof (struct attr_abbrev)));
14622             }
14623
14624           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
14625           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
14626           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14627           abbrev_ptr += bytes_read;
14628           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14629           abbrev_ptr += bytes_read;
14630         }
14631
14632       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
14633                                          (cur_abbrev->num_attrs
14634                                           * sizeof (struct attr_abbrev)));
14635       memcpy (cur_abbrev->attrs, cur_attrs,
14636               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
14637
14638       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
14639
14640       /* Get next abbreviation.
14641          Under Irix6 the abbreviations for a compilation unit are not
14642          always properly terminated with an abbrev number of 0.
14643          Exit loop if we encounter an abbreviation which we have
14644          already read (which means we are about to read the abbreviations
14645          for the next compile unit) or if the end of the abbreviation
14646          table is reached.  */
14647       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
14648         break;
14649       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14650       abbrev_ptr += bytes_read;
14651       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
14652         break;
14653     }
14654
14655   xfree (cur_attrs);
14656   return abbrev_table;
14657 }
14658
14659 /* Free the resources held by ABBREV_TABLE.  */
14660
14661 static void
14662 abbrev_table_free (struct abbrev_table *abbrev_table)
14663 {
14664   obstack_free (&abbrev_table->abbrev_obstack, NULL);
14665   xfree (abbrev_table);
14666 }
14667
14668 /* Same as abbrev_table_free but as a cleanup.
14669    We pass in a pointer to the pointer to the table so that we can
14670    set the pointer to NULL when we're done.  It also simplifies
14671    build_type_unit_groups.  */
14672
14673 static void
14674 abbrev_table_free_cleanup (void *table_ptr)
14675 {
14676   struct abbrev_table **abbrev_table_ptr = table_ptr;
14677
14678   if (*abbrev_table_ptr != NULL)
14679     abbrev_table_free (*abbrev_table_ptr);
14680   *abbrev_table_ptr = NULL;
14681 }
14682
14683 /* Read the abbrev table for CU from ABBREV_SECTION.  */
14684
14685 static void
14686 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
14687                      struct dwarf2_section_info *abbrev_section)
14688 {
14689   cu->abbrev_table =
14690     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
14691 }
14692
14693 /* Release the memory used by the abbrev table for a compilation unit.  */
14694
14695 static void
14696 dwarf2_free_abbrev_table (void *ptr_to_cu)
14697 {
14698   struct dwarf2_cu *cu = ptr_to_cu;
14699
14700   if (cu->abbrev_table != NULL)
14701     abbrev_table_free (cu->abbrev_table);
14702   /* Set this to NULL so that we SEGV if we try to read it later,
14703      and also because free_comp_unit verifies this is NULL.  */
14704   cu->abbrev_table = NULL;
14705 }
14706 \f
14707 /* Returns nonzero if TAG represents a type that we might generate a partial
14708    symbol for.  */
14709
14710 static int
14711 is_type_tag_for_partial (int tag)
14712 {
14713   switch (tag)
14714     {
14715 #if 0
14716     /* Some types that would be reasonable to generate partial symbols for,
14717        that we don't at present.  */
14718     case DW_TAG_array_type:
14719     case DW_TAG_file_type:
14720     case DW_TAG_ptr_to_member_type:
14721     case DW_TAG_set_type:
14722     case DW_TAG_string_type:
14723     case DW_TAG_subroutine_type:
14724 #endif
14725     case DW_TAG_base_type:
14726     case DW_TAG_class_type:
14727     case DW_TAG_interface_type:
14728     case DW_TAG_enumeration_type:
14729     case DW_TAG_structure_type:
14730     case DW_TAG_subrange_type:
14731     case DW_TAG_typedef:
14732     case DW_TAG_union_type:
14733       return 1;
14734     default:
14735       return 0;
14736     }
14737 }
14738
14739 /* Load all DIEs that are interesting for partial symbols into memory.  */
14740
14741 static struct partial_die_info *
14742 load_partial_dies (const struct die_reader_specs *reader,
14743                    const gdb_byte *info_ptr, int building_psymtab)
14744 {
14745   struct dwarf2_cu *cu = reader->cu;
14746   struct objfile *objfile = cu->objfile;
14747   struct partial_die_info *part_die;
14748   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14749   struct abbrev_info *abbrev;
14750   unsigned int bytes_read;
14751   unsigned int load_all = 0;
14752   int nesting_level = 1;
14753
14754   parent_die = NULL;
14755   last_die = NULL;
14756
14757   gdb_assert (cu->per_cu != NULL);
14758   if (cu->per_cu->load_all_dies)
14759     load_all = 1;
14760
14761   cu->partial_dies
14762     = htab_create_alloc_ex (cu->header.length / 12,
14763                             partial_die_hash,
14764                             partial_die_eq,
14765                             NULL,
14766                             &cu->comp_unit_obstack,
14767                             hashtab_obstack_allocate,
14768                             dummy_obstack_deallocate);
14769
14770   part_die = obstack_alloc (&cu->comp_unit_obstack,
14771                             sizeof (struct partial_die_info));
14772
14773   while (1)
14774     {
14775       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14776
14777       /* A NULL abbrev means the end of a series of children.  */
14778       if (abbrev == NULL)
14779         {
14780           if (--nesting_level == 0)
14781             {
14782               /* PART_DIE was probably the last thing allocated on the
14783                  comp_unit_obstack, so we could call obstack_free
14784                  here.  We don't do that because the waste is small,
14785                  and will be cleaned up when we're done with this
14786                  compilation unit.  This way, we're also more robust
14787                  against other users of the comp_unit_obstack.  */
14788               return first_die;
14789             }
14790           info_ptr += bytes_read;
14791           last_die = parent_die;
14792           parent_die = parent_die->die_parent;
14793           continue;
14794         }
14795
14796       /* Check for template arguments.  We never save these; if
14797          they're seen, we just mark the parent, and go on our way.  */
14798       if (parent_die != NULL
14799           && cu->language == language_cplus
14800           && (abbrev->tag == DW_TAG_template_type_param
14801               || abbrev->tag == DW_TAG_template_value_param))
14802         {
14803           parent_die->has_template_arguments = 1;
14804
14805           if (!load_all)
14806             {
14807               /* We don't need a partial DIE for the template argument.  */
14808               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14809               continue;
14810             }
14811         }
14812
14813       /* We only recurse into c++ subprograms looking for template arguments.
14814          Skip their other children.  */
14815       if (!load_all
14816           && cu->language == language_cplus
14817           && parent_die != NULL
14818           && parent_die->tag == DW_TAG_subprogram)
14819         {
14820           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14821           continue;
14822         }
14823
14824       /* Check whether this DIE is interesting enough to save.  Normally
14825          we would not be interested in members here, but there may be
14826          later variables referencing them via DW_AT_specification (for
14827          static members).  */
14828       if (!load_all
14829           && !is_type_tag_for_partial (abbrev->tag)
14830           && abbrev->tag != DW_TAG_constant
14831           && abbrev->tag != DW_TAG_enumerator
14832           && abbrev->tag != DW_TAG_subprogram
14833           && abbrev->tag != DW_TAG_lexical_block
14834           && abbrev->tag != DW_TAG_variable
14835           && abbrev->tag != DW_TAG_namespace
14836           && abbrev->tag != DW_TAG_module
14837           && abbrev->tag != DW_TAG_member
14838           && abbrev->tag != DW_TAG_imported_unit)
14839         {
14840           /* Otherwise we skip to the next sibling, if any.  */
14841           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14842           continue;
14843         }
14844
14845       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14846                                    info_ptr);
14847
14848       /* This two-pass algorithm for processing partial symbols has a
14849          high cost in cache pressure.  Thus, handle some simple cases
14850          here which cover the majority of C partial symbols.  DIEs
14851          which neither have specification tags in them, nor could have
14852          specification tags elsewhere pointing at them, can simply be
14853          processed and discarded.
14854
14855          This segment is also optional; scan_partial_symbols and
14856          add_partial_symbol will handle these DIEs if we chain
14857          them in normally.  When compilers which do not emit large
14858          quantities of duplicate debug information are more common,
14859          this code can probably be removed.  */
14860
14861       /* Any complete simple types at the top level (pretty much all
14862          of them, for a language without namespaces), can be processed
14863          directly.  */
14864       if (parent_die == NULL
14865           && part_die->has_specification == 0
14866           && part_die->is_declaration == 0
14867           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14868               || part_die->tag == DW_TAG_base_type
14869               || part_die->tag == DW_TAG_subrange_type))
14870         {
14871           if (building_psymtab && part_die->name != NULL)
14872             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14873                                  VAR_DOMAIN, LOC_TYPEDEF,
14874                                  &objfile->static_psymbols,
14875                                  0, (CORE_ADDR) 0, cu->language, objfile);
14876           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14877           continue;
14878         }
14879
14880       /* The exception for DW_TAG_typedef with has_children above is
14881          a workaround of GCC PR debug/47510.  In the case of this complaint
14882          type_name_no_tag_or_error will error on such types later.
14883
14884          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14885          it could not find the child DIEs referenced later, this is checked
14886          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14887
14888       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14889         complaint (&symfile_complaints,
14890                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14891                      "- DIE at 0x%x [in module %s]"),
14892                    part_die->offset.sect_off, objfile_name (objfile));
14893
14894       /* If we're at the second level, and we're an enumerator, and
14895          our parent has no specification (meaning possibly lives in a
14896          namespace elsewhere), then we can add the partial symbol now
14897          instead of queueing it.  */
14898       if (part_die->tag == DW_TAG_enumerator
14899           && parent_die != NULL
14900           && parent_die->die_parent == NULL
14901           && parent_die->tag == DW_TAG_enumeration_type
14902           && parent_die->has_specification == 0)
14903         {
14904           if (part_die->name == NULL)
14905             complaint (&symfile_complaints,
14906                        _("malformed enumerator DIE ignored"));
14907           else if (building_psymtab)
14908             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14909                                  VAR_DOMAIN, LOC_CONST,
14910                                  (cu->language == language_cplus
14911                                   || cu->language == language_java)
14912                                  ? &objfile->global_psymbols
14913                                  : &objfile->static_psymbols,
14914                                  0, (CORE_ADDR) 0, cu->language, objfile);
14915
14916           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14917           continue;
14918         }
14919
14920       /* We'll save this DIE so link it in.  */
14921       part_die->die_parent = parent_die;
14922       part_die->die_sibling = NULL;
14923       part_die->die_child = NULL;
14924
14925       if (last_die && last_die == parent_die)
14926         last_die->die_child = part_die;
14927       else if (last_die)
14928         last_die->die_sibling = part_die;
14929
14930       last_die = part_die;
14931
14932       if (first_die == NULL)
14933         first_die = part_die;
14934
14935       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14936          find interesting need to be in the hash table, because we
14937          also have the parent/sibling/child chains; only those that we
14938          might refer to by offset later during partial symbol reading.
14939
14940          For now this means things that might have be the target of a
14941          DW_AT_specification, DW_AT_abstract_origin, or
14942          DW_AT_extension.  DW_AT_extension will refer only to
14943          namespaces; DW_AT_abstract_origin refers to functions (and
14944          many things under the function DIE, but we do not recurse
14945          into function DIEs during partial symbol reading) and
14946          possibly variables as well; DW_AT_specification refers to
14947          declarations.  Declarations ought to have the DW_AT_declaration
14948          flag.  It happens that GCC forgets to put it in sometimes, but
14949          only for functions, not for types.
14950
14951          Adding more things than necessary to the hash table is harmless
14952          except for the performance cost.  Adding too few will result in
14953          wasted time in find_partial_die, when we reread the compilation
14954          unit with load_all_dies set.  */
14955
14956       if (load_all
14957           || abbrev->tag == DW_TAG_constant
14958           || abbrev->tag == DW_TAG_subprogram
14959           || abbrev->tag == DW_TAG_variable
14960           || abbrev->tag == DW_TAG_namespace
14961           || part_die->is_declaration)
14962         {
14963           void **slot;
14964
14965           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14966                                            part_die->offset.sect_off, INSERT);
14967           *slot = part_die;
14968         }
14969
14970       part_die = obstack_alloc (&cu->comp_unit_obstack,
14971                                 sizeof (struct partial_die_info));
14972
14973       /* For some DIEs we want to follow their children (if any).  For C
14974          we have no reason to follow the children of structures; for other
14975          languages we have to, so that we can get at method physnames
14976          to infer fully qualified class names, for DW_AT_specification,
14977          and for C++ template arguments.  For C++, we also look one level
14978          inside functions to find template arguments (if the name of the
14979          function does not already contain the template arguments).
14980
14981          For Ada, we need to scan the children of subprograms and lexical
14982          blocks as well because Ada allows the definition of nested
14983          entities that could be interesting for the debugger, such as
14984          nested subprograms for instance.  */
14985       if (last_die->has_children
14986           && (load_all
14987               || last_die->tag == DW_TAG_namespace
14988               || last_die->tag == DW_TAG_module
14989               || last_die->tag == DW_TAG_enumeration_type
14990               || (cu->language == language_cplus
14991                   && last_die->tag == DW_TAG_subprogram
14992                   && (last_die->name == NULL
14993                       || strchr (last_die->name, '<') == NULL))
14994               || (cu->language != language_c
14995                   && (last_die->tag == DW_TAG_class_type
14996                       || last_die->tag == DW_TAG_interface_type
14997                       || last_die->tag == DW_TAG_structure_type
14998                       || last_die->tag == DW_TAG_union_type))
14999               || (cu->language == language_ada
15000                   && (last_die->tag == DW_TAG_subprogram
15001                       || last_die->tag == DW_TAG_lexical_block))))
15002         {
15003           nesting_level++;
15004           parent_die = last_die;
15005           continue;
15006         }
15007
15008       /* Otherwise we skip to the next sibling, if any.  */
15009       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
15010
15011       /* Back to the top, do it again.  */
15012     }
15013 }
15014
15015 /* Read a minimal amount of information into the minimal die structure.  */
15016
15017 static const gdb_byte *
15018 read_partial_die (const struct die_reader_specs *reader,
15019                   struct partial_die_info *part_die,
15020                   struct abbrev_info *abbrev, unsigned int abbrev_len,
15021                   const gdb_byte *info_ptr)
15022 {
15023   struct dwarf2_cu *cu = reader->cu;
15024   struct objfile *objfile = cu->objfile;
15025   const gdb_byte *buffer = reader->buffer;
15026   unsigned int i;
15027   struct attribute attr;
15028   int has_low_pc_attr = 0;
15029   int has_high_pc_attr = 0;
15030   int high_pc_relative = 0;
15031
15032   memset (part_die, 0, sizeof (struct partial_die_info));
15033
15034   part_die->offset.sect_off = info_ptr - buffer;
15035
15036   info_ptr += abbrev_len;
15037
15038   if (abbrev == NULL)
15039     return info_ptr;
15040
15041   part_die->tag = abbrev->tag;
15042   part_die->has_children = abbrev->has_children;
15043
15044   for (i = 0; i < abbrev->num_attrs; ++i)
15045     {
15046       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
15047
15048       /* Store the data if it is of an attribute we want to keep in a
15049          partial symbol table.  */
15050       switch (attr.name)
15051         {
15052         case DW_AT_name:
15053           switch (part_die->tag)
15054             {
15055             case DW_TAG_compile_unit:
15056             case DW_TAG_partial_unit:
15057             case DW_TAG_type_unit:
15058               /* Compilation units have a DW_AT_name that is a filename, not
15059                  a source language identifier.  */
15060             case DW_TAG_enumeration_type:
15061             case DW_TAG_enumerator:
15062               /* These tags always have simple identifiers already; no need
15063                  to canonicalize them.  */
15064               part_die->name = DW_STRING (&attr);
15065               break;
15066             default:
15067               part_die->name
15068                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
15069                                             &objfile->objfile_obstack);
15070               break;
15071             }
15072           break;
15073         case DW_AT_linkage_name:
15074         case DW_AT_MIPS_linkage_name:
15075           /* Note that both forms of linkage name might appear.  We
15076              assume they will be the same, and we only store the last
15077              one we see.  */
15078           if (cu->language == language_ada)
15079             part_die->name = DW_STRING (&attr);
15080           part_die->linkage_name = DW_STRING (&attr);
15081           break;
15082         case DW_AT_low_pc:
15083           has_low_pc_attr = 1;
15084           part_die->lowpc = DW_ADDR (&attr);
15085           break;
15086         case DW_AT_high_pc:
15087           has_high_pc_attr = 1;
15088           if (attr.form == DW_FORM_addr
15089               || attr.form == DW_FORM_GNU_addr_index)
15090             part_die->highpc = DW_ADDR (&attr);
15091           else
15092             {
15093               high_pc_relative = 1;
15094               part_die->highpc = DW_UNSND (&attr);
15095             }
15096           break;
15097         case DW_AT_location:
15098           /* Support the .debug_loc offsets.  */
15099           if (attr_form_is_block (&attr))
15100             {
15101                part_die->d.locdesc = DW_BLOCK (&attr);
15102             }
15103           else if (attr_form_is_section_offset (&attr))
15104             {
15105               dwarf2_complex_location_expr_complaint ();
15106             }
15107           else
15108             {
15109               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15110                                                      "partial symbol information");
15111             }
15112           break;
15113         case DW_AT_external:
15114           part_die->is_external = DW_UNSND (&attr);
15115           break;
15116         case DW_AT_declaration:
15117           part_die->is_declaration = DW_UNSND (&attr);
15118           break;
15119         case DW_AT_type:
15120           part_die->has_type = 1;
15121           break;
15122         case DW_AT_abstract_origin:
15123         case DW_AT_specification:
15124         case DW_AT_extension:
15125           part_die->has_specification = 1;
15126           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
15127           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15128                                    || cu->per_cu->is_dwz);
15129           break;
15130         case DW_AT_sibling:
15131           /* Ignore absolute siblings, they might point outside of
15132              the current compile unit.  */
15133           if (attr.form == DW_FORM_ref_addr)
15134             complaint (&symfile_complaints,
15135                        _("ignoring absolute DW_AT_sibling"));
15136           else
15137             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
15138           break;
15139         case DW_AT_byte_size:
15140           part_die->has_byte_size = 1;
15141           break;
15142         case DW_AT_calling_convention:
15143           /* DWARF doesn't provide a way to identify a program's source-level
15144              entry point.  DW_AT_calling_convention attributes are only meant
15145              to describe functions' calling conventions.
15146
15147              However, because it's a necessary piece of information in
15148              Fortran, and because DW_CC_program is the only piece of debugging
15149              information whose definition refers to a 'main program' at all,
15150              several compilers have begun marking Fortran main programs with
15151              DW_CC_program --- even when those functions use the standard
15152              calling conventions.
15153
15154              So until DWARF specifies a way to provide this information and
15155              compilers pick up the new representation, we'll support this
15156              practice.  */
15157           if (DW_UNSND (&attr) == DW_CC_program
15158               && cu->language == language_fortran)
15159             {
15160               set_main_name (part_die->name);
15161
15162               /* As this DIE has a static linkage the name would be difficult
15163                  to look up later.  */
15164               language_of_main = language_fortran;
15165             }
15166           break;
15167         case DW_AT_inline:
15168           if (DW_UNSND (&attr) == DW_INL_inlined
15169               || DW_UNSND (&attr) == DW_INL_declared_inlined)
15170             part_die->may_be_inlined = 1;
15171           break;
15172
15173         case DW_AT_import:
15174           if (part_die->tag == DW_TAG_imported_unit)
15175             {
15176               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
15177               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15178                                   || cu->per_cu->is_dwz);
15179             }
15180           break;
15181
15182         default:
15183           break;
15184         }
15185     }
15186
15187   if (high_pc_relative)
15188     part_die->highpc += part_die->lowpc;
15189
15190   if (has_low_pc_attr && has_high_pc_attr)
15191     {
15192       /* When using the GNU linker, .gnu.linkonce. sections are used to
15193          eliminate duplicate copies of functions and vtables and such.
15194          The linker will arbitrarily choose one and discard the others.
15195          The AT_*_pc values for such functions refer to local labels in
15196          these sections.  If the section from that file was discarded, the
15197          labels are not in the output, so the relocs get a value of 0.
15198          If this is a discarded function, mark the pc bounds as invalid,
15199          so that GDB will ignore it.  */
15200       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
15201         {
15202           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15203
15204           complaint (&symfile_complaints,
15205                      _("DW_AT_low_pc %s is zero "
15206                        "for DIE at 0x%x [in module %s]"),
15207                      paddress (gdbarch, part_die->lowpc),
15208                      part_die->offset.sect_off, objfile_name (objfile));
15209         }
15210       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
15211       else if (part_die->lowpc >= part_die->highpc)
15212         {
15213           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15214
15215           complaint (&symfile_complaints,
15216                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
15217                        "for DIE at 0x%x [in module %s]"),
15218                      paddress (gdbarch, part_die->lowpc),
15219                      paddress (gdbarch, part_die->highpc),
15220                      part_die->offset.sect_off, objfile_name (objfile));
15221         }
15222       else
15223         part_die->has_pc_info = 1;
15224     }
15225
15226   return info_ptr;
15227 }
15228
15229 /* Find a cached partial DIE at OFFSET in CU.  */
15230
15231 static struct partial_die_info *
15232 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
15233 {
15234   struct partial_die_info *lookup_die = NULL;
15235   struct partial_die_info part_die;
15236
15237   part_die.offset = offset;
15238   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
15239                                     offset.sect_off);
15240
15241   return lookup_die;
15242 }
15243
15244 /* Find a partial DIE at OFFSET, which may or may not be in CU,
15245    except in the case of .debug_types DIEs which do not reference
15246    outside their CU (they do however referencing other types via
15247    DW_FORM_ref_sig8).  */
15248
15249 static struct partial_die_info *
15250 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
15251 {
15252   struct objfile *objfile = cu->objfile;
15253   struct dwarf2_per_cu_data *per_cu = NULL;
15254   struct partial_die_info *pd = NULL;
15255
15256   if (offset_in_dwz == cu->per_cu->is_dwz
15257       && offset_in_cu_p (&cu->header, offset))
15258     {
15259       pd = find_partial_die_in_comp_unit (offset, cu);
15260       if (pd != NULL)
15261         return pd;
15262       /* We missed recording what we needed.
15263          Load all dies and try again.  */
15264       per_cu = cu->per_cu;
15265     }
15266   else
15267     {
15268       /* TUs don't reference other CUs/TUs (except via type signatures).  */
15269       if (cu->per_cu->is_debug_types)
15270         {
15271           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
15272                    " external reference to offset 0x%lx [in module %s].\n"),
15273                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
15274                  bfd_get_filename (objfile->obfd));
15275         }
15276       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
15277                                                  objfile);
15278
15279       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
15280         load_partial_comp_unit (per_cu);
15281
15282       per_cu->cu->last_used = 0;
15283       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15284     }
15285
15286   /* If we didn't find it, and not all dies have been loaded,
15287      load them all and try again.  */
15288
15289   if (pd == NULL && per_cu->load_all_dies == 0)
15290     {
15291       per_cu->load_all_dies = 1;
15292
15293       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
15294          THIS_CU->cu may already be in use.  So we can't just free it and
15295          replace its DIEs with the ones we read in.  Instead, we leave those
15296          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
15297          and clobber THIS_CU->cu->partial_dies with the hash table for the new
15298          set.  */
15299       load_partial_comp_unit (per_cu);
15300
15301       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15302     }
15303
15304   if (pd == NULL)
15305     internal_error (__FILE__, __LINE__,
15306                     _("could not find partial DIE 0x%x "
15307                       "in cache [from module %s]\n"),
15308                     offset.sect_off, bfd_get_filename (objfile->obfd));
15309   return pd;
15310 }
15311
15312 /* See if we can figure out if the class lives in a namespace.  We do
15313    this by looking for a member function; its demangled name will
15314    contain namespace info, if there is any.  */
15315
15316 static void
15317 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
15318                                   struct dwarf2_cu *cu)
15319 {
15320   /* NOTE: carlton/2003-10-07: Getting the info this way changes
15321      what template types look like, because the demangler
15322      frequently doesn't give the same name as the debug info.  We
15323      could fix this by only using the demangled name to get the
15324      prefix (but see comment in read_structure_type).  */
15325
15326   struct partial_die_info *real_pdi;
15327   struct partial_die_info *child_pdi;
15328
15329   /* If this DIE (this DIE's specification, if any) has a parent, then
15330      we should not do this.  We'll prepend the parent's fully qualified
15331      name when we create the partial symbol.  */
15332
15333   real_pdi = struct_pdi;
15334   while (real_pdi->has_specification)
15335     real_pdi = find_partial_die (real_pdi->spec_offset,
15336                                  real_pdi->spec_is_dwz, cu);
15337
15338   if (real_pdi->die_parent != NULL)
15339     return;
15340
15341   for (child_pdi = struct_pdi->die_child;
15342        child_pdi != NULL;
15343        child_pdi = child_pdi->die_sibling)
15344     {
15345       if (child_pdi->tag == DW_TAG_subprogram
15346           && child_pdi->linkage_name != NULL)
15347         {
15348           char *actual_class_name
15349             = language_class_name_from_physname (cu->language_defn,
15350                                                  child_pdi->linkage_name);
15351           if (actual_class_name != NULL)
15352             {
15353               struct_pdi->name
15354                 = obstack_copy0 (&cu->objfile->objfile_obstack,
15355                                  actual_class_name,
15356                                  strlen (actual_class_name));
15357               xfree (actual_class_name);
15358             }
15359           break;
15360         }
15361     }
15362 }
15363
15364 /* Adjust PART_DIE before generating a symbol for it.  This function
15365    may set the is_external flag or change the DIE's name.  */
15366
15367 static void
15368 fixup_partial_die (struct partial_die_info *part_die,
15369                    struct dwarf2_cu *cu)
15370 {
15371   /* Once we've fixed up a die, there's no point in doing so again.
15372      This also avoids a memory leak if we were to call
15373      guess_partial_die_structure_name multiple times.  */
15374   if (part_die->fixup_called)
15375     return;
15376
15377   /* If we found a reference attribute and the DIE has no name, try
15378      to find a name in the referred to DIE.  */
15379
15380   if (part_die->name == NULL && part_die->has_specification)
15381     {
15382       struct partial_die_info *spec_die;
15383
15384       spec_die = find_partial_die (part_die->spec_offset,
15385                                    part_die->spec_is_dwz, cu);
15386
15387       fixup_partial_die (spec_die, cu);
15388
15389       if (spec_die->name)
15390         {
15391           part_die->name = spec_die->name;
15392
15393           /* Copy DW_AT_external attribute if it is set.  */
15394           if (spec_die->is_external)
15395             part_die->is_external = spec_die->is_external;
15396         }
15397     }
15398
15399   /* Set default names for some unnamed DIEs.  */
15400
15401   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
15402     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
15403
15404   /* If there is no parent die to provide a namespace, and there are
15405      children, see if we can determine the namespace from their linkage
15406      name.  */
15407   if (cu->language == language_cplus
15408       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15409       && part_die->die_parent == NULL
15410       && part_die->has_children
15411       && (part_die->tag == DW_TAG_class_type
15412           || part_die->tag == DW_TAG_structure_type
15413           || part_die->tag == DW_TAG_union_type))
15414     guess_partial_die_structure_name (part_die, cu);
15415
15416   /* GCC might emit a nameless struct or union that has a linkage
15417      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15418   if (part_die->name == NULL
15419       && (part_die->tag == DW_TAG_class_type
15420           || part_die->tag == DW_TAG_interface_type
15421           || part_die->tag == DW_TAG_structure_type
15422           || part_die->tag == DW_TAG_union_type)
15423       && part_die->linkage_name != NULL)
15424     {
15425       char *demangled;
15426
15427       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
15428       if (demangled)
15429         {
15430           const char *base;
15431
15432           /* Strip any leading namespaces/classes, keep only the base name.
15433              DW_AT_name for named DIEs does not contain the prefixes.  */
15434           base = strrchr (demangled, ':');
15435           if (base && base > demangled && base[-1] == ':')
15436             base++;
15437           else
15438             base = demangled;
15439
15440           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
15441                                           base, strlen (base));
15442           xfree (demangled);
15443         }
15444     }
15445
15446   part_die->fixup_called = 1;
15447 }
15448
15449 /* Read an attribute value described by an attribute form.  */
15450
15451 static const gdb_byte *
15452 read_attribute_value (const struct die_reader_specs *reader,
15453                       struct attribute *attr, unsigned form,
15454                       const gdb_byte *info_ptr)
15455 {
15456   struct dwarf2_cu *cu = reader->cu;
15457   bfd *abfd = reader->abfd;
15458   struct comp_unit_head *cu_header = &cu->header;
15459   unsigned int bytes_read;
15460   struct dwarf_block *blk;
15461
15462   attr->form = form;
15463   switch (form)
15464     {
15465     case DW_FORM_ref_addr:
15466       if (cu->header.version == 2)
15467         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15468       else
15469         DW_UNSND (attr) = read_offset (abfd, info_ptr,
15470                                        &cu->header, &bytes_read);
15471       info_ptr += bytes_read;
15472       break;
15473     case DW_FORM_GNU_ref_alt:
15474       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15475       info_ptr += bytes_read;
15476       break;
15477     case DW_FORM_addr:
15478       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15479       info_ptr += bytes_read;
15480       break;
15481     case DW_FORM_block2:
15482       blk = dwarf_alloc_block (cu);
15483       blk->size = read_2_bytes (abfd, info_ptr);
15484       info_ptr += 2;
15485       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15486       info_ptr += blk->size;
15487       DW_BLOCK (attr) = blk;
15488       break;
15489     case DW_FORM_block4:
15490       blk = dwarf_alloc_block (cu);
15491       blk->size = read_4_bytes (abfd, info_ptr);
15492       info_ptr += 4;
15493       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15494       info_ptr += blk->size;
15495       DW_BLOCK (attr) = blk;
15496       break;
15497     case DW_FORM_data2:
15498       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
15499       info_ptr += 2;
15500       break;
15501     case DW_FORM_data4:
15502       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
15503       info_ptr += 4;
15504       break;
15505     case DW_FORM_data8:
15506       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
15507       info_ptr += 8;
15508       break;
15509     case DW_FORM_sec_offset:
15510       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15511       info_ptr += bytes_read;
15512       break;
15513     case DW_FORM_string:
15514       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
15515       DW_STRING_IS_CANONICAL (attr) = 0;
15516       info_ptr += bytes_read;
15517       break;
15518     case DW_FORM_strp:
15519       if (!cu->per_cu->is_dwz)
15520         {
15521           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
15522                                                    &bytes_read);
15523           DW_STRING_IS_CANONICAL (attr) = 0;
15524           info_ptr += bytes_read;
15525           break;
15526         }
15527       /* FALLTHROUGH */
15528     case DW_FORM_GNU_strp_alt:
15529       {
15530         struct dwz_file *dwz = dwarf2_get_dwz_file ();
15531         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
15532                                           &bytes_read);
15533
15534         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
15535         DW_STRING_IS_CANONICAL (attr) = 0;
15536         info_ptr += bytes_read;
15537       }
15538       break;
15539     case DW_FORM_exprloc:
15540     case DW_FORM_block:
15541       blk = dwarf_alloc_block (cu);
15542       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15543       info_ptr += bytes_read;
15544       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15545       info_ptr += blk->size;
15546       DW_BLOCK (attr) = blk;
15547       break;
15548     case DW_FORM_block1:
15549       blk = dwarf_alloc_block (cu);
15550       blk->size = read_1_byte (abfd, info_ptr);
15551       info_ptr += 1;
15552       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15553       info_ptr += blk->size;
15554       DW_BLOCK (attr) = blk;
15555       break;
15556     case DW_FORM_data1:
15557       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15558       info_ptr += 1;
15559       break;
15560     case DW_FORM_flag:
15561       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15562       info_ptr += 1;
15563       break;
15564     case DW_FORM_flag_present:
15565       DW_UNSND (attr) = 1;
15566       break;
15567     case DW_FORM_sdata:
15568       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
15569       info_ptr += bytes_read;
15570       break;
15571     case DW_FORM_udata:
15572       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15573       info_ptr += bytes_read;
15574       break;
15575     case DW_FORM_ref1:
15576       DW_UNSND (attr) = (cu->header.offset.sect_off
15577                          + read_1_byte (abfd, info_ptr));
15578       info_ptr += 1;
15579       break;
15580     case DW_FORM_ref2:
15581       DW_UNSND (attr) = (cu->header.offset.sect_off
15582                          + read_2_bytes (abfd, info_ptr));
15583       info_ptr += 2;
15584       break;
15585     case DW_FORM_ref4:
15586       DW_UNSND (attr) = (cu->header.offset.sect_off
15587                          + read_4_bytes (abfd, info_ptr));
15588       info_ptr += 4;
15589       break;
15590     case DW_FORM_ref8:
15591       DW_UNSND (attr) = (cu->header.offset.sect_off
15592                          + read_8_bytes (abfd, info_ptr));
15593       info_ptr += 8;
15594       break;
15595     case DW_FORM_ref_sig8:
15596       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
15597       info_ptr += 8;
15598       break;
15599     case DW_FORM_ref_udata:
15600       DW_UNSND (attr) = (cu->header.offset.sect_off
15601                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
15602       info_ptr += bytes_read;
15603       break;
15604     case DW_FORM_indirect:
15605       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15606       info_ptr += bytes_read;
15607       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
15608       break;
15609     case DW_FORM_GNU_addr_index:
15610       if (reader->dwo_file == NULL)
15611         {
15612           /* For now flag a hard error.
15613              Later we can turn this into a complaint.  */
15614           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15615                  dwarf_form_name (form),
15616                  bfd_get_filename (abfd));
15617         }
15618       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
15619       info_ptr += bytes_read;
15620       break;
15621     case DW_FORM_GNU_str_index:
15622       if (reader->dwo_file == NULL)
15623         {
15624           /* For now flag a hard error.
15625              Later we can turn this into a complaint if warranted.  */
15626           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15627                  dwarf_form_name (form),
15628                  bfd_get_filename (abfd));
15629         }
15630       {
15631         ULONGEST str_index =
15632           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15633
15634         DW_STRING (attr) = read_str_index (reader, cu, str_index);
15635         DW_STRING_IS_CANONICAL (attr) = 0;
15636         info_ptr += bytes_read;
15637       }
15638       break;
15639     default:
15640       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
15641              dwarf_form_name (form),
15642              bfd_get_filename (abfd));
15643     }
15644
15645   /* Super hack.  */
15646   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
15647     attr->form = DW_FORM_GNU_ref_alt;
15648
15649   /* We have seen instances where the compiler tried to emit a byte
15650      size attribute of -1 which ended up being encoded as an unsigned
15651      0xffffffff.  Although 0xffffffff is technically a valid size value,
15652      an object of this size seems pretty unlikely so we can relatively
15653      safely treat these cases as if the size attribute was invalid and
15654      treat them as zero by default.  */
15655   if (attr->name == DW_AT_byte_size
15656       && form == DW_FORM_data4
15657       && DW_UNSND (attr) >= 0xffffffff)
15658     {
15659       complaint
15660         (&symfile_complaints,
15661          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
15662          hex_string (DW_UNSND (attr)));
15663       DW_UNSND (attr) = 0;
15664     }
15665
15666   return info_ptr;
15667 }
15668
15669 /* Read an attribute described by an abbreviated attribute.  */
15670
15671 static const gdb_byte *
15672 read_attribute (const struct die_reader_specs *reader,
15673                 struct attribute *attr, struct attr_abbrev *abbrev,
15674                 const gdb_byte *info_ptr)
15675 {
15676   attr->name = abbrev->name;
15677   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
15678 }
15679
15680 /* Read dwarf information from a buffer.  */
15681
15682 static unsigned int
15683 read_1_byte (bfd *abfd, const gdb_byte *buf)
15684 {
15685   return bfd_get_8 (abfd, buf);
15686 }
15687
15688 static int
15689 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
15690 {
15691   return bfd_get_signed_8 (abfd, buf);
15692 }
15693
15694 static unsigned int
15695 read_2_bytes (bfd *abfd, const gdb_byte *buf)
15696 {
15697   return bfd_get_16 (abfd, buf);
15698 }
15699
15700 static int
15701 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
15702 {
15703   return bfd_get_signed_16 (abfd, buf);
15704 }
15705
15706 static unsigned int
15707 read_4_bytes (bfd *abfd, const gdb_byte *buf)
15708 {
15709   return bfd_get_32 (abfd, buf);
15710 }
15711
15712 static int
15713 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
15714 {
15715   return bfd_get_signed_32 (abfd, buf);
15716 }
15717
15718 static ULONGEST
15719 read_8_bytes (bfd *abfd, const gdb_byte *buf)
15720 {
15721   return bfd_get_64 (abfd, buf);
15722 }
15723
15724 static CORE_ADDR
15725 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
15726               unsigned int *bytes_read)
15727 {
15728   struct comp_unit_head *cu_header = &cu->header;
15729   CORE_ADDR retval = 0;
15730
15731   if (cu_header->signed_addr_p)
15732     {
15733       switch (cu_header->addr_size)
15734         {
15735         case 2:
15736           retval = bfd_get_signed_16 (abfd, buf);
15737           break;
15738         case 4:
15739           retval = bfd_get_signed_32 (abfd, buf);
15740           break;
15741         case 8:
15742           retval = bfd_get_signed_64 (abfd, buf);
15743           break;
15744         default:
15745           internal_error (__FILE__, __LINE__,
15746                           _("read_address: bad switch, signed [in module %s]"),
15747                           bfd_get_filename (abfd));
15748         }
15749     }
15750   else
15751     {
15752       switch (cu_header->addr_size)
15753         {
15754         case 2:
15755           retval = bfd_get_16 (abfd, buf);
15756           break;
15757         case 4:
15758           retval = bfd_get_32 (abfd, buf);
15759           break;
15760         case 8:
15761           retval = bfd_get_64 (abfd, buf);
15762           break;
15763         default:
15764           internal_error (__FILE__, __LINE__,
15765                           _("read_address: bad switch, "
15766                             "unsigned [in module %s]"),
15767                           bfd_get_filename (abfd));
15768         }
15769     }
15770
15771   *bytes_read = cu_header->addr_size;
15772   return retval;
15773 }
15774
15775 /* Read the initial length from a section.  The (draft) DWARF 3
15776    specification allows the initial length to take up either 4 bytes
15777    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15778    bytes describe the length and all offsets will be 8 bytes in length
15779    instead of 4.
15780
15781    An older, non-standard 64-bit format is also handled by this
15782    function.  The older format in question stores the initial length
15783    as an 8-byte quantity without an escape value.  Lengths greater
15784    than 2^32 aren't very common which means that the initial 4 bytes
15785    is almost always zero.  Since a length value of zero doesn't make
15786    sense for the 32-bit format, this initial zero can be considered to
15787    be an escape value which indicates the presence of the older 64-bit
15788    format.  As written, the code can't detect (old format) lengths
15789    greater than 4GB.  If it becomes necessary to handle lengths
15790    somewhat larger than 4GB, we could allow other small values (such
15791    as the non-sensical values of 1, 2, and 3) to also be used as
15792    escape values indicating the presence of the old format.
15793
15794    The value returned via bytes_read should be used to increment the
15795    relevant pointer after calling read_initial_length().
15796
15797    [ Note:  read_initial_length() and read_offset() are based on the
15798      document entitled "DWARF Debugging Information Format", revision
15799      3, draft 8, dated November 19, 2001.  This document was obtained
15800      from:
15801
15802         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15803
15804      This document is only a draft and is subject to change.  (So beware.)
15805
15806      Details regarding the older, non-standard 64-bit format were
15807      determined empirically by examining 64-bit ELF files produced by
15808      the SGI toolchain on an IRIX 6.5 machine.
15809
15810      - Kevin, July 16, 2002
15811    ] */
15812
15813 static LONGEST
15814 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15815 {
15816   LONGEST length = bfd_get_32 (abfd, buf);
15817
15818   if (length == 0xffffffff)
15819     {
15820       length = bfd_get_64 (abfd, buf + 4);
15821       *bytes_read = 12;
15822     }
15823   else if (length == 0)
15824     {
15825       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15826       length = bfd_get_64 (abfd, buf);
15827       *bytes_read = 8;
15828     }
15829   else
15830     {
15831       *bytes_read = 4;
15832     }
15833
15834   return length;
15835 }
15836
15837 /* Cover function for read_initial_length.
15838    Returns the length of the object at BUF, and stores the size of the
15839    initial length in *BYTES_READ and stores the size that offsets will be in
15840    *OFFSET_SIZE.
15841    If the initial length size is not equivalent to that specified in
15842    CU_HEADER then issue a complaint.
15843    This is useful when reading non-comp-unit headers.  */
15844
15845 static LONGEST
15846 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15847                                         const struct comp_unit_head *cu_header,
15848                                         unsigned int *bytes_read,
15849                                         unsigned int *offset_size)
15850 {
15851   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15852
15853   gdb_assert (cu_header->initial_length_size == 4
15854               || cu_header->initial_length_size == 8
15855               || cu_header->initial_length_size == 12);
15856
15857   if (cu_header->initial_length_size != *bytes_read)
15858     complaint (&symfile_complaints,
15859                _("intermixed 32-bit and 64-bit DWARF sections"));
15860
15861   *offset_size = (*bytes_read == 4) ? 4 : 8;
15862   return length;
15863 }
15864
15865 /* Read an offset from the data stream.  The size of the offset is
15866    given by cu_header->offset_size.  */
15867
15868 static LONGEST
15869 read_offset (bfd *abfd, const gdb_byte *buf,
15870              const struct comp_unit_head *cu_header,
15871              unsigned int *bytes_read)
15872 {
15873   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15874
15875   *bytes_read = cu_header->offset_size;
15876   return offset;
15877 }
15878
15879 /* Read an offset from the data stream.  */
15880
15881 static LONGEST
15882 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15883 {
15884   LONGEST retval = 0;
15885
15886   switch (offset_size)
15887     {
15888     case 4:
15889       retval = bfd_get_32 (abfd, buf);
15890       break;
15891     case 8:
15892       retval = bfd_get_64 (abfd, buf);
15893       break;
15894     default:
15895       internal_error (__FILE__, __LINE__,
15896                       _("read_offset_1: bad switch [in module %s]"),
15897                       bfd_get_filename (abfd));
15898     }
15899
15900   return retval;
15901 }
15902
15903 static const gdb_byte *
15904 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15905 {
15906   /* If the size of a host char is 8 bits, we can return a pointer
15907      to the buffer, otherwise we have to copy the data to a buffer
15908      allocated on the temporary obstack.  */
15909   gdb_assert (HOST_CHAR_BIT == 8);
15910   return buf;
15911 }
15912
15913 static const char *
15914 read_direct_string (bfd *abfd, const gdb_byte *buf,
15915                     unsigned int *bytes_read_ptr)
15916 {
15917   /* If the size of a host char is 8 bits, we can return a pointer
15918      to the string, otherwise we have to copy the string to a buffer
15919      allocated on the temporary obstack.  */
15920   gdb_assert (HOST_CHAR_BIT == 8);
15921   if (*buf == '\0')
15922     {
15923       *bytes_read_ptr = 1;
15924       return NULL;
15925     }
15926   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15927   return (const char *) buf;
15928 }
15929
15930 static const char *
15931 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15932 {
15933   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15934   if (dwarf2_per_objfile->str.buffer == NULL)
15935     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15936            bfd_get_filename (abfd));
15937   if (str_offset >= dwarf2_per_objfile->str.size)
15938     error (_("DW_FORM_strp pointing outside of "
15939              ".debug_str section [in module %s]"),
15940            bfd_get_filename (abfd));
15941   gdb_assert (HOST_CHAR_BIT == 8);
15942   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15943     return NULL;
15944   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15945 }
15946
15947 /* Read a string at offset STR_OFFSET in the .debug_str section from
15948    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15949    the string consists of a single NUL byte, return NULL; otherwise
15950    return a pointer to the string.  */
15951
15952 static const char *
15953 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15954 {
15955   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15956
15957   if (dwz->str.buffer == NULL)
15958     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15959              "section [in module %s]"),
15960            bfd_get_filename (dwz->dwz_bfd));
15961   if (str_offset >= dwz->str.size)
15962     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15963              ".debug_str section [in module %s]"),
15964            bfd_get_filename (dwz->dwz_bfd));
15965   gdb_assert (HOST_CHAR_BIT == 8);
15966   if (dwz->str.buffer[str_offset] == '\0')
15967     return NULL;
15968   return (const char *) (dwz->str.buffer + str_offset);
15969 }
15970
15971 static const char *
15972 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15973                       const struct comp_unit_head *cu_header,
15974                       unsigned int *bytes_read_ptr)
15975 {
15976   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15977
15978   return read_indirect_string_at_offset (abfd, str_offset);
15979 }
15980
15981 static ULONGEST
15982 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15983                       unsigned int *bytes_read_ptr)
15984 {
15985   ULONGEST result;
15986   unsigned int num_read;
15987   int i, shift;
15988   unsigned char byte;
15989
15990   result = 0;
15991   shift = 0;
15992   num_read = 0;
15993   i = 0;
15994   while (1)
15995     {
15996       byte = bfd_get_8 (abfd, buf);
15997       buf++;
15998       num_read++;
15999       result |= ((ULONGEST) (byte & 127) << shift);
16000       if ((byte & 128) == 0)
16001         {
16002           break;
16003         }
16004       shift += 7;
16005     }
16006   *bytes_read_ptr = num_read;
16007   return result;
16008 }
16009
16010 static LONGEST
16011 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
16012                     unsigned int *bytes_read_ptr)
16013 {
16014   LONGEST result;
16015   int i, shift, num_read;
16016   unsigned char byte;
16017
16018   result = 0;
16019   shift = 0;
16020   num_read = 0;
16021   i = 0;
16022   while (1)
16023     {
16024       byte = bfd_get_8 (abfd, buf);
16025       buf++;
16026       num_read++;
16027       result |= ((LONGEST) (byte & 127) << shift);
16028       shift += 7;
16029       if ((byte & 128) == 0)
16030         {
16031           break;
16032         }
16033     }
16034   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
16035     result |= -(((LONGEST) 1) << shift);
16036   *bytes_read_ptr = num_read;
16037   return result;
16038 }
16039
16040 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
16041    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
16042    ADDR_SIZE is the size of addresses from the CU header.  */
16043
16044 static CORE_ADDR
16045 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
16046 {
16047   struct objfile *objfile = dwarf2_per_objfile->objfile;
16048   bfd *abfd = objfile->obfd;
16049   const gdb_byte *info_ptr;
16050
16051   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
16052   if (dwarf2_per_objfile->addr.buffer == NULL)
16053     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
16054            objfile_name (objfile));
16055   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
16056     error (_("DW_FORM_addr_index pointing outside of "
16057              ".debug_addr section [in module %s]"),
16058            objfile_name (objfile));
16059   info_ptr = (dwarf2_per_objfile->addr.buffer
16060               + addr_base + addr_index * addr_size);
16061   if (addr_size == 4)
16062     return bfd_get_32 (abfd, info_ptr);
16063   else
16064     return bfd_get_64 (abfd, info_ptr);
16065 }
16066
16067 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
16068
16069 static CORE_ADDR
16070 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
16071 {
16072   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
16073 }
16074
16075 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
16076
16077 static CORE_ADDR
16078 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
16079                              unsigned int *bytes_read)
16080 {
16081   bfd *abfd = cu->objfile->obfd;
16082   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
16083
16084   return read_addr_index (cu, addr_index);
16085 }
16086
16087 /* Data structure to pass results from dwarf2_read_addr_index_reader
16088    back to dwarf2_read_addr_index.  */
16089
16090 struct dwarf2_read_addr_index_data
16091 {
16092   ULONGEST addr_base;
16093   int addr_size;
16094 };
16095
16096 /* die_reader_func for dwarf2_read_addr_index.  */
16097
16098 static void
16099 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
16100                                const gdb_byte *info_ptr,
16101                                struct die_info *comp_unit_die,
16102                                int has_children,
16103                                void *data)
16104 {
16105   struct dwarf2_cu *cu = reader->cu;
16106   struct dwarf2_read_addr_index_data *aidata =
16107     (struct dwarf2_read_addr_index_data *) data;
16108
16109   aidata->addr_base = cu->addr_base;
16110   aidata->addr_size = cu->header.addr_size;
16111 }
16112
16113 /* Given an index in .debug_addr, fetch the value.
16114    NOTE: This can be called during dwarf expression evaluation,
16115    long after the debug information has been read, and thus per_cu->cu
16116    may no longer exist.  */
16117
16118 CORE_ADDR
16119 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
16120                         unsigned int addr_index)
16121 {
16122   struct objfile *objfile = per_cu->objfile;
16123   struct dwarf2_cu *cu = per_cu->cu;
16124   ULONGEST addr_base;
16125   int addr_size;
16126
16127   /* This is intended to be called from outside this file.  */
16128   dw2_setup (objfile);
16129
16130   /* We need addr_base and addr_size.
16131      If we don't have PER_CU->cu, we have to get it.
16132      Nasty, but the alternative is storing the needed info in PER_CU,
16133      which at this point doesn't seem justified: it's not clear how frequently
16134      it would get used and it would increase the size of every PER_CU.
16135      Entry points like dwarf2_per_cu_addr_size do a similar thing
16136      so we're not in uncharted territory here.
16137      Alas we need to be a bit more complicated as addr_base is contained
16138      in the DIE.
16139
16140      We don't need to read the entire CU(/TU).
16141      We just need the header and top level die.
16142
16143      IWBN to use the aging mechanism to let us lazily later discard the CU.
16144      For now we skip this optimization.  */
16145
16146   if (cu != NULL)
16147     {
16148       addr_base = cu->addr_base;
16149       addr_size = cu->header.addr_size;
16150     }
16151   else
16152     {
16153       struct dwarf2_read_addr_index_data aidata;
16154
16155       /* Note: We can't use init_cutu_and_read_dies_simple here,
16156          we need addr_base.  */
16157       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
16158                                dwarf2_read_addr_index_reader, &aidata);
16159       addr_base = aidata.addr_base;
16160       addr_size = aidata.addr_size;
16161     }
16162
16163   return read_addr_index_1 (addr_index, addr_base, addr_size);
16164 }
16165
16166 /* Given a DW_FORM_GNU_str_index, fetch the string.
16167    This is only used by the Fission support.  */
16168
16169 static const char *
16170 read_str_index (const struct die_reader_specs *reader,
16171                 struct dwarf2_cu *cu, ULONGEST str_index)
16172 {
16173   struct objfile *objfile = dwarf2_per_objfile->objfile;
16174   const char *dwo_name = objfile_name (objfile);
16175   bfd *abfd = objfile->obfd;
16176   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
16177   struct dwarf2_section_info *str_offsets_section =
16178     &reader->dwo_file->sections.str_offsets;
16179   const gdb_byte *info_ptr;
16180   ULONGEST str_offset;
16181   static const char form_name[] = "DW_FORM_GNU_str_index";
16182
16183   dwarf2_read_section (objfile, str_section);
16184   dwarf2_read_section (objfile, str_offsets_section);
16185   if (str_section->buffer == NULL)
16186     error (_("%s used without .debug_str.dwo section"
16187              " in CU at offset 0x%lx [in module %s]"),
16188            form_name, (long) cu->header.offset.sect_off, dwo_name);
16189   if (str_offsets_section->buffer == NULL)
16190     error (_("%s used without .debug_str_offsets.dwo section"
16191              " in CU at offset 0x%lx [in module %s]"),
16192            form_name, (long) cu->header.offset.sect_off, dwo_name);
16193   if (str_index * cu->header.offset_size >= str_offsets_section->size)
16194     error (_("%s pointing outside of .debug_str_offsets.dwo"
16195              " section in CU at offset 0x%lx [in module %s]"),
16196            form_name, (long) cu->header.offset.sect_off, dwo_name);
16197   info_ptr = (str_offsets_section->buffer
16198               + str_index * cu->header.offset_size);
16199   if (cu->header.offset_size == 4)
16200     str_offset = bfd_get_32 (abfd, info_ptr);
16201   else
16202     str_offset = bfd_get_64 (abfd, info_ptr);
16203   if (str_offset >= str_section->size)
16204     error (_("Offset from %s pointing outside of"
16205              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
16206            form_name, (long) cu->header.offset.sect_off, dwo_name);
16207   return (const char *) (str_section->buffer + str_offset);
16208 }
16209
16210 /* Return the length of an LEB128 number in BUF.  */
16211
16212 static int
16213 leb128_size (const gdb_byte *buf)
16214 {
16215   const gdb_byte *begin = buf;
16216   gdb_byte byte;
16217
16218   while (1)
16219     {
16220       byte = *buf++;
16221       if ((byte & 128) == 0)
16222         return buf - begin;
16223     }
16224 }
16225
16226 static void
16227 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
16228 {
16229   switch (lang)
16230     {
16231     case DW_LANG_C89:
16232     case DW_LANG_C99:
16233     case DW_LANG_C:
16234     case DW_LANG_UPC:
16235       cu->language = language_c;
16236       break;
16237     case DW_LANG_C_plus_plus:
16238       cu->language = language_cplus;
16239       break;
16240     case DW_LANG_D:
16241       cu->language = language_d;
16242       break;
16243     case DW_LANG_Fortran77:
16244     case DW_LANG_Fortran90:
16245     case DW_LANG_Fortran95:
16246       cu->language = language_fortran;
16247       break;
16248     case DW_LANG_Go:
16249       cu->language = language_go;
16250       break;
16251     case DW_LANG_Mips_Assembler:
16252       cu->language = language_asm;
16253       break;
16254     case DW_LANG_Java:
16255       cu->language = language_java;
16256       break;
16257     case DW_LANG_Ada83:
16258     case DW_LANG_Ada95:
16259       cu->language = language_ada;
16260       break;
16261     case DW_LANG_Modula2:
16262       cu->language = language_m2;
16263       break;
16264     case DW_LANG_Pascal83:
16265       cu->language = language_pascal;
16266       break;
16267     case DW_LANG_ObjC:
16268       cu->language = language_objc;
16269       break;
16270     case DW_LANG_Cobol74:
16271     case DW_LANG_Cobol85:
16272     default:
16273       cu->language = language_minimal;
16274       break;
16275     }
16276   cu->language_defn = language_def (cu->language);
16277 }
16278
16279 /* Return the named attribute or NULL if not there.  */
16280
16281 static struct attribute *
16282 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
16283 {
16284   for (;;)
16285     {
16286       unsigned int i;
16287       struct attribute *spec = NULL;
16288
16289       for (i = 0; i < die->num_attrs; ++i)
16290         {
16291           if (die->attrs[i].name == name)
16292             return &die->attrs[i];
16293           if (die->attrs[i].name == DW_AT_specification
16294               || die->attrs[i].name == DW_AT_abstract_origin)
16295             spec = &die->attrs[i];
16296         }
16297
16298       if (!spec)
16299         break;
16300
16301       die = follow_die_ref (die, spec, &cu);
16302     }
16303
16304   return NULL;
16305 }
16306
16307 /* Return the named attribute or NULL if not there,
16308    but do not follow DW_AT_specification, etc.
16309    This is for use in contexts where we're reading .debug_types dies.
16310    Following DW_AT_specification, DW_AT_abstract_origin will take us
16311    back up the chain, and we want to go down.  */
16312
16313 static struct attribute *
16314 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
16315 {
16316   unsigned int i;
16317
16318   for (i = 0; i < die->num_attrs; ++i)
16319     if (die->attrs[i].name == name)
16320       return &die->attrs[i];
16321
16322   return NULL;
16323 }
16324
16325 /* Return non-zero iff the attribute NAME is defined for the given DIE,
16326    and holds a non-zero value.  This function should only be used for
16327    DW_FORM_flag or DW_FORM_flag_present attributes.  */
16328
16329 static int
16330 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
16331 {
16332   struct attribute *attr = dwarf2_attr (die, name, cu);
16333
16334   return (attr && DW_UNSND (attr));
16335 }
16336
16337 static int
16338 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
16339 {
16340   /* A DIE is a declaration if it has a DW_AT_declaration attribute
16341      which value is non-zero.  However, we have to be careful with
16342      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
16343      (via dwarf2_flag_true_p) follows this attribute.  So we may
16344      end up accidently finding a declaration attribute that belongs
16345      to a different DIE referenced by the specification attribute,
16346      even though the given DIE does not have a declaration attribute.  */
16347   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
16348           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
16349 }
16350
16351 /* Return the die giving the specification for DIE, if there is
16352    one.  *SPEC_CU is the CU containing DIE on input, and the CU
16353    containing the return value on output.  If there is no
16354    specification, but there is an abstract origin, that is
16355    returned.  */
16356
16357 static struct die_info *
16358 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
16359 {
16360   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
16361                                              *spec_cu);
16362
16363   if (spec_attr == NULL)
16364     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
16365
16366   if (spec_attr == NULL)
16367     return NULL;
16368   else
16369     return follow_die_ref (die, spec_attr, spec_cu);
16370 }
16371
16372 /* Free the line_header structure *LH, and any arrays and strings it
16373    refers to.
16374    NOTE: This is also used as a "cleanup" function.  */
16375
16376 static void
16377 free_line_header (struct line_header *lh)
16378 {
16379   if (lh->standard_opcode_lengths)
16380     xfree (lh->standard_opcode_lengths);
16381
16382   /* Remember that all the lh->file_names[i].name pointers are
16383      pointers into debug_line_buffer, and don't need to be freed.  */
16384   if (lh->file_names)
16385     xfree (lh->file_names);
16386
16387   /* Similarly for the include directory names.  */
16388   if (lh->include_dirs)
16389     xfree (lh->include_dirs);
16390
16391   xfree (lh);
16392 }
16393
16394 /* Add an entry to LH's include directory table.  */
16395
16396 static void
16397 add_include_dir (struct line_header *lh, const char *include_dir)
16398 {
16399   /* Grow the array if necessary.  */
16400   if (lh->include_dirs_size == 0)
16401     {
16402       lh->include_dirs_size = 1; /* for testing */
16403       lh->include_dirs = xmalloc (lh->include_dirs_size
16404                                   * sizeof (*lh->include_dirs));
16405     }
16406   else if (lh->num_include_dirs >= lh->include_dirs_size)
16407     {
16408       lh->include_dirs_size *= 2;
16409       lh->include_dirs = xrealloc (lh->include_dirs,
16410                                    (lh->include_dirs_size
16411                                     * sizeof (*lh->include_dirs)));
16412     }
16413
16414   lh->include_dirs[lh->num_include_dirs++] = include_dir;
16415 }
16416
16417 /* Add an entry to LH's file name table.  */
16418
16419 static void
16420 add_file_name (struct line_header *lh,
16421                const char *name,
16422                unsigned int dir_index,
16423                unsigned int mod_time,
16424                unsigned int length)
16425 {
16426   struct file_entry *fe;
16427
16428   /* Grow the array if necessary.  */
16429   if (lh->file_names_size == 0)
16430     {
16431       lh->file_names_size = 1; /* for testing */
16432       lh->file_names = xmalloc (lh->file_names_size
16433                                 * sizeof (*lh->file_names));
16434     }
16435   else if (lh->num_file_names >= lh->file_names_size)
16436     {
16437       lh->file_names_size *= 2;
16438       lh->file_names = xrealloc (lh->file_names,
16439                                  (lh->file_names_size
16440                                   * sizeof (*lh->file_names)));
16441     }
16442
16443   fe = &lh->file_names[lh->num_file_names++];
16444   fe->name = name;
16445   fe->dir_index = dir_index;
16446   fe->mod_time = mod_time;
16447   fe->length = length;
16448   fe->included_p = 0;
16449   fe->symtab = NULL;
16450 }
16451
16452 /* A convenience function to find the proper .debug_line section for a
16453    CU.  */
16454
16455 static struct dwarf2_section_info *
16456 get_debug_line_section (struct dwarf2_cu *cu)
16457 {
16458   struct dwarf2_section_info *section;
16459
16460   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
16461      DWO file.  */
16462   if (cu->dwo_unit && cu->per_cu->is_debug_types)
16463     section = &cu->dwo_unit->dwo_file->sections.line;
16464   else if (cu->per_cu->is_dwz)
16465     {
16466       struct dwz_file *dwz = dwarf2_get_dwz_file ();
16467
16468       section = &dwz->line;
16469     }
16470   else
16471     section = &dwarf2_per_objfile->line;
16472
16473   return section;
16474 }
16475
16476 /* Read the statement program header starting at OFFSET in
16477    .debug_line, or .debug_line.dwo.  Return a pointer
16478    to a struct line_header, allocated using xmalloc.
16479
16480    NOTE: the strings in the include directory and file name tables of
16481    the returned object point into the dwarf line section buffer,
16482    and must not be freed.  */
16483
16484 static struct line_header *
16485 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
16486 {
16487   struct cleanup *back_to;
16488   struct line_header *lh;
16489   const gdb_byte *line_ptr;
16490   unsigned int bytes_read, offset_size;
16491   int i;
16492   const char *cur_dir, *cur_file;
16493   struct dwarf2_section_info *section;
16494   bfd *abfd;
16495
16496   section = get_debug_line_section (cu);
16497   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16498   if (section->buffer == NULL)
16499     {
16500       if (cu->dwo_unit && cu->per_cu->is_debug_types)
16501         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
16502       else
16503         complaint (&symfile_complaints, _("missing .debug_line section"));
16504       return 0;
16505     }
16506
16507   /* We can't do this until we know the section is non-empty.
16508      Only then do we know we have such a section.  */
16509   abfd = get_section_bfd_owner (section);
16510
16511   /* Make sure that at least there's room for the total_length field.
16512      That could be 12 bytes long, but we're just going to fudge that.  */
16513   if (offset + 4 >= section->size)
16514     {
16515       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16516       return 0;
16517     }
16518
16519   lh = xmalloc (sizeof (*lh));
16520   memset (lh, 0, sizeof (*lh));
16521   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
16522                           (void *) lh);
16523
16524   line_ptr = section->buffer + offset;
16525
16526   /* Read in the header.  */
16527   lh->total_length =
16528     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
16529                                             &bytes_read, &offset_size);
16530   line_ptr += bytes_read;
16531   if (line_ptr + lh->total_length > (section->buffer + section->size))
16532     {
16533       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16534       do_cleanups (back_to);
16535       return 0;
16536     }
16537   lh->statement_program_end = line_ptr + lh->total_length;
16538   lh->version = read_2_bytes (abfd, line_ptr);
16539   line_ptr += 2;
16540   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
16541   line_ptr += offset_size;
16542   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
16543   line_ptr += 1;
16544   if (lh->version >= 4)
16545     {
16546       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
16547       line_ptr += 1;
16548     }
16549   else
16550     lh->maximum_ops_per_instruction = 1;
16551
16552   if (lh->maximum_ops_per_instruction == 0)
16553     {
16554       lh->maximum_ops_per_instruction = 1;
16555       complaint (&symfile_complaints,
16556                  _("invalid maximum_ops_per_instruction "
16557                    "in `.debug_line' section"));
16558     }
16559
16560   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
16561   line_ptr += 1;
16562   lh->line_base = read_1_signed_byte (abfd, line_ptr);
16563   line_ptr += 1;
16564   lh->line_range = read_1_byte (abfd, line_ptr);
16565   line_ptr += 1;
16566   lh->opcode_base = read_1_byte (abfd, line_ptr);
16567   line_ptr += 1;
16568   lh->standard_opcode_lengths
16569     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
16570
16571   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
16572   for (i = 1; i < lh->opcode_base; ++i)
16573     {
16574       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
16575       line_ptr += 1;
16576     }
16577
16578   /* Read directory table.  */
16579   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16580     {
16581       line_ptr += bytes_read;
16582       add_include_dir (lh, cur_dir);
16583     }
16584   line_ptr += bytes_read;
16585
16586   /* Read file name table.  */
16587   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16588     {
16589       unsigned int dir_index, mod_time, length;
16590
16591       line_ptr += bytes_read;
16592       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16593       line_ptr += bytes_read;
16594       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16595       line_ptr += bytes_read;
16596       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16597       line_ptr += bytes_read;
16598
16599       add_file_name (lh, cur_file, dir_index, mod_time, length);
16600     }
16601   line_ptr += bytes_read;
16602   lh->statement_program_start = line_ptr;
16603
16604   if (line_ptr > (section->buffer + section->size))
16605     complaint (&symfile_complaints,
16606                _("line number info header doesn't "
16607                  "fit in `.debug_line' section"));
16608
16609   discard_cleanups (back_to);
16610   return lh;
16611 }
16612
16613 /* Subroutine of dwarf_decode_lines to simplify it.
16614    Return the file name of the psymtab for included file FILE_INDEX
16615    in line header LH of PST.
16616    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16617    If space for the result is malloc'd, it will be freed by a cleanup.
16618    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
16619
16620    The function creates dangling cleanup registration.  */
16621
16622 static const char *
16623 psymtab_include_file_name (const struct line_header *lh, int file_index,
16624                            const struct partial_symtab *pst,
16625                            const char *comp_dir)
16626 {
16627   const struct file_entry fe = lh->file_names [file_index];
16628   const char *include_name = fe.name;
16629   const char *include_name_to_compare = include_name;
16630   const char *dir_name = NULL;
16631   const char *pst_filename;
16632   char *copied_name = NULL;
16633   int file_is_pst;
16634
16635   if (fe.dir_index)
16636     dir_name = lh->include_dirs[fe.dir_index - 1];
16637
16638   if (!IS_ABSOLUTE_PATH (include_name)
16639       && (dir_name != NULL || comp_dir != NULL))
16640     {
16641       /* Avoid creating a duplicate psymtab for PST.
16642          We do this by comparing INCLUDE_NAME and PST_FILENAME.
16643          Before we do the comparison, however, we need to account
16644          for DIR_NAME and COMP_DIR.
16645          First prepend dir_name (if non-NULL).  If we still don't
16646          have an absolute path prepend comp_dir (if non-NULL).
16647          However, the directory we record in the include-file's
16648          psymtab does not contain COMP_DIR (to match the
16649          corresponding symtab(s)).
16650
16651          Example:
16652
16653          bash$ cd /tmp
16654          bash$ gcc -g ./hello.c
16655          include_name = "hello.c"
16656          dir_name = "."
16657          DW_AT_comp_dir = comp_dir = "/tmp"
16658          DW_AT_name = "./hello.c"  */
16659
16660       if (dir_name != NULL)
16661         {
16662           char *tem = concat (dir_name, SLASH_STRING,
16663                               include_name, (char *)NULL);
16664
16665           make_cleanup (xfree, tem);
16666           include_name = tem;
16667           include_name_to_compare = include_name;
16668         }
16669       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
16670         {
16671           char *tem = concat (comp_dir, SLASH_STRING,
16672                               include_name, (char *)NULL);
16673
16674           make_cleanup (xfree, tem);
16675           include_name_to_compare = tem;
16676         }
16677     }
16678
16679   pst_filename = pst->filename;
16680   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
16681     {
16682       copied_name = concat (pst->dirname, SLASH_STRING,
16683                             pst_filename, (char *)NULL);
16684       pst_filename = copied_name;
16685     }
16686
16687   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
16688
16689   if (copied_name != NULL)
16690     xfree (copied_name);
16691
16692   if (file_is_pst)
16693     return NULL;
16694   return include_name;
16695 }
16696
16697 /* Ignore this record_line request.  */
16698
16699 static void
16700 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
16701 {
16702   return;
16703 }
16704
16705 /* Subroutine of dwarf_decode_lines to simplify it.
16706    Process the line number information in LH.  */
16707
16708 static void
16709 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
16710                       struct dwarf2_cu *cu, struct partial_symtab *pst)
16711 {
16712   const gdb_byte *line_ptr, *extended_end;
16713   const gdb_byte *line_end;
16714   unsigned int bytes_read, extended_len;
16715   unsigned char op_code, extended_op, adj_opcode;
16716   CORE_ADDR baseaddr;
16717   struct objfile *objfile = cu->objfile;
16718   bfd *abfd = objfile->obfd;
16719   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16720   const int decode_for_pst_p = (pst != NULL);
16721   struct subfile *last_subfile = NULL;
16722   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
16723     = record_line;
16724
16725   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16726
16727   line_ptr = lh->statement_program_start;
16728   line_end = lh->statement_program_end;
16729
16730   /* Read the statement sequences until there's nothing left.  */
16731   while (line_ptr < line_end)
16732     {
16733       /* state machine registers  */
16734       CORE_ADDR address = 0;
16735       unsigned int file = 1;
16736       unsigned int line = 1;
16737       unsigned int column = 0;
16738       int is_stmt = lh->default_is_stmt;
16739       int basic_block = 0;
16740       int end_sequence = 0;
16741       CORE_ADDR addr;
16742       unsigned char op_index = 0;
16743
16744       if (!decode_for_pst_p && lh->num_file_names >= file)
16745         {
16746           /* Start a subfile for the current file of the state machine.  */
16747           /* lh->include_dirs and lh->file_names are 0-based, but the
16748              directory and file name numbers in the statement program
16749              are 1-based.  */
16750           struct file_entry *fe = &lh->file_names[file - 1];
16751           const char *dir = NULL;
16752
16753           if (fe->dir_index)
16754             dir = lh->include_dirs[fe->dir_index - 1];
16755
16756           dwarf2_start_subfile (fe->name, dir, comp_dir);
16757         }
16758
16759       /* Decode the table.  */
16760       while (!end_sequence)
16761         {
16762           op_code = read_1_byte (abfd, line_ptr);
16763           line_ptr += 1;
16764           if (line_ptr > line_end)
16765             {
16766               dwarf2_debug_line_missing_end_sequence_complaint ();
16767               break;
16768             }
16769
16770           if (op_code >= lh->opcode_base)
16771             {
16772               /* Special operand.  */
16773               adj_opcode = op_code - lh->opcode_base;
16774               address += (((op_index + (adj_opcode / lh->line_range))
16775                            / lh->maximum_ops_per_instruction)
16776                           * lh->minimum_instruction_length);
16777               op_index = ((op_index + (adj_opcode / lh->line_range))
16778                           % lh->maximum_ops_per_instruction);
16779               line += lh->line_base + (adj_opcode % lh->line_range);
16780               if (lh->num_file_names < file || file == 0)
16781                 dwarf2_debug_line_missing_file_complaint ();
16782               /* For now we ignore lines not starting on an
16783                  instruction boundary.  */
16784               else if (op_index == 0)
16785                 {
16786                   lh->file_names[file - 1].included_p = 1;
16787                   if (!decode_for_pst_p && is_stmt)
16788                     {
16789                       if (last_subfile != current_subfile)
16790                         {
16791                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16792                           if (last_subfile)
16793                             (*p_record_line) (last_subfile, 0, addr);
16794                           last_subfile = current_subfile;
16795                         }
16796                       /* Append row to matrix using current values.  */
16797                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16798                       (*p_record_line) (current_subfile, line, addr);
16799                     }
16800                 }
16801               basic_block = 0;
16802             }
16803           else switch (op_code)
16804             {
16805             case DW_LNS_extended_op:
16806               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16807                                                    &bytes_read);
16808               line_ptr += bytes_read;
16809               extended_end = line_ptr + extended_len;
16810               extended_op = read_1_byte (abfd, line_ptr);
16811               line_ptr += 1;
16812               switch (extended_op)
16813                 {
16814                 case DW_LNE_end_sequence:
16815                   p_record_line = record_line;
16816                   end_sequence = 1;
16817                   break;
16818                 case DW_LNE_set_address:
16819                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16820
16821                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16822                     {
16823                       /* This line table is for a function which has been
16824                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16825
16826                       long line_offset
16827                         = line_ptr - get_debug_line_section (cu)->buffer;
16828
16829                       complaint (&symfile_complaints,
16830                                  _(".debug_line address at offset 0x%lx is 0 "
16831                                    "[in module %s]"),
16832                                  line_offset, objfile_name (objfile));
16833                       p_record_line = noop_record_line;
16834                     }
16835
16836                   op_index = 0;
16837                   line_ptr += bytes_read;
16838                   address += baseaddr;
16839                   break;
16840                 case DW_LNE_define_file:
16841                   {
16842                     const char *cur_file;
16843                     unsigned int dir_index, mod_time, length;
16844
16845                     cur_file = read_direct_string (abfd, line_ptr,
16846                                                    &bytes_read);
16847                     line_ptr += bytes_read;
16848                     dir_index =
16849                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16850                     line_ptr += bytes_read;
16851                     mod_time =
16852                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16853                     line_ptr += bytes_read;
16854                     length =
16855                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16856                     line_ptr += bytes_read;
16857                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16858                   }
16859                   break;
16860                 case DW_LNE_set_discriminator:
16861                   /* The discriminator is not interesting to the debugger;
16862                      just ignore it.  */
16863                   line_ptr = extended_end;
16864                   break;
16865                 default:
16866                   complaint (&symfile_complaints,
16867                              _("mangled .debug_line section"));
16868                   return;
16869                 }
16870               /* Make sure that we parsed the extended op correctly.  If e.g.
16871                  we expected a different address size than the producer used,
16872                  we may have read the wrong number of bytes.  */
16873               if (line_ptr != extended_end)
16874                 {
16875                   complaint (&symfile_complaints,
16876                              _("mangled .debug_line section"));
16877                   return;
16878                 }
16879               break;
16880             case DW_LNS_copy:
16881               if (lh->num_file_names < file || file == 0)
16882                 dwarf2_debug_line_missing_file_complaint ();
16883               else
16884                 {
16885                   lh->file_names[file - 1].included_p = 1;
16886                   if (!decode_for_pst_p && is_stmt)
16887                     {
16888                       if (last_subfile != current_subfile)
16889                         {
16890                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16891                           if (last_subfile)
16892                             (*p_record_line) (last_subfile, 0, addr);
16893                           last_subfile = current_subfile;
16894                         }
16895                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16896                       (*p_record_line) (current_subfile, line, addr);
16897                     }
16898                 }
16899               basic_block = 0;
16900               break;
16901             case DW_LNS_advance_pc:
16902               {
16903                 CORE_ADDR adjust
16904                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16905
16906                 address += (((op_index + adjust)
16907                              / lh->maximum_ops_per_instruction)
16908                             * lh->minimum_instruction_length);
16909                 op_index = ((op_index + adjust)
16910                             % lh->maximum_ops_per_instruction);
16911                 line_ptr += bytes_read;
16912               }
16913               break;
16914             case DW_LNS_advance_line:
16915               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16916               line_ptr += bytes_read;
16917               break;
16918             case DW_LNS_set_file:
16919               {
16920                 /* The arrays lh->include_dirs and lh->file_names are
16921                    0-based, but the directory and file name numbers in
16922                    the statement program are 1-based.  */
16923                 struct file_entry *fe;
16924                 const char *dir = NULL;
16925
16926                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16927                 line_ptr += bytes_read;
16928                 if (lh->num_file_names < file || file == 0)
16929                   dwarf2_debug_line_missing_file_complaint ();
16930                 else
16931                   {
16932                     fe = &lh->file_names[file - 1];
16933                     if (fe->dir_index)
16934                       dir = lh->include_dirs[fe->dir_index - 1];
16935                     if (!decode_for_pst_p)
16936                       {
16937                         last_subfile = current_subfile;
16938                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16939                       }
16940                   }
16941               }
16942               break;
16943             case DW_LNS_set_column:
16944               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16945               line_ptr += bytes_read;
16946               break;
16947             case DW_LNS_negate_stmt:
16948               is_stmt = (!is_stmt);
16949               break;
16950             case DW_LNS_set_basic_block:
16951               basic_block = 1;
16952               break;
16953             /* Add to the address register of the state machine the
16954                address increment value corresponding to special opcode
16955                255.  I.e., this value is scaled by the minimum
16956                instruction length since special opcode 255 would have
16957                scaled the increment.  */
16958             case DW_LNS_const_add_pc:
16959               {
16960                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16961
16962                 address += (((op_index + adjust)
16963                              / lh->maximum_ops_per_instruction)
16964                             * lh->minimum_instruction_length);
16965                 op_index = ((op_index + adjust)
16966                             % lh->maximum_ops_per_instruction);
16967               }
16968               break;
16969             case DW_LNS_fixed_advance_pc:
16970               address += read_2_bytes (abfd, line_ptr);
16971               op_index = 0;
16972               line_ptr += 2;
16973               break;
16974             default:
16975               {
16976                 /* Unknown standard opcode, ignore it.  */
16977                 int i;
16978
16979                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16980                   {
16981                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16982                     line_ptr += bytes_read;
16983                   }
16984               }
16985             }
16986         }
16987       if (lh->num_file_names < file || file == 0)
16988         dwarf2_debug_line_missing_file_complaint ();
16989       else
16990         {
16991           lh->file_names[file - 1].included_p = 1;
16992           if (!decode_for_pst_p)
16993             {
16994               addr = gdbarch_addr_bits_remove (gdbarch, address);
16995               (*p_record_line) (current_subfile, 0, addr);
16996             }
16997         }
16998     }
16999 }
17000
17001 /* Decode the Line Number Program (LNP) for the given line_header
17002    structure and CU.  The actual information extracted and the type
17003    of structures created from the LNP depends on the value of PST.
17004
17005    1. If PST is NULL, then this procedure uses the data from the program
17006       to create all necessary symbol tables, and their linetables.
17007
17008    2. If PST is not NULL, this procedure reads the program to determine
17009       the list of files included by the unit represented by PST, and
17010       builds all the associated partial symbol tables.
17011
17012    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17013    It is used for relative paths in the line table.
17014    NOTE: When processing partial symtabs (pst != NULL),
17015    comp_dir == pst->dirname.
17016
17017    NOTE: It is important that psymtabs have the same file name (via strcmp)
17018    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
17019    symtab we don't use it in the name of the psymtabs we create.
17020    E.g. expand_line_sal requires this when finding psymtabs to expand.
17021    A good testcase for this is mb-inline.exp.  */
17022
17023 static void
17024 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
17025                     struct dwarf2_cu *cu, struct partial_symtab *pst,
17026                     int want_line_info)
17027 {
17028   struct objfile *objfile = cu->objfile;
17029   const int decode_for_pst_p = (pst != NULL);
17030   struct subfile *first_subfile = current_subfile;
17031
17032   if (want_line_info)
17033     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
17034
17035   if (decode_for_pst_p)
17036     {
17037       int file_index;
17038
17039       /* Now that we're done scanning the Line Header Program, we can
17040          create the psymtab of each included file.  */
17041       for (file_index = 0; file_index < lh->num_file_names; file_index++)
17042         if (lh->file_names[file_index].included_p == 1)
17043           {
17044             const char *include_name =
17045               psymtab_include_file_name (lh, file_index, pst, comp_dir);
17046             if (include_name != NULL)
17047               dwarf2_create_include_psymtab (include_name, pst, objfile);
17048           }
17049     }
17050   else
17051     {
17052       /* Make sure a symtab is created for every file, even files
17053          which contain only variables (i.e. no code with associated
17054          line numbers).  */
17055       int i;
17056
17057       for (i = 0; i < lh->num_file_names; i++)
17058         {
17059           const char *dir = NULL;
17060           struct file_entry *fe;
17061
17062           fe = &lh->file_names[i];
17063           if (fe->dir_index)
17064             dir = lh->include_dirs[fe->dir_index - 1];
17065           dwarf2_start_subfile (fe->name, dir, comp_dir);
17066
17067           /* Skip the main file; we don't need it, and it must be
17068              allocated last, so that it will show up before the
17069              non-primary symtabs in the objfile's symtab list.  */
17070           if (current_subfile == first_subfile)
17071             continue;
17072
17073           if (current_subfile->symtab == NULL)
17074             current_subfile->symtab = allocate_symtab (current_subfile->name,
17075                                                        objfile);
17076           fe->symtab = current_subfile->symtab;
17077         }
17078     }
17079 }
17080
17081 /* Start a subfile for DWARF.  FILENAME is the name of the file and
17082    DIRNAME the name of the source directory which contains FILENAME
17083    or NULL if not known.  COMP_DIR is the compilation directory for the
17084    linetable's compilation unit or NULL if not known.
17085    This routine tries to keep line numbers from identical absolute and
17086    relative file names in a common subfile.
17087
17088    Using the `list' example from the GDB testsuite, which resides in
17089    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
17090    of /srcdir/list0.c yields the following debugging information for list0.c:
17091
17092    DW_AT_name:          /srcdir/list0.c
17093    DW_AT_comp_dir:              /compdir
17094    files.files[0].name: list0.h
17095    files.files[0].dir:  /srcdir
17096    files.files[1].name: list0.c
17097    files.files[1].dir:  /srcdir
17098
17099    The line number information for list0.c has to end up in a single
17100    subfile, so that `break /srcdir/list0.c:1' works as expected.
17101    start_subfile will ensure that this happens provided that we pass the
17102    concatenation of files.files[1].dir and files.files[1].name as the
17103    subfile's name.  */
17104
17105 static void
17106 dwarf2_start_subfile (const char *filename, const char *dirname,
17107                       const char *comp_dir)
17108 {
17109   char *copy = NULL;
17110
17111   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
17112      `start_symtab' will always pass the contents of DW_AT_comp_dir as
17113      second argument to start_subfile.  To be consistent, we do the
17114      same here.  In order not to lose the line information directory,
17115      we concatenate it to the filename when it makes sense.
17116      Note that the Dwarf3 standard says (speaking of filenames in line
17117      information): ``The directory index is ignored for file names
17118      that represent full path names''.  Thus ignoring dirname in the
17119      `else' branch below isn't an issue.  */
17120
17121   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
17122     {
17123       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
17124       filename = copy;
17125     }
17126
17127   start_subfile (filename, comp_dir);
17128
17129   if (copy != NULL)
17130     xfree (copy);
17131 }
17132
17133 /* Start a symtab for DWARF.
17134    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
17135
17136 static void
17137 dwarf2_start_symtab (struct dwarf2_cu *cu,
17138                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
17139 {
17140   start_symtab (name, comp_dir, low_pc);
17141   record_debugformat ("DWARF 2");
17142   record_producer (cu->producer);
17143
17144   /* We assume that we're processing GCC output.  */
17145   processing_gcc_compilation = 2;
17146
17147   cu->processing_has_namespace_info = 0;
17148 }
17149
17150 static void
17151 var_decode_location (struct attribute *attr, struct symbol *sym,
17152                      struct dwarf2_cu *cu)
17153 {
17154   struct objfile *objfile = cu->objfile;
17155   struct comp_unit_head *cu_header = &cu->header;
17156
17157   /* NOTE drow/2003-01-30: There used to be a comment and some special
17158      code here to turn a symbol with DW_AT_external and a
17159      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
17160      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
17161      with some versions of binutils) where shared libraries could have
17162      relocations against symbols in their debug information - the
17163      minimal symbol would have the right address, but the debug info
17164      would not.  It's no longer necessary, because we will explicitly
17165      apply relocations when we read in the debug information now.  */
17166
17167   /* A DW_AT_location attribute with no contents indicates that a
17168      variable has been optimized away.  */
17169   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
17170     {
17171       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17172       return;
17173     }
17174
17175   /* Handle one degenerate form of location expression specially, to
17176      preserve GDB's previous behavior when section offsets are
17177      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
17178      then mark this symbol as LOC_STATIC.  */
17179
17180   if (attr_form_is_block (attr)
17181       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
17182            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
17183           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
17184               && (DW_BLOCK (attr)->size
17185                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
17186     {
17187       unsigned int dummy;
17188
17189       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
17190         SYMBOL_VALUE_ADDRESS (sym) =
17191           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
17192       else
17193         SYMBOL_VALUE_ADDRESS (sym) =
17194           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
17195       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
17196       fixup_symbol_section (sym, objfile);
17197       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
17198                                               SYMBOL_SECTION (sym));
17199       return;
17200     }
17201
17202   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
17203      expression evaluator, and use LOC_COMPUTED only when necessary
17204      (i.e. when the value of a register or memory location is
17205      referenced, or a thread-local block, etc.).  Then again, it might
17206      not be worthwhile.  I'm assuming that it isn't unless performance
17207      or memory numbers show me otherwise.  */
17208
17209   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
17210
17211   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
17212     cu->has_loclist = 1;
17213 }
17214
17215 /* Given a pointer to a DWARF information entry, figure out if we need
17216    to make a symbol table entry for it, and if so, create a new entry
17217    and return a pointer to it.
17218    If TYPE is NULL, determine symbol type from the die, otherwise
17219    used the passed type.
17220    If SPACE is not NULL, use it to hold the new symbol.  If it is
17221    NULL, allocate a new symbol on the objfile's obstack.  */
17222
17223 static struct symbol *
17224 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
17225                  struct symbol *space)
17226 {
17227   struct objfile *objfile = cu->objfile;
17228   struct symbol *sym = NULL;
17229   const char *name;
17230   struct attribute *attr = NULL;
17231   struct attribute *attr2 = NULL;
17232   CORE_ADDR baseaddr;
17233   struct pending **list_to_add = NULL;
17234
17235   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
17236
17237   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17238
17239   name = dwarf2_name (die, cu);
17240   if (name)
17241     {
17242       const char *linkagename;
17243       int suppress_add = 0;
17244
17245       if (space)
17246         sym = space;
17247       else
17248         sym = allocate_symbol (objfile);
17249       OBJSTAT (objfile, n_syms++);
17250
17251       /* Cache this symbol's name and the name's demangled form (if any).  */
17252       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
17253       linkagename = dwarf2_physname (name, die, cu);
17254       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
17255
17256       /* Fortran does not have mangling standard and the mangling does differ
17257          between gfortran, iFort etc.  */
17258       if (cu->language == language_fortran
17259           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
17260         symbol_set_demangled_name (&(sym->ginfo),
17261                                    dwarf2_full_name (name, die, cu),
17262                                    NULL);
17263
17264       /* Default assumptions.
17265          Use the passed type or decode it from the die.  */
17266       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17267       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17268       if (type != NULL)
17269         SYMBOL_TYPE (sym) = type;
17270       else
17271         SYMBOL_TYPE (sym) = die_type (die, cu);
17272       attr = dwarf2_attr (die,
17273                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
17274                           cu);
17275       if (attr)
17276         {
17277           SYMBOL_LINE (sym) = DW_UNSND (attr);
17278         }
17279
17280       attr = dwarf2_attr (die,
17281                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
17282                           cu);
17283       if (attr)
17284         {
17285           int file_index = DW_UNSND (attr);
17286
17287           if (cu->line_header == NULL
17288               || file_index > cu->line_header->num_file_names)
17289             complaint (&symfile_complaints,
17290                        _("file index out of range"));
17291           else if (file_index > 0)
17292             {
17293               struct file_entry *fe;
17294
17295               fe = &cu->line_header->file_names[file_index - 1];
17296               SYMBOL_SYMTAB (sym) = fe->symtab;
17297             }
17298         }
17299
17300       switch (die->tag)
17301         {
17302         case DW_TAG_label:
17303           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
17304           if (attr)
17305             {
17306               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
17307             }
17308           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
17309           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
17310           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
17311           add_symbol_to_list (sym, cu->list_in_scope);
17312           break;
17313         case DW_TAG_subprogram:
17314           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17315              finish_block.  */
17316           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17317           attr2 = dwarf2_attr (die, DW_AT_external, cu);
17318           if ((attr2 && (DW_UNSND (attr2) != 0))
17319               || cu->language == language_ada)
17320             {
17321               /* Subprograms marked external are stored as a global symbol.
17322                  Ada subprograms, whether marked external or not, are always
17323                  stored as a global symbol, because we want to be able to
17324                  access them globally.  For instance, we want to be able
17325                  to break on a nested subprogram without having to
17326                  specify the context.  */
17327               list_to_add = &global_symbols;
17328             }
17329           else
17330             {
17331               list_to_add = cu->list_in_scope;
17332             }
17333           break;
17334         case DW_TAG_inlined_subroutine:
17335           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17336              finish_block.  */
17337           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17338           SYMBOL_INLINED (sym) = 1;
17339           list_to_add = cu->list_in_scope;
17340           break;
17341         case DW_TAG_template_value_param:
17342           suppress_add = 1;
17343           /* Fall through.  */
17344         case DW_TAG_constant:
17345         case DW_TAG_variable:
17346         case DW_TAG_member:
17347           /* Compilation with minimal debug info may result in
17348              variables with missing type entries.  Change the
17349              misleading `void' type to something sensible.  */
17350           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
17351             SYMBOL_TYPE (sym)
17352               = objfile_type (objfile)->nodebug_data_symbol;
17353
17354           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17355           /* In the case of DW_TAG_member, we should only be called for
17356              static const members.  */
17357           if (die->tag == DW_TAG_member)
17358             {
17359               /* dwarf2_add_field uses die_is_declaration,
17360                  so we do the same.  */
17361               gdb_assert (die_is_declaration (die, cu));
17362               gdb_assert (attr);
17363             }
17364           if (attr)
17365             {
17366               dwarf2_const_value (attr, sym, cu);
17367               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17368               if (!suppress_add)
17369                 {
17370                   if (attr2 && (DW_UNSND (attr2) != 0))
17371                     list_to_add = &global_symbols;
17372                   else
17373                     list_to_add = cu->list_in_scope;
17374                 }
17375               break;
17376             }
17377           attr = dwarf2_attr (die, DW_AT_location, cu);
17378           if (attr)
17379             {
17380               var_decode_location (attr, sym, cu);
17381               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17382
17383               /* Fortran explicitly imports any global symbols to the local
17384                  scope by DW_TAG_common_block.  */
17385               if (cu->language == language_fortran && die->parent
17386                   && die->parent->tag == DW_TAG_common_block)
17387                 attr2 = NULL;
17388
17389               if (SYMBOL_CLASS (sym) == LOC_STATIC
17390                   && SYMBOL_VALUE_ADDRESS (sym) == 0
17391                   && !dwarf2_per_objfile->has_section_at_zero)
17392                 {
17393                   /* When a static variable is eliminated by the linker,
17394                      the corresponding debug information is not stripped
17395                      out, but the variable address is set to null;
17396                      do not add such variables into symbol table.  */
17397                 }
17398               else if (attr2 && (DW_UNSND (attr2) != 0))
17399                 {
17400                   /* Workaround gfortran PR debug/40040 - it uses
17401                      DW_AT_location for variables in -fPIC libraries which may
17402                      get overriden by other libraries/executable and get
17403                      a different address.  Resolve it by the minimal symbol
17404                      which may come from inferior's executable using copy
17405                      relocation.  Make this workaround only for gfortran as for
17406                      other compilers GDB cannot guess the minimal symbol
17407                      Fortran mangling kind.  */
17408                   if (cu->language == language_fortran && die->parent
17409                       && die->parent->tag == DW_TAG_module
17410                       && cu->producer
17411                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
17412                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17413
17414                   /* A variable with DW_AT_external is never static,
17415                      but it may be block-scoped.  */
17416                   list_to_add = (cu->list_in_scope == &file_symbols
17417                                  ? &global_symbols : cu->list_in_scope);
17418                 }
17419               else
17420                 list_to_add = cu->list_in_scope;
17421             }
17422           else
17423             {
17424               /* We do not know the address of this symbol.
17425                  If it is an external symbol and we have type information
17426                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
17427                  The address of the variable will then be determined from
17428                  the minimal symbol table whenever the variable is
17429                  referenced.  */
17430               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17431
17432               /* Fortran explicitly imports any global symbols to the local
17433                  scope by DW_TAG_common_block.  */
17434               if (cu->language == language_fortran && die->parent
17435                   && die->parent->tag == DW_TAG_common_block)
17436                 {
17437                   /* SYMBOL_CLASS doesn't matter here because
17438                      read_common_block is going to reset it.  */
17439                   if (!suppress_add)
17440                     list_to_add = cu->list_in_scope;
17441                 }
17442               else if (attr2 && (DW_UNSND (attr2) != 0)
17443                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
17444                 {
17445                   /* A variable with DW_AT_external is never static, but it
17446                      may be block-scoped.  */
17447                   list_to_add = (cu->list_in_scope == &file_symbols
17448                                  ? &global_symbols : cu->list_in_scope);
17449
17450                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17451                 }
17452               else if (!die_is_declaration (die, cu))
17453                 {
17454                   /* Use the default LOC_OPTIMIZED_OUT class.  */
17455                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
17456                   if (!suppress_add)
17457                     list_to_add = cu->list_in_scope;
17458                 }
17459             }
17460           break;
17461         case DW_TAG_formal_parameter:
17462           /* If we are inside a function, mark this as an argument.  If
17463              not, we might be looking at an argument to an inlined function
17464              when we do not have enough information to show inlined frames;
17465              pretend it's a local variable in that case so that the user can
17466              still see it.  */
17467           if (context_stack_depth > 0
17468               && context_stack[context_stack_depth - 1].name != NULL)
17469             SYMBOL_IS_ARGUMENT (sym) = 1;
17470           attr = dwarf2_attr (die, DW_AT_location, cu);
17471           if (attr)
17472             {
17473               var_decode_location (attr, sym, cu);
17474             }
17475           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17476           if (attr)
17477             {
17478               dwarf2_const_value (attr, sym, cu);
17479             }
17480
17481           list_to_add = cu->list_in_scope;
17482           break;
17483         case DW_TAG_unspecified_parameters:
17484           /* From varargs functions; gdb doesn't seem to have any
17485              interest in this information, so just ignore it for now.
17486              (FIXME?) */
17487           break;
17488         case DW_TAG_template_type_param:
17489           suppress_add = 1;
17490           /* Fall through.  */
17491         case DW_TAG_class_type:
17492         case DW_TAG_interface_type:
17493         case DW_TAG_structure_type:
17494         case DW_TAG_union_type:
17495         case DW_TAG_set_type:
17496         case DW_TAG_enumeration_type:
17497           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17498           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
17499
17500           {
17501             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
17502                really ever be static objects: otherwise, if you try
17503                to, say, break of a class's method and you're in a file
17504                which doesn't mention that class, it won't work unless
17505                the check for all static symbols in lookup_symbol_aux
17506                saves you.  See the OtherFileClass tests in
17507                gdb.c++/namespace.exp.  */
17508
17509             if (!suppress_add)
17510               {
17511                 list_to_add = (cu->list_in_scope == &file_symbols
17512                                && (cu->language == language_cplus
17513                                    || cu->language == language_java)
17514                                ? &global_symbols : cu->list_in_scope);
17515
17516                 /* The semantics of C++ state that "struct foo {
17517                    ... }" also defines a typedef for "foo".  A Java
17518                    class declaration also defines a typedef for the
17519                    class.  */
17520                 if (cu->language == language_cplus
17521                     || cu->language == language_java
17522                     || cu->language == language_ada)
17523                   {
17524                     /* The symbol's name is already allocated along
17525                        with this objfile, so we don't need to
17526                        duplicate it for the type.  */
17527                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
17528                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
17529                   }
17530               }
17531           }
17532           break;
17533         case DW_TAG_typedef:
17534           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17535           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17536           list_to_add = cu->list_in_scope;
17537           break;
17538         case DW_TAG_base_type:
17539         case DW_TAG_subrange_type:
17540           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17541           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17542           list_to_add = cu->list_in_scope;
17543           break;
17544         case DW_TAG_enumerator:
17545           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17546           if (attr)
17547             {
17548               dwarf2_const_value (attr, sym, cu);
17549             }
17550           {
17551             /* NOTE: carlton/2003-11-10: See comment above in the
17552                DW_TAG_class_type, etc. block.  */
17553
17554             list_to_add = (cu->list_in_scope == &file_symbols
17555                            && (cu->language == language_cplus
17556                                || cu->language == language_java)
17557                            ? &global_symbols : cu->list_in_scope);
17558           }
17559           break;
17560         case DW_TAG_namespace:
17561           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17562           list_to_add = &global_symbols;
17563           break;
17564         case DW_TAG_common_block:
17565           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
17566           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
17567           add_symbol_to_list (sym, cu->list_in_scope);
17568           break;
17569         default:
17570           /* Not a tag we recognize.  Hopefully we aren't processing
17571              trash data, but since we must specifically ignore things
17572              we don't recognize, there is nothing else we should do at
17573              this point.  */
17574           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
17575                      dwarf_tag_name (die->tag));
17576           break;
17577         }
17578
17579       if (suppress_add)
17580         {
17581           sym->hash_next = objfile->template_symbols;
17582           objfile->template_symbols = sym;
17583           list_to_add = NULL;
17584         }
17585
17586       if (list_to_add != NULL)
17587         add_symbol_to_list (sym, list_to_add);
17588
17589       /* For the benefit of old versions of GCC, check for anonymous
17590          namespaces based on the demangled name.  */
17591       if (!cu->processing_has_namespace_info
17592           && cu->language == language_cplus)
17593         cp_scan_for_anonymous_namespaces (sym, objfile);
17594     }
17595   return (sym);
17596 }
17597
17598 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
17599
17600 static struct symbol *
17601 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
17602 {
17603   return new_symbol_full (die, type, cu, NULL);
17604 }
17605
17606 /* Given an attr with a DW_FORM_dataN value in host byte order,
17607    zero-extend it as appropriate for the symbol's type.  The DWARF
17608    standard (v4) is not entirely clear about the meaning of using
17609    DW_FORM_dataN for a constant with a signed type, where the type is
17610    wider than the data.  The conclusion of a discussion on the DWARF
17611    list was that this is unspecified.  We choose to always zero-extend
17612    because that is the interpretation long in use by GCC.  */
17613
17614 static gdb_byte *
17615 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
17616                          struct dwarf2_cu *cu, LONGEST *value, int bits)
17617 {
17618   struct objfile *objfile = cu->objfile;
17619   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
17620                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
17621   LONGEST l = DW_UNSND (attr);
17622
17623   if (bits < sizeof (*value) * 8)
17624     {
17625       l &= ((LONGEST) 1 << bits) - 1;
17626       *value = l;
17627     }
17628   else if (bits == sizeof (*value) * 8)
17629     *value = l;
17630   else
17631     {
17632       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
17633       store_unsigned_integer (bytes, bits / 8, byte_order, l);
17634       return bytes;
17635     }
17636
17637   return NULL;
17638 }
17639
17640 /* Read a constant value from an attribute.  Either set *VALUE, or if
17641    the value does not fit in *VALUE, set *BYTES - either already
17642    allocated on the objfile obstack, or newly allocated on OBSTACK,
17643    or, set *BATON, if we translated the constant to a location
17644    expression.  */
17645
17646 static void
17647 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
17648                          const char *name, struct obstack *obstack,
17649                          struct dwarf2_cu *cu,
17650                          LONGEST *value, const gdb_byte **bytes,
17651                          struct dwarf2_locexpr_baton **baton)
17652 {
17653   struct objfile *objfile = cu->objfile;
17654   struct comp_unit_head *cu_header = &cu->header;
17655   struct dwarf_block *blk;
17656   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
17657                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
17658
17659   *value = 0;
17660   *bytes = NULL;
17661   *baton = NULL;
17662
17663   switch (attr->form)
17664     {
17665     case DW_FORM_addr:
17666     case DW_FORM_GNU_addr_index:
17667       {
17668         gdb_byte *data;
17669
17670         if (TYPE_LENGTH (type) != cu_header->addr_size)
17671           dwarf2_const_value_length_mismatch_complaint (name,
17672                                                         cu_header->addr_size,
17673                                                         TYPE_LENGTH (type));
17674         /* Symbols of this form are reasonably rare, so we just
17675            piggyback on the existing location code rather than writing
17676            a new implementation of symbol_computed_ops.  */
17677         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
17678         (*baton)->per_cu = cu->per_cu;
17679         gdb_assert ((*baton)->per_cu);
17680
17681         (*baton)->size = 2 + cu_header->addr_size;
17682         data = obstack_alloc (obstack, (*baton)->size);
17683         (*baton)->data = data;
17684
17685         data[0] = DW_OP_addr;
17686         store_unsigned_integer (&data[1], cu_header->addr_size,
17687                                 byte_order, DW_ADDR (attr));
17688         data[cu_header->addr_size + 1] = DW_OP_stack_value;
17689       }
17690       break;
17691     case DW_FORM_string:
17692     case DW_FORM_strp:
17693     case DW_FORM_GNU_str_index:
17694     case DW_FORM_GNU_strp_alt:
17695       /* DW_STRING is already allocated on the objfile obstack, point
17696          directly to it.  */
17697       *bytes = (const gdb_byte *) DW_STRING (attr);
17698       break;
17699     case DW_FORM_block1:
17700     case DW_FORM_block2:
17701     case DW_FORM_block4:
17702     case DW_FORM_block:
17703     case DW_FORM_exprloc:
17704       blk = DW_BLOCK (attr);
17705       if (TYPE_LENGTH (type) != blk->size)
17706         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
17707                                                       TYPE_LENGTH (type));
17708       *bytes = blk->data;
17709       break;
17710
17711       /* The DW_AT_const_value attributes are supposed to carry the
17712          symbol's value "represented as it would be on the target
17713          architecture."  By the time we get here, it's already been
17714          converted to host endianness, so we just need to sign- or
17715          zero-extend it as appropriate.  */
17716     case DW_FORM_data1:
17717       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
17718       break;
17719     case DW_FORM_data2:
17720       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
17721       break;
17722     case DW_FORM_data4:
17723       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
17724       break;
17725     case DW_FORM_data8:
17726       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
17727       break;
17728
17729     case DW_FORM_sdata:
17730       *value = DW_SND (attr);
17731       break;
17732
17733     case DW_FORM_udata:
17734       *value = DW_UNSND (attr);
17735       break;
17736
17737     default:
17738       complaint (&symfile_complaints,
17739                  _("unsupported const value attribute form: '%s'"),
17740                  dwarf_form_name (attr->form));
17741       *value = 0;
17742       break;
17743     }
17744 }
17745
17746
17747 /* Copy constant value from an attribute to a symbol.  */
17748
17749 static void
17750 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17751                     struct dwarf2_cu *cu)
17752 {
17753   struct objfile *objfile = cu->objfile;
17754   struct comp_unit_head *cu_header = &cu->header;
17755   LONGEST value;
17756   const gdb_byte *bytes;
17757   struct dwarf2_locexpr_baton *baton;
17758
17759   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17760                            SYMBOL_PRINT_NAME (sym),
17761                            &objfile->objfile_obstack, cu,
17762                            &value, &bytes, &baton);
17763
17764   if (baton != NULL)
17765     {
17766       SYMBOL_LOCATION_BATON (sym) = baton;
17767       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17768     }
17769   else if (bytes != NULL)
17770      {
17771       SYMBOL_VALUE_BYTES (sym) = bytes;
17772       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17773     }
17774   else
17775     {
17776       SYMBOL_VALUE (sym) = value;
17777       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17778     }
17779 }
17780
17781 /* Return the type of the die in question using its DW_AT_type attribute.  */
17782
17783 static struct type *
17784 die_type (struct die_info *die, struct dwarf2_cu *cu)
17785 {
17786   struct attribute *type_attr;
17787
17788   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17789   if (!type_attr)
17790     {
17791       /* A missing DW_AT_type represents a void type.  */
17792       return objfile_type (cu->objfile)->builtin_void;
17793     }
17794
17795   return lookup_die_type (die, type_attr, cu);
17796 }
17797
17798 /* True iff CU's producer generates GNAT Ada auxiliary information
17799    that allows to find parallel types through that information instead
17800    of having to do expensive parallel lookups by type name.  */
17801
17802 static int
17803 need_gnat_info (struct dwarf2_cu *cu)
17804 {
17805   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17806      of GNAT produces this auxiliary information, without any indication
17807      that it is produced.  Part of enhancing the FSF version of GNAT
17808      to produce that information will be to put in place an indicator
17809      that we can use in order to determine whether the descriptive type
17810      info is available or not.  One suggestion that has been made is
17811      to use a new attribute, attached to the CU die.  For now, assume
17812      that the descriptive type info is not available.  */
17813   return 0;
17814 }
17815
17816 /* Return the auxiliary type of the die in question using its
17817    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17818    attribute is not present.  */
17819
17820 static struct type *
17821 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17822 {
17823   struct attribute *type_attr;
17824
17825   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17826   if (!type_attr)
17827     return NULL;
17828
17829   return lookup_die_type (die, type_attr, cu);
17830 }
17831
17832 /* If DIE has a descriptive_type attribute, then set the TYPE's
17833    descriptive type accordingly.  */
17834
17835 static void
17836 set_descriptive_type (struct type *type, struct die_info *die,
17837                       struct dwarf2_cu *cu)
17838 {
17839   struct type *descriptive_type = die_descriptive_type (die, cu);
17840
17841   if (descriptive_type)
17842     {
17843       ALLOCATE_GNAT_AUX_TYPE (type);
17844       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17845     }
17846 }
17847
17848 /* Return the containing type of the die in question using its
17849    DW_AT_containing_type attribute.  */
17850
17851 static struct type *
17852 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17853 {
17854   struct attribute *type_attr;
17855
17856   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17857   if (!type_attr)
17858     error (_("Dwarf Error: Problem turning containing type into gdb type "
17859              "[in module %s]"), objfile_name (cu->objfile));
17860
17861   return lookup_die_type (die, type_attr, cu);
17862 }
17863
17864 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17865
17866 static struct type *
17867 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17868 {
17869   struct objfile *objfile = dwarf2_per_objfile->objfile;
17870   char *message, *saved;
17871
17872   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17873                         objfile_name (objfile),
17874                         cu->header.offset.sect_off,
17875                         die->offset.sect_off);
17876   saved = obstack_copy0 (&objfile->objfile_obstack,
17877                          message, strlen (message));
17878   xfree (message);
17879
17880   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17881 }
17882
17883 /* Look up the type of DIE in CU using its type attribute ATTR.
17884    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17885    DW_AT_containing_type.
17886    If there is no type substitute an error marker.  */
17887
17888 static struct type *
17889 lookup_die_type (struct die_info *die, const struct attribute *attr,
17890                  struct dwarf2_cu *cu)
17891 {
17892   struct objfile *objfile = cu->objfile;
17893   struct type *this_type;
17894
17895   gdb_assert (attr->name == DW_AT_type
17896               || attr->name == DW_AT_GNAT_descriptive_type
17897               || attr->name == DW_AT_containing_type);
17898
17899   /* First see if we have it cached.  */
17900
17901   if (attr->form == DW_FORM_GNU_ref_alt)
17902     {
17903       struct dwarf2_per_cu_data *per_cu;
17904       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17905
17906       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17907       this_type = get_die_type_at_offset (offset, per_cu);
17908     }
17909   else if (attr_form_is_ref (attr))
17910     {
17911       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17912
17913       this_type = get_die_type_at_offset (offset, cu->per_cu);
17914     }
17915   else if (attr->form == DW_FORM_ref_sig8)
17916     {
17917       ULONGEST signature = DW_SIGNATURE (attr);
17918
17919       return get_signatured_type (die, signature, cu);
17920     }
17921   else
17922     {
17923       complaint (&symfile_complaints,
17924                  _("Dwarf Error: Bad type attribute %s in DIE"
17925                    " at 0x%x [in module %s]"),
17926                  dwarf_attr_name (attr->name), die->offset.sect_off,
17927                  objfile_name (objfile));
17928       return build_error_marker_type (cu, die);
17929     }
17930
17931   /* If not cached we need to read it in.  */
17932
17933   if (this_type == NULL)
17934     {
17935       struct die_info *type_die = NULL;
17936       struct dwarf2_cu *type_cu = cu;
17937
17938       if (attr_form_is_ref (attr))
17939         type_die = follow_die_ref (die, attr, &type_cu);
17940       if (type_die == NULL)
17941         return build_error_marker_type (cu, die);
17942       /* If we find the type now, it's probably because the type came
17943          from an inter-CU reference and the type's CU got expanded before
17944          ours.  */
17945       this_type = read_type_die (type_die, type_cu);
17946     }
17947
17948   /* If we still don't have a type use an error marker.  */
17949
17950   if (this_type == NULL)
17951     return build_error_marker_type (cu, die);
17952
17953   return this_type;
17954 }
17955
17956 /* Return the type in DIE, CU.
17957    Returns NULL for invalid types.
17958
17959    This first does a lookup in die_type_hash,
17960    and only reads the die in if necessary.
17961
17962    NOTE: This can be called when reading in partial or full symbols.  */
17963
17964 static struct type *
17965 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17966 {
17967   struct type *this_type;
17968
17969   this_type = get_die_type (die, cu);
17970   if (this_type)
17971     return this_type;
17972
17973   return read_type_die_1 (die, cu);
17974 }
17975
17976 /* Read the type in DIE, CU.
17977    Returns NULL for invalid types.  */
17978
17979 static struct type *
17980 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17981 {
17982   struct type *this_type = NULL;
17983
17984   switch (die->tag)
17985     {
17986     case DW_TAG_class_type:
17987     case DW_TAG_interface_type:
17988     case DW_TAG_structure_type:
17989     case DW_TAG_union_type:
17990       this_type = read_structure_type (die, cu);
17991       break;
17992     case DW_TAG_enumeration_type:
17993       this_type = read_enumeration_type (die, cu);
17994       break;
17995     case DW_TAG_subprogram:
17996     case DW_TAG_subroutine_type:
17997     case DW_TAG_inlined_subroutine:
17998       this_type = read_subroutine_type (die, cu);
17999       break;
18000     case DW_TAG_array_type:
18001       this_type = read_array_type (die, cu);
18002       break;
18003     case DW_TAG_set_type:
18004       this_type = read_set_type (die, cu);
18005       break;
18006     case DW_TAG_pointer_type:
18007       this_type = read_tag_pointer_type (die, cu);
18008       break;
18009     case DW_TAG_ptr_to_member_type:
18010       this_type = read_tag_ptr_to_member_type (die, cu);
18011       break;
18012     case DW_TAG_reference_type:
18013       this_type = read_tag_reference_type (die, cu);
18014       break;
18015     case DW_TAG_const_type:
18016       this_type = read_tag_const_type (die, cu);
18017       break;
18018     case DW_TAG_volatile_type:
18019       this_type = read_tag_volatile_type (die, cu);
18020       break;
18021     case DW_TAG_restrict_type:
18022       this_type = read_tag_restrict_type (die, cu);
18023       break;
18024     case DW_TAG_string_type:
18025       this_type = read_tag_string_type (die, cu);
18026       break;
18027     case DW_TAG_typedef:
18028       this_type = read_typedef (die, cu);
18029       break;
18030     case DW_TAG_subrange_type:
18031       this_type = read_subrange_type (die, cu);
18032       break;
18033     case DW_TAG_base_type:
18034       this_type = read_base_type (die, cu);
18035       break;
18036     case DW_TAG_unspecified_type:
18037       this_type = read_unspecified_type (die, cu);
18038       break;
18039     case DW_TAG_namespace:
18040       this_type = read_namespace_type (die, cu);
18041       break;
18042     case DW_TAG_module:
18043       this_type = read_module_type (die, cu);
18044       break;
18045     default:
18046       complaint (&symfile_complaints,
18047                  _("unexpected tag in read_type_die: '%s'"),
18048                  dwarf_tag_name (die->tag));
18049       break;
18050     }
18051
18052   return this_type;
18053 }
18054
18055 /* See if we can figure out if the class lives in a namespace.  We do
18056    this by looking for a member function; its demangled name will
18057    contain namespace info, if there is any.
18058    Return the computed name or NULL.
18059    Space for the result is allocated on the objfile's obstack.
18060    This is the full-die version of guess_partial_die_structure_name.
18061    In this case we know DIE has no useful parent.  */
18062
18063 static char *
18064 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
18065 {
18066   struct die_info *spec_die;
18067   struct dwarf2_cu *spec_cu;
18068   struct die_info *child;
18069
18070   spec_cu = cu;
18071   spec_die = die_specification (die, &spec_cu);
18072   if (spec_die != NULL)
18073     {
18074       die = spec_die;
18075       cu = spec_cu;
18076     }
18077
18078   for (child = die->child;
18079        child != NULL;
18080        child = child->sibling)
18081     {
18082       if (child->tag == DW_TAG_subprogram)
18083         {
18084           struct attribute *attr;
18085
18086           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
18087           if (attr == NULL)
18088             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
18089           if (attr != NULL)
18090             {
18091               char *actual_name
18092                 = language_class_name_from_physname (cu->language_defn,
18093                                                      DW_STRING (attr));
18094               char *name = NULL;
18095
18096               if (actual_name != NULL)
18097                 {
18098                   const char *die_name = dwarf2_name (die, cu);
18099
18100                   if (die_name != NULL
18101                       && strcmp (die_name, actual_name) != 0)
18102                     {
18103                       /* Strip off the class name from the full name.
18104                          We want the prefix.  */
18105                       int die_name_len = strlen (die_name);
18106                       int actual_name_len = strlen (actual_name);
18107
18108                       /* Test for '::' as a sanity check.  */
18109                       if (actual_name_len > die_name_len + 2
18110                           && actual_name[actual_name_len
18111                                          - die_name_len - 1] == ':')
18112                         name =
18113                           obstack_copy0 (&cu->objfile->objfile_obstack,
18114                                          actual_name,
18115                                          actual_name_len - die_name_len - 2);
18116                     }
18117                 }
18118               xfree (actual_name);
18119               return name;
18120             }
18121         }
18122     }
18123
18124   return NULL;
18125 }
18126
18127 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
18128    prefix part in such case.  See
18129    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18130
18131 static char *
18132 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
18133 {
18134   struct attribute *attr;
18135   char *base;
18136
18137   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
18138       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
18139     return NULL;
18140
18141   attr = dwarf2_attr (die, DW_AT_name, cu);
18142   if (attr != NULL && DW_STRING (attr) != NULL)
18143     return NULL;
18144
18145   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18146   if (attr == NULL)
18147     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18148   if (attr == NULL || DW_STRING (attr) == NULL)
18149     return NULL;
18150
18151   /* dwarf2_name had to be already called.  */
18152   gdb_assert (DW_STRING_IS_CANONICAL (attr));
18153
18154   /* Strip the base name, keep any leading namespaces/classes.  */
18155   base = strrchr (DW_STRING (attr), ':');
18156   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
18157     return "";
18158
18159   return obstack_copy0 (&cu->objfile->objfile_obstack,
18160                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
18161 }
18162
18163 /* Return the name of the namespace/class that DIE is defined within,
18164    or "" if we can't tell.  The caller should not xfree the result.
18165
18166    For example, if we're within the method foo() in the following
18167    code:
18168
18169    namespace N {
18170      class C {
18171        void foo () {
18172        }
18173      };
18174    }
18175
18176    then determine_prefix on foo's die will return "N::C".  */
18177
18178 static const char *
18179 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
18180 {
18181   struct die_info *parent, *spec_die;
18182   struct dwarf2_cu *spec_cu;
18183   struct type *parent_type;
18184   char *retval;
18185
18186   if (cu->language != language_cplus && cu->language != language_java
18187       && cu->language != language_fortran)
18188     return "";
18189
18190   retval = anonymous_struct_prefix (die, cu);
18191   if (retval)
18192     return retval;
18193
18194   /* We have to be careful in the presence of DW_AT_specification.
18195      For example, with GCC 3.4, given the code
18196
18197      namespace N {
18198        void foo() {
18199          // Definition of N::foo.
18200        }
18201      }
18202
18203      then we'll have a tree of DIEs like this:
18204
18205      1: DW_TAG_compile_unit
18206        2: DW_TAG_namespace        // N
18207          3: DW_TAG_subprogram     // declaration of N::foo
18208        4: DW_TAG_subprogram       // definition of N::foo
18209             DW_AT_specification   // refers to die #3
18210
18211      Thus, when processing die #4, we have to pretend that we're in
18212      the context of its DW_AT_specification, namely the contex of die
18213      #3.  */
18214   spec_cu = cu;
18215   spec_die = die_specification (die, &spec_cu);
18216   if (spec_die == NULL)
18217     parent = die->parent;
18218   else
18219     {
18220       parent = spec_die->parent;
18221       cu = spec_cu;
18222     }
18223
18224   if (parent == NULL)
18225     return "";
18226   else if (parent->building_fullname)
18227     {
18228       const char *name;
18229       const char *parent_name;
18230
18231       /* It has been seen on RealView 2.2 built binaries,
18232          DW_TAG_template_type_param types actually _defined_ as
18233          children of the parent class:
18234
18235          enum E {};
18236          template class <class Enum> Class{};
18237          Class<enum E> class_e;
18238
18239          1: DW_TAG_class_type (Class)
18240            2: DW_TAG_enumeration_type (E)
18241              3: DW_TAG_enumerator (enum1:0)
18242              3: DW_TAG_enumerator (enum2:1)
18243              ...
18244            2: DW_TAG_template_type_param
18245               DW_AT_type  DW_FORM_ref_udata (E)
18246
18247          Besides being broken debug info, it can put GDB into an
18248          infinite loop.  Consider:
18249
18250          When we're building the full name for Class<E>, we'll start
18251          at Class, and go look over its template type parameters,
18252          finding E.  We'll then try to build the full name of E, and
18253          reach here.  We're now trying to build the full name of E,
18254          and look over the parent DIE for containing scope.  In the
18255          broken case, if we followed the parent DIE of E, we'd again
18256          find Class, and once again go look at its template type
18257          arguments, etc., etc.  Simply don't consider such parent die
18258          as source-level parent of this die (it can't be, the language
18259          doesn't allow it), and break the loop here.  */
18260       name = dwarf2_name (die, cu);
18261       parent_name = dwarf2_name (parent, cu);
18262       complaint (&symfile_complaints,
18263                  _("template param type '%s' defined within parent '%s'"),
18264                  name ? name : "<unknown>",
18265                  parent_name ? parent_name : "<unknown>");
18266       return "";
18267     }
18268   else
18269     switch (parent->tag)
18270       {
18271       case DW_TAG_namespace:
18272         parent_type = read_type_die (parent, cu);
18273         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
18274            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
18275            Work around this problem here.  */
18276         if (cu->language == language_cplus
18277             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
18278           return "";
18279         /* We give a name to even anonymous namespaces.  */
18280         return TYPE_TAG_NAME (parent_type);
18281       case DW_TAG_class_type:
18282       case DW_TAG_interface_type:
18283       case DW_TAG_structure_type:
18284       case DW_TAG_union_type:
18285       case DW_TAG_module:
18286         parent_type = read_type_die (parent, cu);
18287         if (TYPE_TAG_NAME (parent_type) != NULL)
18288           return TYPE_TAG_NAME (parent_type);
18289         else
18290           /* An anonymous structure is only allowed non-static data
18291              members; no typedefs, no member functions, et cetera.
18292              So it does not need a prefix.  */
18293           return "";
18294       case DW_TAG_compile_unit:
18295       case DW_TAG_partial_unit:
18296         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
18297         if (cu->language == language_cplus
18298             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18299             && die->child != NULL
18300             && (die->tag == DW_TAG_class_type
18301                 || die->tag == DW_TAG_structure_type
18302                 || die->tag == DW_TAG_union_type))
18303           {
18304             char *name = guess_full_die_structure_name (die, cu);
18305             if (name != NULL)
18306               return name;
18307           }
18308         return "";
18309       default:
18310         return determine_prefix (parent, cu);
18311       }
18312 }
18313
18314 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
18315    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
18316    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
18317    an obconcat, otherwise allocate storage for the result.  The CU argument is
18318    used to determine the language and hence, the appropriate separator.  */
18319
18320 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
18321
18322 static char *
18323 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
18324                  int physname, struct dwarf2_cu *cu)
18325 {
18326   const char *lead = "";
18327   const char *sep;
18328
18329   if (suffix == NULL || suffix[0] == '\0'
18330       || prefix == NULL || prefix[0] == '\0')
18331     sep = "";
18332   else if (cu->language == language_java)
18333     sep = ".";
18334   else if (cu->language == language_fortran && physname)
18335     {
18336       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
18337          DW_AT_MIPS_linkage_name is preferred and used instead.  */
18338
18339       lead = "__";
18340       sep = "_MOD_";
18341     }
18342   else
18343     sep = "::";
18344
18345   if (prefix == NULL)
18346     prefix = "";
18347   if (suffix == NULL)
18348     suffix = "";
18349
18350   if (obs == NULL)
18351     {
18352       char *retval
18353         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
18354
18355       strcpy (retval, lead);
18356       strcat (retval, prefix);
18357       strcat (retval, sep);
18358       strcat (retval, suffix);
18359       return retval;
18360     }
18361   else
18362     {
18363       /* We have an obstack.  */
18364       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
18365     }
18366 }
18367
18368 /* Return sibling of die, NULL if no sibling.  */
18369
18370 static struct die_info *
18371 sibling_die (struct die_info *die)
18372 {
18373   return die->sibling;
18374 }
18375
18376 /* Get name of a die, return NULL if not found.  */
18377
18378 static const char *
18379 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
18380                           struct obstack *obstack)
18381 {
18382   if (name && cu->language == language_cplus)
18383     {
18384       char *canon_name = cp_canonicalize_string (name);
18385
18386       if (canon_name != NULL)
18387         {
18388           if (strcmp (canon_name, name) != 0)
18389             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
18390           xfree (canon_name);
18391         }
18392     }
18393
18394   return name;
18395 }
18396
18397 /* Get name of a die, return NULL if not found.  */
18398
18399 static const char *
18400 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
18401 {
18402   struct attribute *attr;
18403
18404   attr = dwarf2_attr (die, DW_AT_name, cu);
18405   if ((!attr || !DW_STRING (attr))
18406       && die->tag != DW_TAG_class_type
18407       && die->tag != DW_TAG_interface_type
18408       && die->tag != DW_TAG_structure_type
18409       && die->tag != DW_TAG_union_type)
18410     return NULL;
18411
18412   switch (die->tag)
18413     {
18414     case DW_TAG_compile_unit:
18415     case DW_TAG_partial_unit:
18416       /* Compilation units have a DW_AT_name that is a filename, not
18417          a source language identifier.  */
18418     case DW_TAG_enumeration_type:
18419     case DW_TAG_enumerator:
18420       /* These tags always have simple identifiers already; no need
18421          to canonicalize them.  */
18422       return DW_STRING (attr);
18423
18424     case DW_TAG_subprogram:
18425       /* Java constructors will all be named "<init>", so return
18426          the class name when we see this special case.  */
18427       if (cu->language == language_java
18428           && DW_STRING (attr) != NULL
18429           && strcmp (DW_STRING (attr), "<init>") == 0)
18430         {
18431           struct dwarf2_cu *spec_cu = cu;
18432           struct die_info *spec_die;
18433
18434           /* GCJ will output '<init>' for Java constructor names.
18435              For this special case, return the name of the parent class.  */
18436
18437           /* GCJ may output suprogram DIEs with AT_specification set.
18438              If so, use the name of the specified DIE.  */
18439           spec_die = die_specification (die, &spec_cu);
18440           if (spec_die != NULL)
18441             return dwarf2_name (spec_die, spec_cu);
18442
18443           do
18444             {
18445               die = die->parent;
18446               if (die->tag == DW_TAG_class_type)
18447                 return dwarf2_name (die, cu);
18448             }
18449           while (die->tag != DW_TAG_compile_unit
18450                  && die->tag != DW_TAG_partial_unit);
18451         }
18452       break;
18453
18454     case DW_TAG_class_type:
18455     case DW_TAG_interface_type:
18456     case DW_TAG_structure_type:
18457     case DW_TAG_union_type:
18458       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
18459          structures or unions.  These were of the form "._%d" in GCC 4.1,
18460          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
18461          and GCC 4.4.  We work around this problem by ignoring these.  */
18462       if (attr && DW_STRING (attr)
18463           && (strncmp (DW_STRING (attr), "._", 2) == 0
18464               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
18465         return NULL;
18466
18467       /* GCC might emit a nameless typedef that has a linkage name.  See
18468          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18469       if (!attr || DW_STRING (attr) == NULL)
18470         {
18471           char *demangled = NULL;
18472
18473           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18474           if (attr == NULL)
18475             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18476
18477           if (attr == NULL || DW_STRING (attr) == NULL)
18478             return NULL;
18479
18480           /* Avoid demangling DW_STRING (attr) the second time on a second
18481              call for the same DIE.  */
18482           if (!DW_STRING_IS_CANONICAL (attr))
18483             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
18484
18485           if (demangled)
18486             {
18487               char *base;
18488
18489               /* FIXME: we already did this for the partial symbol... */
18490               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
18491                                                 demangled, strlen (demangled));
18492               DW_STRING_IS_CANONICAL (attr) = 1;
18493               xfree (demangled);
18494
18495               /* Strip any leading namespaces/classes, keep only the base name.
18496                  DW_AT_name for named DIEs does not contain the prefixes.  */
18497               base = strrchr (DW_STRING (attr), ':');
18498               if (base && base > DW_STRING (attr) && base[-1] == ':')
18499                 return &base[1];
18500               else
18501                 return DW_STRING (attr);
18502             }
18503         }
18504       break;
18505
18506     default:
18507       break;
18508     }
18509
18510   if (!DW_STRING_IS_CANONICAL (attr))
18511     {
18512       DW_STRING (attr)
18513         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
18514                                     &cu->objfile->objfile_obstack);
18515       DW_STRING_IS_CANONICAL (attr) = 1;
18516     }
18517   return DW_STRING (attr);
18518 }
18519
18520 /* Return the die that this die in an extension of, or NULL if there
18521    is none.  *EXT_CU is the CU containing DIE on input, and the CU
18522    containing the return value on output.  */
18523
18524 static struct die_info *
18525 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
18526 {
18527   struct attribute *attr;
18528
18529   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
18530   if (attr == NULL)
18531     return NULL;
18532
18533   return follow_die_ref (die, attr, ext_cu);
18534 }
18535
18536 /* Convert a DIE tag into its string name.  */
18537
18538 static const char *
18539 dwarf_tag_name (unsigned tag)
18540 {
18541   const char *name = get_DW_TAG_name (tag);
18542
18543   if (name == NULL)
18544     return "DW_TAG_<unknown>";
18545
18546   return name;
18547 }
18548
18549 /* Convert a DWARF attribute code into its string name.  */
18550
18551 static const char *
18552 dwarf_attr_name (unsigned attr)
18553 {
18554   const char *name;
18555
18556 #ifdef MIPS /* collides with DW_AT_HP_block_index */
18557   if (attr == DW_AT_MIPS_fde)
18558     return "DW_AT_MIPS_fde";
18559 #else
18560   if (attr == DW_AT_HP_block_index)
18561     return "DW_AT_HP_block_index";
18562 #endif
18563
18564   name = get_DW_AT_name (attr);
18565
18566   if (name == NULL)
18567     return "DW_AT_<unknown>";
18568
18569   return name;
18570 }
18571
18572 /* Convert a DWARF value form code into its string name.  */
18573
18574 static const char *
18575 dwarf_form_name (unsigned form)
18576 {
18577   const char *name = get_DW_FORM_name (form);
18578
18579   if (name == NULL)
18580     return "DW_FORM_<unknown>";
18581
18582   return name;
18583 }
18584
18585 static char *
18586 dwarf_bool_name (unsigned mybool)
18587 {
18588   if (mybool)
18589     return "TRUE";
18590   else
18591     return "FALSE";
18592 }
18593
18594 /* Convert a DWARF type code into its string name.  */
18595
18596 static const char *
18597 dwarf_type_encoding_name (unsigned enc)
18598 {
18599   const char *name = get_DW_ATE_name (enc);
18600
18601   if (name == NULL)
18602     return "DW_ATE_<unknown>";
18603
18604   return name;
18605 }
18606
18607 static void
18608 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
18609 {
18610   unsigned int i;
18611
18612   print_spaces (indent, f);
18613   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
18614            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
18615
18616   if (die->parent != NULL)
18617     {
18618       print_spaces (indent, f);
18619       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
18620                           die->parent->offset.sect_off);
18621     }
18622
18623   print_spaces (indent, f);
18624   fprintf_unfiltered (f, "  has children: %s\n",
18625            dwarf_bool_name (die->child != NULL));
18626
18627   print_spaces (indent, f);
18628   fprintf_unfiltered (f, "  attributes:\n");
18629
18630   for (i = 0; i < die->num_attrs; ++i)
18631     {
18632       print_spaces (indent, f);
18633       fprintf_unfiltered (f, "    %s (%s) ",
18634                dwarf_attr_name (die->attrs[i].name),
18635                dwarf_form_name (die->attrs[i].form));
18636
18637       switch (die->attrs[i].form)
18638         {
18639         case DW_FORM_addr:
18640         case DW_FORM_GNU_addr_index:
18641           fprintf_unfiltered (f, "address: ");
18642           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
18643           break;
18644         case DW_FORM_block2:
18645         case DW_FORM_block4:
18646         case DW_FORM_block:
18647         case DW_FORM_block1:
18648           fprintf_unfiltered (f, "block: size %s",
18649                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18650           break;
18651         case DW_FORM_exprloc:
18652           fprintf_unfiltered (f, "expression: size %s",
18653                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18654           break;
18655         case DW_FORM_ref_addr:
18656           fprintf_unfiltered (f, "ref address: ");
18657           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18658           break;
18659         case DW_FORM_GNU_ref_alt:
18660           fprintf_unfiltered (f, "alt ref address: ");
18661           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18662           break;
18663         case DW_FORM_ref1:
18664         case DW_FORM_ref2:
18665         case DW_FORM_ref4:
18666         case DW_FORM_ref8:
18667         case DW_FORM_ref_udata:
18668           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
18669                               (long) (DW_UNSND (&die->attrs[i])));
18670           break;
18671         case DW_FORM_data1:
18672         case DW_FORM_data2:
18673         case DW_FORM_data4:
18674         case DW_FORM_data8:
18675         case DW_FORM_udata:
18676         case DW_FORM_sdata:
18677           fprintf_unfiltered (f, "constant: %s",
18678                               pulongest (DW_UNSND (&die->attrs[i])));
18679           break;
18680         case DW_FORM_sec_offset:
18681           fprintf_unfiltered (f, "section offset: %s",
18682                               pulongest (DW_UNSND (&die->attrs[i])));
18683           break;
18684         case DW_FORM_ref_sig8:
18685           fprintf_unfiltered (f, "signature: %s",
18686                               hex_string (DW_SIGNATURE (&die->attrs[i])));
18687           break;
18688         case DW_FORM_string:
18689         case DW_FORM_strp:
18690         case DW_FORM_GNU_str_index:
18691         case DW_FORM_GNU_strp_alt:
18692           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
18693                    DW_STRING (&die->attrs[i])
18694                    ? DW_STRING (&die->attrs[i]) : "",
18695                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
18696           break;
18697         case DW_FORM_flag:
18698           if (DW_UNSND (&die->attrs[i]))
18699             fprintf_unfiltered (f, "flag: TRUE");
18700           else
18701             fprintf_unfiltered (f, "flag: FALSE");
18702           break;
18703         case DW_FORM_flag_present:
18704           fprintf_unfiltered (f, "flag: TRUE");
18705           break;
18706         case DW_FORM_indirect:
18707           /* The reader will have reduced the indirect form to
18708              the "base form" so this form should not occur.  */
18709           fprintf_unfiltered (f, 
18710                               "unexpected attribute form: DW_FORM_indirect");
18711           break;
18712         default:
18713           fprintf_unfiltered (f, "unsupported attribute form: %d.",
18714                    die->attrs[i].form);
18715           break;
18716         }
18717       fprintf_unfiltered (f, "\n");
18718     }
18719 }
18720
18721 static void
18722 dump_die_for_error (struct die_info *die)
18723 {
18724   dump_die_shallow (gdb_stderr, 0, die);
18725 }
18726
18727 static void
18728 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
18729 {
18730   int indent = level * 4;
18731
18732   gdb_assert (die != NULL);
18733
18734   if (level >= max_level)
18735     return;
18736
18737   dump_die_shallow (f, indent, die);
18738
18739   if (die->child != NULL)
18740     {
18741       print_spaces (indent, f);
18742       fprintf_unfiltered (f, "  Children:");
18743       if (level + 1 < max_level)
18744         {
18745           fprintf_unfiltered (f, "\n");
18746           dump_die_1 (f, level + 1, max_level, die->child);
18747         }
18748       else
18749         {
18750           fprintf_unfiltered (f,
18751                               " [not printed, max nesting level reached]\n");
18752         }
18753     }
18754
18755   if (die->sibling != NULL && level > 0)
18756     {
18757       dump_die_1 (f, level, max_level, die->sibling);
18758     }
18759 }
18760
18761 /* This is called from the pdie macro in gdbinit.in.
18762    It's not static so gcc will keep a copy callable from gdb.  */
18763
18764 void
18765 dump_die (struct die_info *die, int max_level)
18766 {
18767   dump_die_1 (gdb_stdlog, 0, max_level, die);
18768 }
18769
18770 static void
18771 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18772 {
18773   void **slot;
18774
18775   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18776                                    INSERT);
18777
18778   *slot = die;
18779 }
18780
18781 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18782    required kind.  */
18783
18784 static sect_offset
18785 dwarf2_get_ref_die_offset (const struct attribute *attr)
18786 {
18787   sect_offset retval = { DW_UNSND (attr) };
18788
18789   if (attr_form_is_ref (attr))
18790     return retval;
18791
18792   retval.sect_off = 0;
18793   complaint (&symfile_complaints,
18794              _("unsupported die ref attribute form: '%s'"),
18795              dwarf_form_name (attr->form));
18796   return retval;
18797 }
18798
18799 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18800  * the value held by the attribute is not constant.  */
18801
18802 static LONGEST
18803 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18804 {
18805   if (attr->form == DW_FORM_sdata)
18806     return DW_SND (attr);
18807   else if (attr->form == DW_FORM_udata
18808            || attr->form == DW_FORM_data1
18809            || attr->form == DW_FORM_data2
18810            || attr->form == DW_FORM_data4
18811            || attr->form == DW_FORM_data8)
18812     return DW_UNSND (attr);
18813   else
18814     {
18815       complaint (&symfile_complaints,
18816                  _("Attribute value is not a constant (%s)"),
18817                  dwarf_form_name (attr->form));
18818       return default_value;
18819     }
18820 }
18821
18822 /* Follow reference or signature attribute ATTR of SRC_DIE.
18823    On entry *REF_CU is the CU of SRC_DIE.
18824    On exit *REF_CU is the CU of the result.  */
18825
18826 static struct die_info *
18827 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18828                        struct dwarf2_cu **ref_cu)
18829 {
18830   struct die_info *die;
18831
18832   if (attr_form_is_ref (attr))
18833     die = follow_die_ref (src_die, attr, ref_cu);
18834   else if (attr->form == DW_FORM_ref_sig8)
18835     die = follow_die_sig (src_die, attr, ref_cu);
18836   else
18837     {
18838       dump_die_for_error (src_die);
18839       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18840              objfile_name ((*ref_cu)->objfile));
18841     }
18842
18843   return die;
18844 }
18845
18846 /* Follow reference OFFSET.
18847    On entry *REF_CU is the CU of the source die referencing OFFSET.
18848    On exit *REF_CU is the CU of the result.
18849    Returns NULL if OFFSET is invalid.  */
18850
18851 static struct die_info *
18852 follow_die_offset (sect_offset offset, int offset_in_dwz,
18853                    struct dwarf2_cu **ref_cu)
18854 {
18855   struct die_info temp_die;
18856   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18857
18858   gdb_assert (cu->per_cu != NULL);
18859
18860   target_cu = cu;
18861
18862   if (cu->per_cu->is_debug_types)
18863     {
18864       /* .debug_types CUs cannot reference anything outside their CU.
18865          If they need to, they have to reference a signatured type via
18866          DW_FORM_ref_sig8.  */
18867       if (! offset_in_cu_p (&cu->header, offset))
18868         return NULL;
18869     }
18870   else if (offset_in_dwz != cu->per_cu->is_dwz
18871            || ! offset_in_cu_p (&cu->header, offset))
18872     {
18873       struct dwarf2_per_cu_data *per_cu;
18874
18875       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18876                                                  cu->objfile);
18877
18878       /* If necessary, add it to the queue and load its DIEs.  */
18879       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18880         load_full_comp_unit (per_cu, cu->language);
18881
18882       target_cu = per_cu->cu;
18883     }
18884   else if (cu->dies == NULL)
18885     {
18886       /* We're loading full DIEs during partial symbol reading.  */
18887       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18888       load_full_comp_unit (cu->per_cu, language_minimal);
18889     }
18890
18891   *ref_cu = target_cu;
18892   temp_die.offset = offset;
18893   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18894 }
18895
18896 /* Follow reference attribute ATTR of SRC_DIE.
18897    On entry *REF_CU is the CU of SRC_DIE.
18898    On exit *REF_CU is the CU of the result.  */
18899
18900 static struct die_info *
18901 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18902                 struct dwarf2_cu **ref_cu)
18903 {
18904   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18905   struct dwarf2_cu *cu = *ref_cu;
18906   struct die_info *die;
18907
18908   die = follow_die_offset (offset,
18909                            (attr->form == DW_FORM_GNU_ref_alt
18910                             || cu->per_cu->is_dwz),
18911                            ref_cu);
18912   if (!die)
18913     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18914            "at 0x%x [in module %s]"),
18915            offset.sect_off, src_die->offset.sect_off,
18916            objfile_name (cu->objfile));
18917
18918   return die;
18919 }
18920
18921 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18922    Returned value is intended for DW_OP_call*.  Returned
18923    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18924
18925 struct dwarf2_locexpr_baton
18926 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18927                                struct dwarf2_per_cu_data *per_cu,
18928                                CORE_ADDR (*get_frame_pc) (void *baton),
18929                                void *baton)
18930 {
18931   struct dwarf2_cu *cu;
18932   struct die_info *die;
18933   struct attribute *attr;
18934   struct dwarf2_locexpr_baton retval;
18935
18936   dw2_setup (per_cu->objfile);
18937
18938   if (per_cu->cu == NULL)
18939     load_cu (per_cu);
18940   cu = per_cu->cu;
18941
18942   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18943   if (!die)
18944     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18945            offset.sect_off, objfile_name (per_cu->objfile));
18946
18947   attr = dwarf2_attr (die, DW_AT_location, cu);
18948   if (!attr)
18949     {
18950       /* DWARF: "If there is no such attribute, then there is no effect.".
18951          DATA is ignored if SIZE is 0.  */
18952
18953       retval.data = NULL;
18954       retval.size = 0;
18955     }
18956   else if (attr_form_is_section_offset (attr))
18957     {
18958       struct dwarf2_loclist_baton loclist_baton;
18959       CORE_ADDR pc = (*get_frame_pc) (baton);
18960       size_t size;
18961
18962       fill_in_loclist_baton (cu, &loclist_baton, attr);
18963
18964       retval.data = dwarf2_find_location_expression (&loclist_baton,
18965                                                      &size, pc);
18966       retval.size = size;
18967     }
18968   else
18969     {
18970       if (!attr_form_is_block (attr))
18971         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18972                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18973                offset.sect_off, objfile_name (per_cu->objfile));
18974
18975       retval.data = DW_BLOCK (attr)->data;
18976       retval.size = DW_BLOCK (attr)->size;
18977     }
18978   retval.per_cu = cu->per_cu;
18979
18980   age_cached_comp_units ();
18981
18982   return retval;
18983 }
18984
18985 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18986    offset.  */
18987
18988 struct dwarf2_locexpr_baton
18989 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18990                              struct dwarf2_per_cu_data *per_cu,
18991                              CORE_ADDR (*get_frame_pc) (void *baton),
18992                              void *baton)
18993 {
18994   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18995
18996   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18997 }
18998
18999 /* Write a constant of a given type as target-ordered bytes into
19000    OBSTACK.  */
19001
19002 static const gdb_byte *
19003 write_constant_as_bytes (struct obstack *obstack,
19004                          enum bfd_endian byte_order,
19005                          struct type *type,
19006                          ULONGEST value,
19007                          LONGEST *len)
19008 {
19009   gdb_byte *result;
19010
19011   *len = TYPE_LENGTH (type);
19012   result = obstack_alloc (obstack, *len);
19013   store_unsigned_integer (result, *len, byte_order, value);
19014
19015   return result;
19016 }
19017
19018 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
19019    pointer to the constant bytes and set LEN to the length of the
19020    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
19021    does not have a DW_AT_const_value, return NULL.  */
19022
19023 const gdb_byte *
19024 dwarf2_fetch_constant_bytes (sect_offset offset,
19025                              struct dwarf2_per_cu_data *per_cu,
19026                              struct obstack *obstack,
19027                              LONGEST *len)
19028 {
19029   struct dwarf2_cu *cu;
19030   struct die_info *die;
19031   struct attribute *attr;
19032   const gdb_byte *result = NULL;
19033   struct type *type;
19034   LONGEST value;
19035   enum bfd_endian byte_order;
19036
19037   dw2_setup (per_cu->objfile);
19038
19039   if (per_cu->cu == NULL)
19040     load_cu (per_cu);
19041   cu = per_cu->cu;
19042
19043   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
19044   if (!die)
19045     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19046            offset.sect_off, objfile_name (per_cu->objfile));
19047
19048
19049   attr = dwarf2_attr (die, DW_AT_const_value, cu);
19050   if (attr == NULL)
19051     return NULL;
19052
19053   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
19054                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19055
19056   switch (attr->form)
19057     {
19058     case DW_FORM_addr:
19059     case DW_FORM_GNU_addr_index:
19060       {
19061         gdb_byte *tem;
19062
19063         *len = cu->header.addr_size;
19064         tem = obstack_alloc (obstack, *len);
19065         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
19066         result = tem;
19067       }
19068       break;
19069     case DW_FORM_string:
19070     case DW_FORM_strp:
19071     case DW_FORM_GNU_str_index:
19072     case DW_FORM_GNU_strp_alt:
19073       /* DW_STRING is already allocated on the objfile obstack, point
19074          directly to it.  */
19075       result = (const gdb_byte *) DW_STRING (attr);
19076       *len = strlen (DW_STRING (attr));
19077       break;
19078     case DW_FORM_block1:
19079     case DW_FORM_block2:
19080     case DW_FORM_block4:
19081     case DW_FORM_block:
19082     case DW_FORM_exprloc:
19083       result = DW_BLOCK (attr)->data;
19084       *len = DW_BLOCK (attr)->size;
19085       break;
19086
19087       /* The DW_AT_const_value attributes are supposed to carry the
19088          symbol's value "represented as it would be on the target
19089          architecture."  By the time we get here, it's already been
19090          converted to host endianness, so we just need to sign- or
19091          zero-extend it as appropriate.  */
19092     case DW_FORM_data1:
19093       type = die_type (die, cu);
19094       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
19095       if (result == NULL)
19096         result = write_constant_as_bytes (obstack, byte_order,
19097                                           type, value, len);
19098       break;
19099     case DW_FORM_data2:
19100       type = die_type (die, cu);
19101       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
19102       if (result == NULL)
19103         result = write_constant_as_bytes (obstack, byte_order,
19104                                           type, value, len);
19105       break;
19106     case DW_FORM_data4:
19107       type = die_type (die, cu);
19108       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
19109       if (result == NULL)
19110         result = write_constant_as_bytes (obstack, byte_order,
19111                                           type, value, len);
19112       break;
19113     case DW_FORM_data8:
19114       type = die_type (die, cu);
19115       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
19116       if (result == NULL)
19117         result = write_constant_as_bytes (obstack, byte_order,
19118                                           type, value, len);
19119       break;
19120
19121     case DW_FORM_sdata:
19122       type = die_type (die, cu);
19123       result = write_constant_as_bytes (obstack, byte_order,
19124                                         type, DW_SND (attr), len);
19125       break;
19126
19127     case DW_FORM_udata:
19128       type = die_type (die, cu);
19129       result = write_constant_as_bytes (obstack, byte_order,
19130                                         type, DW_UNSND (attr), len);
19131       break;
19132
19133     default:
19134       complaint (&symfile_complaints,
19135                  _("unsupported const value attribute form: '%s'"),
19136                  dwarf_form_name (attr->form));
19137       break;
19138     }
19139
19140   return result;
19141 }
19142
19143 /* Return the type of the DIE at DIE_OFFSET in the CU named by
19144    PER_CU.  */
19145
19146 struct type *
19147 dwarf2_get_die_type (cu_offset die_offset,
19148                      struct dwarf2_per_cu_data *per_cu)
19149 {
19150   sect_offset die_offset_sect;
19151
19152   dw2_setup (per_cu->objfile);
19153
19154   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
19155   return get_die_type_at_offset (die_offset_sect, per_cu);
19156 }
19157
19158 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
19159    On entry *REF_CU is the CU of SRC_DIE.
19160    On exit *REF_CU is the CU of the result.
19161    Returns NULL if the referenced DIE isn't found.  */
19162
19163 static struct die_info *
19164 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
19165                   struct dwarf2_cu **ref_cu)
19166 {
19167   struct objfile *objfile = (*ref_cu)->objfile;
19168   struct die_info temp_die;
19169   struct dwarf2_cu *sig_cu;
19170   struct die_info *die;
19171
19172   /* While it might be nice to assert sig_type->type == NULL here,
19173      we can get here for DW_AT_imported_declaration where we need
19174      the DIE not the type.  */
19175
19176   /* If necessary, add it to the queue and load its DIEs.  */
19177
19178   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
19179     read_signatured_type (sig_type);
19180
19181   sig_cu = sig_type->per_cu.cu;
19182   gdb_assert (sig_cu != NULL);
19183   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
19184   temp_die.offset = sig_type->type_offset_in_section;
19185   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
19186                              temp_die.offset.sect_off);
19187   if (die)
19188     {
19189       /* For .gdb_index version 7 keep track of included TUs.
19190          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
19191       if (dwarf2_per_objfile->index_table != NULL
19192           && dwarf2_per_objfile->index_table->version <= 7)
19193         {
19194           VEC_safe_push (dwarf2_per_cu_ptr,
19195                          (*ref_cu)->per_cu->imported_symtabs,
19196                          sig_cu->per_cu);
19197         }
19198
19199       *ref_cu = sig_cu;
19200       return die;
19201     }
19202
19203   return NULL;
19204 }
19205
19206 /* Follow signatured type referenced by ATTR in SRC_DIE.
19207    On entry *REF_CU is the CU of SRC_DIE.
19208    On exit *REF_CU is the CU of the result.
19209    The result is the DIE of the type.
19210    If the referenced type cannot be found an error is thrown.  */
19211
19212 static struct die_info *
19213 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
19214                 struct dwarf2_cu **ref_cu)
19215 {
19216   ULONGEST signature = DW_SIGNATURE (attr);
19217   struct signatured_type *sig_type;
19218   struct die_info *die;
19219
19220   gdb_assert (attr->form == DW_FORM_ref_sig8);
19221
19222   sig_type = lookup_signatured_type (*ref_cu, signature);
19223   /* sig_type will be NULL if the signatured type is missing from
19224      the debug info.  */
19225   if (sig_type == NULL)
19226     {
19227       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
19228                " from DIE at 0x%x [in module %s]"),
19229              hex_string (signature), src_die->offset.sect_off,
19230              objfile_name ((*ref_cu)->objfile));
19231     }
19232
19233   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
19234   if (die == NULL)
19235     {
19236       dump_die_for_error (src_die);
19237       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
19238                " from DIE at 0x%x [in module %s]"),
19239              hex_string (signature), src_die->offset.sect_off,
19240              objfile_name ((*ref_cu)->objfile));
19241     }
19242
19243   return die;
19244 }
19245
19246 /* Get the type specified by SIGNATURE referenced in DIE/CU,
19247    reading in and processing the type unit if necessary.  */
19248
19249 static struct type *
19250 get_signatured_type (struct die_info *die, ULONGEST signature,
19251                      struct dwarf2_cu *cu)
19252 {
19253   struct signatured_type *sig_type;
19254   struct dwarf2_cu *type_cu;
19255   struct die_info *type_die;
19256   struct type *type;
19257
19258   sig_type = lookup_signatured_type (cu, signature);
19259   /* sig_type will be NULL if the signatured type is missing from
19260      the debug info.  */
19261   if (sig_type == NULL)
19262     {
19263       complaint (&symfile_complaints,
19264                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
19265                    " from DIE at 0x%x [in module %s]"),
19266                  hex_string (signature), die->offset.sect_off,
19267                  objfile_name (dwarf2_per_objfile->objfile));
19268       return build_error_marker_type (cu, die);
19269     }
19270
19271   /* If we already know the type we're done.  */
19272   if (sig_type->type != NULL)
19273     return sig_type->type;
19274
19275   type_cu = cu;
19276   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
19277   if (type_die != NULL)
19278     {
19279       /* N.B. We need to call get_die_type to ensure only one type for this DIE
19280          is created.  This is important, for example, because for c++ classes
19281          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
19282       type = read_type_die (type_die, type_cu);
19283       if (type == NULL)
19284         {
19285           complaint (&symfile_complaints,
19286                      _("Dwarf Error: Cannot build signatured type %s"
19287                        " referenced from DIE at 0x%x [in module %s]"),
19288                      hex_string (signature), die->offset.sect_off,
19289                      objfile_name (dwarf2_per_objfile->objfile));
19290           type = build_error_marker_type (cu, die);
19291         }
19292     }
19293   else
19294     {
19295       complaint (&symfile_complaints,
19296                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
19297                    " from DIE at 0x%x [in module %s]"),
19298                  hex_string (signature), die->offset.sect_off,
19299                  objfile_name (dwarf2_per_objfile->objfile));
19300       type = build_error_marker_type (cu, die);
19301     }
19302   sig_type->type = type;
19303
19304   return type;
19305 }
19306
19307 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
19308    reading in and processing the type unit if necessary.  */
19309
19310 static struct type *
19311 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
19312                           struct dwarf2_cu *cu) /* ARI: editCase function */
19313 {
19314   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
19315   if (attr_form_is_ref (attr))
19316     {
19317       struct dwarf2_cu *type_cu = cu;
19318       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
19319
19320       return read_type_die (type_die, type_cu);
19321     }
19322   else if (attr->form == DW_FORM_ref_sig8)
19323     {
19324       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
19325     }
19326   else
19327     {
19328       complaint (&symfile_complaints,
19329                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
19330                    " at 0x%x [in module %s]"),
19331                  dwarf_form_name (attr->form), die->offset.sect_off,
19332                  objfile_name (dwarf2_per_objfile->objfile));
19333       return build_error_marker_type (cu, die);
19334     }
19335 }
19336
19337 /* Load the DIEs associated with type unit PER_CU into memory.  */
19338
19339 static void
19340 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
19341 {
19342   struct signatured_type *sig_type;
19343
19344   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
19345   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
19346
19347   /* We have the per_cu, but we need the signatured_type.
19348      Fortunately this is an easy translation.  */
19349   gdb_assert (per_cu->is_debug_types);
19350   sig_type = (struct signatured_type *) per_cu;
19351
19352   gdb_assert (per_cu->cu == NULL);
19353
19354   read_signatured_type (sig_type);
19355
19356   gdb_assert (per_cu->cu != NULL);
19357 }
19358
19359 /* die_reader_func for read_signatured_type.
19360    This is identical to load_full_comp_unit_reader,
19361    but is kept separate for now.  */
19362
19363 static void
19364 read_signatured_type_reader (const struct die_reader_specs *reader,
19365                              const gdb_byte *info_ptr,
19366                              struct die_info *comp_unit_die,
19367                              int has_children,
19368                              void *data)
19369 {
19370   struct dwarf2_cu *cu = reader->cu;
19371
19372   gdb_assert (cu->die_hash == NULL);
19373   cu->die_hash =
19374     htab_create_alloc_ex (cu->header.length / 12,
19375                           die_hash,
19376                           die_eq,
19377                           NULL,
19378                           &cu->comp_unit_obstack,
19379                           hashtab_obstack_allocate,
19380                           dummy_obstack_deallocate);
19381
19382   if (has_children)
19383     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
19384                                                   &info_ptr, comp_unit_die);
19385   cu->dies = comp_unit_die;
19386   /* comp_unit_die is not stored in die_hash, no need.  */
19387
19388   /* We try not to read any attributes in this function, because not
19389      all CUs needed for references have been loaded yet, and symbol
19390      table processing isn't initialized.  But we have to set the CU language,
19391      or we won't be able to build types correctly.
19392      Similarly, if we do not read the producer, we can not apply
19393      producer-specific interpretation.  */
19394   prepare_one_comp_unit (cu, cu->dies, language_minimal);
19395 }
19396
19397 /* Read in a signatured type and build its CU and DIEs.
19398    If the type is a stub for the real type in a DWO file,
19399    read in the real type from the DWO file as well.  */
19400
19401 static void
19402 read_signatured_type (struct signatured_type *sig_type)
19403 {
19404   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
19405
19406   gdb_assert (per_cu->is_debug_types);
19407   gdb_assert (per_cu->cu == NULL);
19408
19409   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
19410                            read_signatured_type_reader, NULL);
19411   sig_type->per_cu.tu_read = 1;
19412 }
19413
19414 /* Decode simple location descriptions.
19415    Given a pointer to a dwarf block that defines a location, compute
19416    the location and return the value.
19417
19418    NOTE drow/2003-11-18: This function is called in two situations
19419    now: for the address of static or global variables (partial symbols
19420    only) and for offsets into structures which are expected to be
19421    (more or less) constant.  The partial symbol case should go away,
19422    and only the constant case should remain.  That will let this
19423    function complain more accurately.  A few special modes are allowed
19424    without complaint for global variables (for instance, global
19425    register values and thread-local values).
19426
19427    A location description containing no operations indicates that the
19428    object is optimized out.  The return value is 0 for that case.
19429    FIXME drow/2003-11-16: No callers check for this case any more; soon all
19430    callers will only want a very basic result and this can become a
19431    complaint.
19432
19433    Note that stack[0] is unused except as a default error return.  */
19434
19435 static CORE_ADDR
19436 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
19437 {
19438   struct objfile *objfile = cu->objfile;
19439   size_t i;
19440   size_t size = blk->size;
19441   const gdb_byte *data = blk->data;
19442   CORE_ADDR stack[64];
19443   int stacki;
19444   unsigned int bytes_read, unsnd;
19445   gdb_byte op;
19446
19447   i = 0;
19448   stacki = 0;
19449   stack[stacki] = 0;
19450   stack[++stacki] = 0;
19451
19452   while (i < size)
19453     {
19454       op = data[i++];
19455       switch (op)
19456         {
19457         case DW_OP_lit0:
19458         case DW_OP_lit1:
19459         case DW_OP_lit2:
19460         case DW_OP_lit3:
19461         case DW_OP_lit4:
19462         case DW_OP_lit5:
19463         case DW_OP_lit6:
19464         case DW_OP_lit7:
19465         case DW_OP_lit8:
19466         case DW_OP_lit9:
19467         case DW_OP_lit10:
19468         case DW_OP_lit11:
19469         case DW_OP_lit12:
19470         case DW_OP_lit13:
19471         case DW_OP_lit14:
19472         case DW_OP_lit15:
19473         case DW_OP_lit16:
19474         case DW_OP_lit17:
19475         case DW_OP_lit18:
19476         case DW_OP_lit19:
19477         case DW_OP_lit20:
19478         case DW_OP_lit21:
19479         case DW_OP_lit22:
19480         case DW_OP_lit23:
19481         case DW_OP_lit24:
19482         case DW_OP_lit25:
19483         case DW_OP_lit26:
19484         case DW_OP_lit27:
19485         case DW_OP_lit28:
19486         case DW_OP_lit29:
19487         case DW_OP_lit30:
19488         case DW_OP_lit31:
19489           stack[++stacki] = op - DW_OP_lit0;
19490           break;
19491
19492         case DW_OP_reg0:
19493         case DW_OP_reg1:
19494         case DW_OP_reg2:
19495         case DW_OP_reg3:
19496         case DW_OP_reg4:
19497         case DW_OP_reg5:
19498         case DW_OP_reg6:
19499         case DW_OP_reg7:
19500         case DW_OP_reg8:
19501         case DW_OP_reg9:
19502         case DW_OP_reg10:
19503         case DW_OP_reg11:
19504         case DW_OP_reg12:
19505         case DW_OP_reg13:
19506         case DW_OP_reg14:
19507         case DW_OP_reg15:
19508         case DW_OP_reg16:
19509         case DW_OP_reg17:
19510         case DW_OP_reg18:
19511         case DW_OP_reg19:
19512         case DW_OP_reg20:
19513         case DW_OP_reg21:
19514         case DW_OP_reg22:
19515         case DW_OP_reg23:
19516         case DW_OP_reg24:
19517         case DW_OP_reg25:
19518         case DW_OP_reg26:
19519         case DW_OP_reg27:
19520         case DW_OP_reg28:
19521         case DW_OP_reg29:
19522         case DW_OP_reg30:
19523         case DW_OP_reg31:
19524           stack[++stacki] = op - DW_OP_reg0;
19525           if (i < size)
19526             dwarf2_complex_location_expr_complaint ();
19527           break;
19528
19529         case DW_OP_regx:
19530           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
19531           i += bytes_read;
19532           stack[++stacki] = unsnd;
19533           if (i < size)
19534             dwarf2_complex_location_expr_complaint ();
19535           break;
19536
19537         case DW_OP_addr:
19538           stack[++stacki] = read_address (objfile->obfd, &data[i],
19539                                           cu, &bytes_read);
19540           i += bytes_read;
19541           break;
19542
19543         case DW_OP_const1u:
19544           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
19545           i += 1;
19546           break;
19547
19548         case DW_OP_const1s:
19549           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
19550           i += 1;
19551           break;
19552
19553         case DW_OP_const2u:
19554           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
19555           i += 2;
19556           break;
19557
19558         case DW_OP_const2s:
19559           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
19560           i += 2;
19561           break;
19562
19563         case DW_OP_const4u:
19564           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
19565           i += 4;
19566           break;
19567
19568         case DW_OP_const4s:
19569           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
19570           i += 4;
19571           break;
19572
19573         case DW_OP_const8u:
19574           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
19575           i += 8;
19576           break;
19577
19578         case DW_OP_constu:
19579           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
19580                                                   &bytes_read);
19581           i += bytes_read;
19582           break;
19583
19584         case DW_OP_consts:
19585           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
19586           i += bytes_read;
19587           break;
19588
19589         case DW_OP_dup:
19590           stack[stacki + 1] = stack[stacki];
19591           stacki++;
19592           break;
19593
19594         case DW_OP_plus:
19595           stack[stacki - 1] += stack[stacki];
19596           stacki--;
19597           break;
19598
19599         case DW_OP_plus_uconst:
19600           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
19601                                                  &bytes_read);
19602           i += bytes_read;
19603           break;
19604
19605         case DW_OP_minus:
19606           stack[stacki - 1] -= stack[stacki];
19607           stacki--;
19608           break;
19609
19610         case DW_OP_deref:
19611           /* If we're not the last op, then we definitely can't encode
19612              this using GDB's address_class enum.  This is valid for partial
19613              global symbols, although the variable's address will be bogus
19614              in the psymtab.  */
19615           if (i < size)
19616             dwarf2_complex_location_expr_complaint ();
19617           break;
19618
19619         case DW_OP_GNU_push_tls_address:
19620           /* The top of the stack has the offset from the beginning
19621              of the thread control block at which the variable is located.  */
19622           /* Nothing should follow this operator, so the top of stack would
19623              be returned.  */
19624           /* This is valid for partial global symbols, but the variable's
19625              address will be bogus in the psymtab.  Make it always at least
19626              non-zero to not look as a variable garbage collected by linker
19627              which have DW_OP_addr 0.  */
19628           if (i < size)
19629             dwarf2_complex_location_expr_complaint ();
19630           stack[stacki]++;
19631           break;
19632
19633         case DW_OP_GNU_uninit:
19634           break;
19635
19636         case DW_OP_GNU_addr_index:
19637         case DW_OP_GNU_const_index:
19638           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
19639                                                          &bytes_read);
19640           i += bytes_read;
19641           break;
19642
19643         default:
19644           {
19645             const char *name = get_DW_OP_name (op);
19646
19647             if (name)
19648               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
19649                          name);
19650             else
19651               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
19652                          op);
19653           }
19654
19655           return (stack[stacki]);
19656         }
19657
19658       /* Enforce maximum stack depth of SIZE-1 to avoid writing
19659          outside of the allocated space.  Also enforce minimum>0.  */
19660       if (stacki >= ARRAY_SIZE (stack) - 1)
19661         {
19662           complaint (&symfile_complaints,
19663                      _("location description stack overflow"));
19664           return 0;
19665         }
19666
19667       if (stacki <= 0)
19668         {
19669           complaint (&symfile_complaints,
19670                      _("location description stack underflow"));
19671           return 0;
19672         }
19673     }
19674   return (stack[stacki]);
19675 }
19676
19677 /* memory allocation interface */
19678
19679 static struct dwarf_block *
19680 dwarf_alloc_block (struct dwarf2_cu *cu)
19681 {
19682   struct dwarf_block *blk;
19683
19684   blk = (struct dwarf_block *)
19685     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
19686   return (blk);
19687 }
19688
19689 static struct die_info *
19690 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
19691 {
19692   struct die_info *die;
19693   size_t size = sizeof (struct die_info);
19694
19695   if (num_attrs > 1)
19696     size += (num_attrs - 1) * sizeof (struct attribute);
19697
19698   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
19699   memset (die, 0, sizeof (struct die_info));
19700   return (die);
19701 }
19702
19703 \f
19704 /* Macro support.  */
19705
19706 /* Return file name relative to the compilation directory of file number I in
19707    *LH's file name table.  The result is allocated using xmalloc; the caller is
19708    responsible for freeing it.  */
19709
19710 static char *
19711 file_file_name (int file, struct line_header *lh)
19712 {
19713   /* Is the file number a valid index into the line header's file name
19714      table?  Remember that file numbers start with one, not zero.  */
19715   if (1 <= file && file <= lh->num_file_names)
19716     {
19717       struct file_entry *fe = &lh->file_names[file - 1];
19718
19719       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
19720         return xstrdup (fe->name);
19721       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
19722                      fe->name, NULL);
19723     }
19724   else
19725     {
19726       /* The compiler produced a bogus file number.  We can at least
19727          record the macro definitions made in the file, even if we
19728          won't be able to find the file by name.  */
19729       char fake_name[80];
19730
19731       xsnprintf (fake_name, sizeof (fake_name),
19732                  "<bad macro file number %d>", file);
19733
19734       complaint (&symfile_complaints,
19735                  _("bad file number in macro information (%d)"),
19736                  file);
19737
19738       return xstrdup (fake_name);
19739     }
19740 }
19741
19742 /* Return the full name of file number I in *LH's file name table.
19743    Use COMP_DIR as the name of the current directory of the
19744    compilation.  The result is allocated using xmalloc; the caller is
19745    responsible for freeing it.  */
19746 static char *
19747 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19748 {
19749   /* Is the file number a valid index into the line header's file name
19750      table?  Remember that file numbers start with one, not zero.  */
19751   if (1 <= file && file <= lh->num_file_names)
19752     {
19753       char *relative = file_file_name (file, lh);
19754
19755       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19756         return relative;
19757       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19758     }
19759   else
19760     return file_file_name (file, lh);
19761 }
19762
19763
19764 static struct macro_source_file *
19765 macro_start_file (int file, int line,
19766                   struct macro_source_file *current_file,
19767                   const char *comp_dir,
19768                   struct line_header *lh, struct objfile *objfile)
19769 {
19770   /* File name relative to the compilation directory of this source file.  */
19771   char *file_name = file_file_name (file, lh);
19772
19773   if (! current_file)
19774     {
19775       /* Note: We don't create a macro table for this compilation unit
19776          at all until we actually get a filename.  */
19777       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19778
19779       /* If we have no current file, then this must be the start_file
19780          directive for the compilation unit's main source file.  */
19781       current_file = macro_set_main (macro_table, file_name);
19782       macro_define_special (macro_table);
19783     }
19784   else
19785     current_file = macro_include (current_file, line, file_name);
19786
19787   xfree (file_name);
19788
19789   return current_file;
19790 }
19791
19792
19793 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19794    followed by a null byte.  */
19795 static char *
19796 copy_string (const char *buf, int len)
19797 {
19798   char *s = xmalloc (len + 1);
19799
19800   memcpy (s, buf, len);
19801   s[len] = '\0';
19802   return s;
19803 }
19804
19805
19806 static const char *
19807 consume_improper_spaces (const char *p, const char *body)
19808 {
19809   if (*p == ' ')
19810     {
19811       complaint (&symfile_complaints,
19812                  _("macro definition contains spaces "
19813                    "in formal argument list:\n`%s'"),
19814                  body);
19815
19816       while (*p == ' ')
19817         p++;
19818     }
19819
19820   return p;
19821 }
19822
19823
19824 static void
19825 parse_macro_definition (struct macro_source_file *file, int line,
19826                         const char *body)
19827 {
19828   const char *p;
19829
19830   /* The body string takes one of two forms.  For object-like macro
19831      definitions, it should be:
19832
19833         <macro name> " " <definition>
19834
19835      For function-like macro definitions, it should be:
19836
19837         <macro name> "() " <definition>
19838      or
19839         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19840
19841      Spaces may appear only where explicitly indicated, and in the
19842      <definition>.
19843
19844      The Dwarf 2 spec says that an object-like macro's name is always
19845      followed by a space, but versions of GCC around March 2002 omit
19846      the space when the macro's definition is the empty string.
19847
19848      The Dwarf 2 spec says that there should be no spaces between the
19849      formal arguments in a function-like macro's formal argument list,
19850      but versions of GCC around March 2002 include spaces after the
19851      commas.  */
19852
19853
19854   /* Find the extent of the macro name.  The macro name is terminated
19855      by either a space or null character (for an object-like macro) or
19856      an opening paren (for a function-like macro).  */
19857   for (p = body; *p; p++)
19858     if (*p == ' ' || *p == '(')
19859       break;
19860
19861   if (*p == ' ' || *p == '\0')
19862     {
19863       /* It's an object-like macro.  */
19864       int name_len = p - body;
19865       char *name = copy_string (body, name_len);
19866       const char *replacement;
19867
19868       if (*p == ' ')
19869         replacement = body + name_len + 1;
19870       else
19871         {
19872           dwarf2_macro_malformed_definition_complaint (body);
19873           replacement = body + name_len;
19874         }
19875
19876       macro_define_object (file, line, name, replacement);
19877
19878       xfree (name);
19879     }
19880   else if (*p == '(')
19881     {
19882       /* It's a function-like macro.  */
19883       char *name = copy_string (body, p - body);
19884       int argc = 0;
19885       int argv_size = 1;
19886       char **argv = xmalloc (argv_size * sizeof (*argv));
19887
19888       p++;
19889
19890       p = consume_improper_spaces (p, body);
19891
19892       /* Parse the formal argument list.  */
19893       while (*p && *p != ')')
19894         {
19895           /* Find the extent of the current argument name.  */
19896           const char *arg_start = p;
19897
19898           while (*p && *p != ',' && *p != ')' && *p != ' ')
19899             p++;
19900
19901           if (! *p || p == arg_start)
19902             dwarf2_macro_malformed_definition_complaint (body);
19903           else
19904             {
19905               /* Make sure argv has room for the new argument.  */
19906               if (argc >= argv_size)
19907                 {
19908                   argv_size *= 2;
19909                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19910                 }
19911
19912               argv[argc++] = copy_string (arg_start, p - arg_start);
19913             }
19914
19915           p = consume_improper_spaces (p, body);
19916
19917           /* Consume the comma, if present.  */
19918           if (*p == ',')
19919             {
19920               p++;
19921
19922               p = consume_improper_spaces (p, body);
19923             }
19924         }
19925
19926       if (*p == ')')
19927         {
19928           p++;
19929
19930           if (*p == ' ')
19931             /* Perfectly formed definition, no complaints.  */
19932             macro_define_function (file, line, name,
19933                                    argc, (const char **) argv,
19934                                    p + 1);
19935           else if (*p == '\0')
19936             {
19937               /* Complain, but do define it.  */
19938               dwarf2_macro_malformed_definition_complaint (body);
19939               macro_define_function (file, line, name,
19940                                      argc, (const char **) argv,
19941                                      p);
19942             }
19943           else
19944             /* Just complain.  */
19945             dwarf2_macro_malformed_definition_complaint (body);
19946         }
19947       else
19948         /* Just complain.  */
19949         dwarf2_macro_malformed_definition_complaint (body);
19950
19951       xfree (name);
19952       {
19953         int i;
19954
19955         for (i = 0; i < argc; i++)
19956           xfree (argv[i]);
19957       }
19958       xfree (argv);
19959     }
19960   else
19961     dwarf2_macro_malformed_definition_complaint (body);
19962 }
19963
19964 /* Skip some bytes from BYTES according to the form given in FORM.
19965    Returns the new pointer.  */
19966
19967 static const gdb_byte *
19968 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19969                  enum dwarf_form form,
19970                  unsigned int offset_size,
19971                  struct dwarf2_section_info *section)
19972 {
19973   unsigned int bytes_read;
19974
19975   switch (form)
19976     {
19977     case DW_FORM_data1:
19978     case DW_FORM_flag:
19979       ++bytes;
19980       break;
19981
19982     case DW_FORM_data2:
19983       bytes += 2;
19984       break;
19985
19986     case DW_FORM_data4:
19987       bytes += 4;
19988       break;
19989
19990     case DW_FORM_data8:
19991       bytes += 8;
19992       break;
19993
19994     case DW_FORM_string:
19995       read_direct_string (abfd, bytes, &bytes_read);
19996       bytes += bytes_read;
19997       break;
19998
19999     case DW_FORM_sec_offset:
20000     case DW_FORM_strp:
20001     case DW_FORM_GNU_strp_alt:
20002       bytes += offset_size;
20003       break;
20004
20005     case DW_FORM_block:
20006       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
20007       bytes += bytes_read;
20008       break;
20009
20010     case DW_FORM_block1:
20011       bytes += 1 + read_1_byte (abfd, bytes);
20012       break;
20013     case DW_FORM_block2:
20014       bytes += 2 + read_2_bytes (abfd, bytes);
20015       break;
20016     case DW_FORM_block4:
20017       bytes += 4 + read_4_bytes (abfd, bytes);
20018       break;
20019
20020     case DW_FORM_sdata:
20021     case DW_FORM_udata:
20022     case DW_FORM_GNU_addr_index:
20023     case DW_FORM_GNU_str_index:
20024       bytes = gdb_skip_leb128 (bytes, buffer_end);
20025       if (bytes == NULL)
20026         {
20027           dwarf2_section_buffer_overflow_complaint (section);
20028           return NULL;
20029         }
20030       break;
20031
20032     default:
20033       {
20034       complain:
20035         complaint (&symfile_complaints,
20036                    _("invalid form 0x%x in `%s'"),
20037                    form, get_section_name (section));
20038         return NULL;
20039       }
20040     }
20041
20042   return bytes;
20043 }
20044
20045 /* A helper for dwarf_decode_macros that handles skipping an unknown
20046    opcode.  Returns an updated pointer to the macro data buffer; or,
20047    on error, issues a complaint and returns NULL.  */
20048
20049 static const gdb_byte *
20050 skip_unknown_opcode (unsigned int opcode,
20051                      const gdb_byte **opcode_definitions,
20052                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20053                      bfd *abfd,
20054                      unsigned int offset_size,
20055                      struct dwarf2_section_info *section)
20056 {
20057   unsigned int bytes_read, i;
20058   unsigned long arg;
20059   const gdb_byte *defn;
20060
20061   if (opcode_definitions[opcode] == NULL)
20062     {
20063       complaint (&symfile_complaints,
20064                  _("unrecognized DW_MACFINO opcode 0x%x"),
20065                  opcode);
20066       return NULL;
20067     }
20068
20069   defn = opcode_definitions[opcode];
20070   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
20071   defn += bytes_read;
20072
20073   for (i = 0; i < arg; ++i)
20074     {
20075       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
20076                                  section);
20077       if (mac_ptr == NULL)
20078         {
20079           /* skip_form_bytes already issued the complaint.  */
20080           return NULL;
20081         }
20082     }
20083
20084   return mac_ptr;
20085 }
20086
20087 /* A helper function which parses the header of a macro section.
20088    If the macro section is the extended (for now called "GNU") type,
20089    then this updates *OFFSET_SIZE.  Returns a pointer to just after
20090    the header, or issues a complaint and returns NULL on error.  */
20091
20092 static const gdb_byte *
20093 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
20094                           bfd *abfd,
20095                           const gdb_byte *mac_ptr,
20096                           unsigned int *offset_size,
20097                           int section_is_gnu)
20098 {
20099   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
20100
20101   if (section_is_gnu)
20102     {
20103       unsigned int version, flags;
20104
20105       version = read_2_bytes (abfd, mac_ptr);
20106       if (version != 4)
20107         {
20108           complaint (&symfile_complaints,
20109                      _("unrecognized version `%d' in .debug_macro section"),
20110                      version);
20111           return NULL;
20112         }
20113       mac_ptr += 2;
20114
20115       flags = read_1_byte (abfd, mac_ptr);
20116       ++mac_ptr;
20117       *offset_size = (flags & 1) ? 8 : 4;
20118
20119       if ((flags & 2) != 0)
20120         /* We don't need the line table offset.  */
20121         mac_ptr += *offset_size;
20122
20123       /* Vendor opcode descriptions.  */
20124       if ((flags & 4) != 0)
20125         {
20126           unsigned int i, count;
20127
20128           count = read_1_byte (abfd, mac_ptr);
20129           ++mac_ptr;
20130           for (i = 0; i < count; ++i)
20131             {
20132               unsigned int opcode, bytes_read;
20133               unsigned long arg;
20134
20135               opcode = read_1_byte (abfd, mac_ptr);
20136               ++mac_ptr;
20137               opcode_definitions[opcode] = mac_ptr;
20138               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20139               mac_ptr += bytes_read;
20140               mac_ptr += arg;
20141             }
20142         }
20143     }
20144
20145   return mac_ptr;
20146 }
20147
20148 /* A helper for dwarf_decode_macros that handles the GNU extensions,
20149    including DW_MACRO_GNU_transparent_include.  */
20150
20151 static void
20152 dwarf_decode_macro_bytes (bfd *abfd,
20153                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20154                           struct macro_source_file *current_file,
20155                           struct line_header *lh, const char *comp_dir,
20156                           struct dwarf2_section_info *section,
20157                           int section_is_gnu, int section_is_dwz,
20158                           unsigned int offset_size,
20159                           struct objfile *objfile,
20160                           htab_t include_hash)
20161 {
20162   enum dwarf_macro_record_type macinfo_type;
20163   int at_commandline;
20164   const gdb_byte *opcode_definitions[256];
20165
20166   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20167                                       &offset_size, section_is_gnu);
20168   if (mac_ptr == NULL)
20169     {
20170       /* We already issued a complaint.  */
20171       return;
20172     }
20173
20174   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
20175      GDB is still reading the definitions from command line.  First
20176      DW_MACINFO_start_file will need to be ignored as it was already executed
20177      to create CURRENT_FILE for the main source holding also the command line
20178      definitions.  On first met DW_MACINFO_start_file this flag is reset to
20179      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
20180
20181   at_commandline = 1;
20182
20183   do
20184     {
20185       /* Do we at least have room for a macinfo type byte?  */
20186       if (mac_ptr >= mac_end)
20187         {
20188           dwarf2_section_buffer_overflow_complaint (section);
20189           break;
20190         }
20191
20192       macinfo_type = read_1_byte (abfd, mac_ptr);
20193       mac_ptr++;
20194
20195       /* Note that we rely on the fact that the corresponding GNU and
20196          DWARF constants are the same.  */
20197       switch (macinfo_type)
20198         {
20199           /* A zero macinfo type indicates the end of the macro
20200              information.  */
20201         case 0:
20202           break;
20203
20204         case DW_MACRO_GNU_define:
20205         case DW_MACRO_GNU_undef:
20206         case DW_MACRO_GNU_define_indirect:
20207         case DW_MACRO_GNU_undef_indirect:
20208         case DW_MACRO_GNU_define_indirect_alt:
20209         case DW_MACRO_GNU_undef_indirect_alt:
20210           {
20211             unsigned int bytes_read;
20212             int line;
20213             const char *body;
20214             int is_define;
20215
20216             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20217             mac_ptr += bytes_read;
20218
20219             if (macinfo_type == DW_MACRO_GNU_define
20220                 || macinfo_type == DW_MACRO_GNU_undef)
20221               {
20222                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
20223                 mac_ptr += bytes_read;
20224               }
20225             else
20226               {
20227                 LONGEST str_offset;
20228
20229                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
20230                 mac_ptr += offset_size;
20231
20232                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
20233                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
20234                     || section_is_dwz)
20235                   {
20236                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
20237
20238                     body = read_indirect_string_from_dwz (dwz, str_offset);
20239                   }
20240                 else
20241                   body = read_indirect_string_at_offset (abfd, str_offset);
20242               }
20243
20244             is_define = (macinfo_type == DW_MACRO_GNU_define
20245                          || macinfo_type == DW_MACRO_GNU_define_indirect
20246                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
20247             if (! current_file)
20248               {
20249                 /* DWARF violation as no main source is present.  */
20250                 complaint (&symfile_complaints,
20251                            _("debug info with no main source gives macro %s "
20252                              "on line %d: %s"),
20253                            is_define ? _("definition") : _("undefinition"),
20254                            line, body);
20255                 break;
20256               }
20257             if ((line == 0 && !at_commandline)
20258                 || (line != 0 && at_commandline))
20259               complaint (&symfile_complaints,
20260                          _("debug info gives %s macro %s with %s line %d: %s"),
20261                          at_commandline ? _("command-line") : _("in-file"),
20262                          is_define ? _("definition") : _("undefinition"),
20263                          line == 0 ? _("zero") : _("non-zero"), line, body);
20264
20265             if (is_define)
20266               parse_macro_definition (current_file, line, body);
20267             else
20268               {
20269                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
20270                             || macinfo_type == DW_MACRO_GNU_undef_indirect
20271                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
20272                 macro_undef (current_file, line, body);
20273               }
20274           }
20275           break;
20276
20277         case DW_MACRO_GNU_start_file:
20278           {
20279             unsigned int bytes_read;
20280             int line, file;
20281
20282             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20283             mac_ptr += bytes_read;
20284             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20285             mac_ptr += bytes_read;
20286
20287             if ((line == 0 && !at_commandline)
20288                 || (line != 0 && at_commandline))
20289               complaint (&symfile_complaints,
20290                          _("debug info gives source %d included "
20291                            "from %s at %s line %d"),
20292                          file, at_commandline ? _("command-line") : _("file"),
20293                          line == 0 ? _("zero") : _("non-zero"), line);
20294
20295             if (at_commandline)
20296               {
20297                 /* This DW_MACRO_GNU_start_file was executed in the
20298                    pass one.  */
20299                 at_commandline = 0;
20300               }
20301             else
20302               current_file = macro_start_file (file, line,
20303                                                current_file, comp_dir,
20304                                                lh, objfile);
20305           }
20306           break;
20307
20308         case DW_MACRO_GNU_end_file:
20309           if (! current_file)
20310             complaint (&symfile_complaints,
20311                        _("macro debug info has an unmatched "
20312                          "`close_file' directive"));
20313           else
20314             {
20315               current_file = current_file->included_by;
20316               if (! current_file)
20317                 {
20318                   enum dwarf_macro_record_type next_type;
20319
20320                   /* GCC circa March 2002 doesn't produce the zero
20321                      type byte marking the end of the compilation
20322                      unit.  Complain if it's not there, but exit no
20323                      matter what.  */
20324
20325                   /* Do we at least have room for a macinfo type byte?  */
20326                   if (mac_ptr >= mac_end)
20327                     {
20328                       dwarf2_section_buffer_overflow_complaint (section);
20329                       return;
20330                     }
20331
20332                   /* We don't increment mac_ptr here, so this is just
20333                      a look-ahead.  */
20334                   next_type = read_1_byte (abfd, mac_ptr);
20335                   if (next_type != 0)
20336                     complaint (&symfile_complaints,
20337                                _("no terminating 0-type entry for "
20338                                  "macros in `.debug_macinfo' section"));
20339
20340                   return;
20341                 }
20342             }
20343           break;
20344
20345         case DW_MACRO_GNU_transparent_include:
20346         case DW_MACRO_GNU_transparent_include_alt:
20347           {
20348             LONGEST offset;
20349             void **slot;
20350             bfd *include_bfd = abfd;
20351             struct dwarf2_section_info *include_section = section;
20352             struct dwarf2_section_info alt_section;
20353             const gdb_byte *include_mac_end = mac_end;
20354             int is_dwz = section_is_dwz;
20355             const gdb_byte *new_mac_ptr;
20356
20357             offset = read_offset_1 (abfd, mac_ptr, offset_size);
20358             mac_ptr += offset_size;
20359
20360             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
20361               {
20362                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
20363
20364                 dwarf2_read_section (dwarf2_per_objfile->objfile,
20365                                      &dwz->macro);
20366
20367                 include_section = &dwz->macro;
20368                 include_bfd = get_section_bfd_owner (include_section);
20369                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
20370                 is_dwz = 1;
20371               }
20372
20373             new_mac_ptr = include_section->buffer + offset;
20374             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
20375
20376             if (*slot != NULL)
20377               {
20378                 /* This has actually happened; see
20379                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
20380                 complaint (&symfile_complaints,
20381                            _("recursive DW_MACRO_GNU_transparent_include in "
20382                              ".debug_macro section"));
20383               }
20384             else
20385               {
20386                 *slot = (void *) new_mac_ptr;
20387
20388                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
20389                                           include_mac_end, current_file,
20390                                           lh, comp_dir,
20391                                           section, section_is_gnu, is_dwz,
20392                                           offset_size, objfile, include_hash);
20393
20394                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
20395               }
20396           }
20397           break;
20398
20399         case DW_MACINFO_vendor_ext:
20400           if (!section_is_gnu)
20401             {
20402               unsigned int bytes_read;
20403               int constant;
20404
20405               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20406               mac_ptr += bytes_read;
20407               read_direct_string (abfd, mac_ptr, &bytes_read);
20408               mac_ptr += bytes_read;
20409
20410               /* We don't recognize any vendor extensions.  */
20411               break;
20412             }
20413           /* FALLTHROUGH */
20414
20415         default:
20416           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20417                                          mac_ptr, mac_end, abfd, offset_size,
20418                                          section);
20419           if (mac_ptr == NULL)
20420             return;
20421           break;
20422         }
20423     } while (macinfo_type != 0);
20424 }
20425
20426 static void
20427 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
20428                      const char *comp_dir, int section_is_gnu)
20429 {
20430   struct objfile *objfile = dwarf2_per_objfile->objfile;
20431   struct line_header *lh = cu->line_header;
20432   bfd *abfd;
20433   const gdb_byte *mac_ptr, *mac_end;
20434   struct macro_source_file *current_file = 0;
20435   enum dwarf_macro_record_type macinfo_type;
20436   unsigned int offset_size = cu->header.offset_size;
20437   const gdb_byte *opcode_definitions[256];
20438   struct cleanup *cleanup;
20439   htab_t include_hash;
20440   void **slot;
20441   struct dwarf2_section_info *section;
20442   const char *section_name;
20443
20444   if (cu->dwo_unit != NULL)
20445     {
20446       if (section_is_gnu)
20447         {
20448           section = &cu->dwo_unit->dwo_file->sections.macro;
20449           section_name = ".debug_macro.dwo";
20450         }
20451       else
20452         {
20453           section = &cu->dwo_unit->dwo_file->sections.macinfo;
20454           section_name = ".debug_macinfo.dwo";
20455         }
20456     }
20457   else
20458     {
20459       if (section_is_gnu)
20460         {
20461           section = &dwarf2_per_objfile->macro;
20462           section_name = ".debug_macro";
20463         }
20464       else
20465         {
20466           section = &dwarf2_per_objfile->macinfo;
20467           section_name = ".debug_macinfo";
20468         }
20469     }
20470
20471   dwarf2_read_section (objfile, section);
20472   if (section->buffer == NULL)
20473     {
20474       complaint (&symfile_complaints, _("missing %s section"), section_name);
20475       return;
20476     }
20477   abfd = get_section_bfd_owner (section);
20478
20479   /* First pass: Find the name of the base filename.
20480      This filename is needed in order to process all macros whose definition
20481      (or undefinition) comes from the command line.  These macros are defined
20482      before the first DW_MACINFO_start_file entry, and yet still need to be
20483      associated to the base file.
20484
20485      To determine the base file name, we scan the macro definitions until we
20486      reach the first DW_MACINFO_start_file entry.  We then initialize
20487      CURRENT_FILE accordingly so that any macro definition found before the
20488      first DW_MACINFO_start_file can still be associated to the base file.  */
20489
20490   mac_ptr = section->buffer + offset;
20491   mac_end = section->buffer + section->size;
20492
20493   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20494                                       &offset_size, section_is_gnu);
20495   if (mac_ptr == NULL)
20496     {
20497       /* We already issued a complaint.  */
20498       return;
20499     }
20500
20501   do
20502     {
20503       /* Do we at least have room for a macinfo type byte?  */
20504       if (mac_ptr >= mac_end)
20505         {
20506           /* Complaint is printed during the second pass as GDB will probably
20507              stop the first pass earlier upon finding
20508              DW_MACINFO_start_file.  */
20509           break;
20510         }
20511
20512       macinfo_type = read_1_byte (abfd, mac_ptr);
20513       mac_ptr++;
20514
20515       /* Note that we rely on the fact that the corresponding GNU and
20516          DWARF constants are the same.  */
20517       switch (macinfo_type)
20518         {
20519           /* A zero macinfo type indicates the end of the macro
20520              information.  */
20521         case 0:
20522           break;
20523
20524         case DW_MACRO_GNU_define:
20525         case DW_MACRO_GNU_undef:
20526           /* Only skip the data by MAC_PTR.  */
20527           {
20528             unsigned int bytes_read;
20529
20530             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20531             mac_ptr += bytes_read;
20532             read_direct_string (abfd, mac_ptr, &bytes_read);
20533             mac_ptr += bytes_read;
20534           }
20535           break;
20536
20537         case DW_MACRO_GNU_start_file:
20538           {
20539             unsigned int bytes_read;
20540             int line, file;
20541
20542             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20543             mac_ptr += bytes_read;
20544             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20545             mac_ptr += bytes_read;
20546
20547             current_file = macro_start_file (file, line, current_file,
20548                                              comp_dir, lh, objfile);
20549           }
20550           break;
20551
20552         case DW_MACRO_GNU_end_file:
20553           /* No data to skip by MAC_PTR.  */
20554           break;
20555
20556         case DW_MACRO_GNU_define_indirect:
20557         case DW_MACRO_GNU_undef_indirect:
20558         case DW_MACRO_GNU_define_indirect_alt:
20559         case DW_MACRO_GNU_undef_indirect_alt:
20560           {
20561             unsigned int bytes_read;
20562
20563             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20564             mac_ptr += bytes_read;
20565             mac_ptr += offset_size;
20566           }
20567           break;
20568
20569         case DW_MACRO_GNU_transparent_include:
20570         case DW_MACRO_GNU_transparent_include_alt:
20571           /* Note that, according to the spec, a transparent include
20572              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
20573              skip this opcode.  */
20574           mac_ptr += offset_size;
20575           break;
20576
20577         case DW_MACINFO_vendor_ext:
20578           /* Only skip the data by MAC_PTR.  */
20579           if (!section_is_gnu)
20580             {
20581               unsigned int bytes_read;
20582
20583               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20584               mac_ptr += bytes_read;
20585               read_direct_string (abfd, mac_ptr, &bytes_read);
20586               mac_ptr += bytes_read;
20587             }
20588           /* FALLTHROUGH */
20589
20590         default:
20591           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20592                                          mac_ptr, mac_end, abfd, offset_size,
20593                                          section);
20594           if (mac_ptr == NULL)
20595             return;
20596           break;
20597         }
20598     } while (macinfo_type != 0 && current_file == NULL);
20599
20600   /* Second pass: Process all entries.
20601
20602      Use the AT_COMMAND_LINE flag to determine whether we are still processing
20603      command-line macro definitions/undefinitions.  This flag is unset when we
20604      reach the first DW_MACINFO_start_file entry.  */
20605
20606   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
20607                                     NULL, xcalloc, xfree);
20608   cleanup = make_cleanup_htab_delete (include_hash);
20609   mac_ptr = section->buffer + offset;
20610   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
20611   *slot = (void *) mac_ptr;
20612   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
20613                             current_file, lh, comp_dir, section,
20614                             section_is_gnu, 0,
20615                             offset_size, objfile, include_hash);
20616   do_cleanups (cleanup);
20617 }
20618
20619 /* Check if the attribute's form is a DW_FORM_block*
20620    if so return true else false.  */
20621
20622 static int
20623 attr_form_is_block (const struct attribute *attr)
20624 {
20625   return (attr == NULL ? 0 :
20626       attr->form == DW_FORM_block1
20627       || attr->form == DW_FORM_block2
20628       || attr->form == DW_FORM_block4
20629       || attr->form == DW_FORM_block
20630       || attr->form == DW_FORM_exprloc);
20631 }
20632
20633 /* Return non-zero if ATTR's value is a section offset --- classes
20634    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
20635    You may use DW_UNSND (attr) to retrieve such offsets.
20636
20637    Section 7.5.4, "Attribute Encodings", explains that no attribute
20638    may have a value that belongs to more than one of these classes; it
20639    would be ambiguous if we did, because we use the same forms for all
20640    of them.  */
20641
20642 static int
20643 attr_form_is_section_offset (const struct attribute *attr)
20644 {
20645   return (attr->form == DW_FORM_data4
20646           || attr->form == DW_FORM_data8
20647           || attr->form == DW_FORM_sec_offset);
20648 }
20649
20650 /* Return non-zero if ATTR's value falls in the 'constant' class, or
20651    zero otherwise.  When this function returns true, you can apply
20652    dwarf2_get_attr_constant_value to it.
20653
20654    However, note that for some attributes you must check
20655    attr_form_is_section_offset before using this test.  DW_FORM_data4
20656    and DW_FORM_data8 are members of both the constant class, and of
20657    the classes that contain offsets into other debug sections
20658    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
20659    that, if an attribute's can be either a constant or one of the
20660    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
20661    taken as section offsets, not constants.  */
20662
20663 static int
20664 attr_form_is_constant (const struct attribute *attr)
20665 {
20666   switch (attr->form)
20667     {
20668     case DW_FORM_sdata:
20669     case DW_FORM_udata:
20670     case DW_FORM_data1:
20671     case DW_FORM_data2:
20672     case DW_FORM_data4:
20673     case DW_FORM_data8:
20674       return 1;
20675     default:
20676       return 0;
20677     }
20678 }
20679
20680
20681 /* DW_ADDR is always stored already as sect_offset; despite for the forms
20682    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
20683
20684 static int
20685 attr_form_is_ref (const struct attribute *attr)
20686 {
20687   switch (attr->form)
20688     {
20689     case DW_FORM_ref_addr:
20690     case DW_FORM_ref1:
20691     case DW_FORM_ref2:
20692     case DW_FORM_ref4:
20693     case DW_FORM_ref8:
20694     case DW_FORM_ref_udata:
20695     case DW_FORM_GNU_ref_alt:
20696       return 1;
20697     default:
20698       return 0;
20699     }
20700 }
20701
20702 /* Return the .debug_loc section to use for CU.
20703    For DWO files use .debug_loc.dwo.  */
20704
20705 static struct dwarf2_section_info *
20706 cu_debug_loc_section (struct dwarf2_cu *cu)
20707 {
20708   if (cu->dwo_unit)
20709     return &cu->dwo_unit->dwo_file->sections.loc;
20710   return &dwarf2_per_objfile->loc;
20711 }
20712
20713 /* A helper function that fills in a dwarf2_loclist_baton.  */
20714
20715 static void
20716 fill_in_loclist_baton (struct dwarf2_cu *cu,
20717                        struct dwarf2_loclist_baton *baton,
20718                        const struct attribute *attr)
20719 {
20720   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20721
20722   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20723
20724   baton->per_cu = cu->per_cu;
20725   gdb_assert (baton->per_cu);
20726   /* We don't know how long the location list is, but make sure we
20727      don't run off the edge of the section.  */
20728   baton->size = section->size - DW_UNSND (attr);
20729   baton->data = section->buffer + DW_UNSND (attr);
20730   baton->base_address = cu->base_address;
20731   baton->from_dwo = cu->dwo_unit != NULL;
20732 }
20733
20734 static void
20735 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
20736                              struct dwarf2_cu *cu, int is_block)
20737 {
20738   struct objfile *objfile = dwarf2_per_objfile->objfile;
20739   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20740
20741   if (attr_form_is_section_offset (attr)
20742       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
20743          the section.  If so, fall through to the complaint in the
20744          other branch.  */
20745       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
20746     {
20747       struct dwarf2_loclist_baton *baton;
20748
20749       baton = obstack_alloc (&objfile->objfile_obstack,
20750                              sizeof (struct dwarf2_loclist_baton));
20751
20752       fill_in_loclist_baton (cu, baton, attr);
20753
20754       if (cu->base_known == 0)
20755         complaint (&symfile_complaints,
20756                    _("Location list used without "
20757                      "specifying the CU base address."));
20758
20759       SYMBOL_ACLASS_INDEX (sym) = (is_block
20760                                    ? dwarf2_loclist_block_index
20761                                    : dwarf2_loclist_index);
20762       SYMBOL_LOCATION_BATON (sym) = baton;
20763     }
20764   else
20765     {
20766       struct dwarf2_locexpr_baton *baton;
20767
20768       baton = obstack_alloc (&objfile->objfile_obstack,
20769                              sizeof (struct dwarf2_locexpr_baton));
20770       baton->per_cu = cu->per_cu;
20771       gdb_assert (baton->per_cu);
20772
20773       if (attr_form_is_block (attr))
20774         {
20775           /* Note that we're just copying the block's data pointer
20776              here, not the actual data.  We're still pointing into the
20777              info_buffer for SYM's objfile; right now we never release
20778              that buffer, but when we do clean up properly this may
20779              need to change.  */
20780           baton->size = DW_BLOCK (attr)->size;
20781           baton->data = DW_BLOCK (attr)->data;
20782         }
20783       else
20784         {
20785           dwarf2_invalid_attrib_class_complaint ("location description",
20786                                                  SYMBOL_NATURAL_NAME (sym));
20787           baton->size = 0;
20788         }
20789
20790       SYMBOL_ACLASS_INDEX (sym) = (is_block
20791                                    ? dwarf2_locexpr_block_index
20792                                    : dwarf2_locexpr_index);
20793       SYMBOL_LOCATION_BATON (sym) = baton;
20794     }
20795 }
20796
20797 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20798    came from a separate debuginfo file, then the master objfile is
20799    returned.  */
20800
20801 struct objfile *
20802 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20803 {
20804   struct objfile *objfile = per_cu->objfile;
20805
20806   /* Return the master objfile, so that we can report and look up the
20807      correct file containing this variable.  */
20808   if (objfile->separate_debug_objfile_backlink)
20809     objfile = objfile->separate_debug_objfile_backlink;
20810
20811   return objfile;
20812 }
20813
20814 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20815    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20816    CU_HEADERP first.  */
20817
20818 static const struct comp_unit_head *
20819 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20820                        struct dwarf2_per_cu_data *per_cu)
20821 {
20822   const gdb_byte *info_ptr;
20823
20824   if (per_cu->cu)
20825     return &per_cu->cu->header;
20826
20827   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20828
20829   memset (cu_headerp, 0, sizeof (*cu_headerp));
20830   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20831
20832   return cu_headerp;
20833 }
20834
20835 /* Return the address size given in the compilation unit header for CU.  */
20836
20837 int
20838 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20839 {
20840   struct comp_unit_head cu_header_local;
20841   const struct comp_unit_head *cu_headerp;
20842
20843   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20844
20845   return cu_headerp->addr_size;
20846 }
20847
20848 /* Return the offset size given in the compilation unit header for CU.  */
20849
20850 int
20851 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20852 {
20853   struct comp_unit_head cu_header_local;
20854   const struct comp_unit_head *cu_headerp;
20855
20856   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20857
20858   return cu_headerp->offset_size;
20859 }
20860
20861 /* See its dwarf2loc.h declaration.  */
20862
20863 int
20864 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20865 {
20866   struct comp_unit_head cu_header_local;
20867   const struct comp_unit_head *cu_headerp;
20868
20869   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20870
20871   if (cu_headerp->version == 2)
20872     return cu_headerp->addr_size;
20873   else
20874     return cu_headerp->offset_size;
20875 }
20876
20877 /* Return the text offset of the CU.  The returned offset comes from
20878    this CU's objfile.  If this objfile came from a separate debuginfo
20879    file, then the offset may be different from the corresponding
20880    offset in the parent objfile.  */
20881
20882 CORE_ADDR
20883 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20884 {
20885   struct objfile *objfile = per_cu->objfile;
20886
20887   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20888 }
20889
20890 /* Locate the .debug_info compilation unit from CU's objfile which contains
20891    the DIE at OFFSET.  Raises an error on failure.  */
20892
20893 static struct dwarf2_per_cu_data *
20894 dwarf2_find_containing_comp_unit (sect_offset offset,
20895                                   unsigned int offset_in_dwz,
20896                                   struct objfile *objfile)
20897 {
20898   struct dwarf2_per_cu_data *this_cu;
20899   int low, high;
20900   const sect_offset *cu_off;
20901
20902   low = 0;
20903   high = dwarf2_per_objfile->n_comp_units - 1;
20904   while (high > low)
20905     {
20906       struct dwarf2_per_cu_data *mid_cu;
20907       int mid = low + (high - low) / 2;
20908
20909       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20910       cu_off = &mid_cu->offset;
20911       if (mid_cu->is_dwz > offset_in_dwz
20912           || (mid_cu->is_dwz == offset_in_dwz
20913               && cu_off->sect_off >= offset.sect_off))
20914         high = mid;
20915       else
20916         low = mid + 1;
20917     }
20918   gdb_assert (low == high);
20919   this_cu = dwarf2_per_objfile->all_comp_units[low];
20920   cu_off = &this_cu->offset;
20921   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20922     {
20923       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20924         error (_("Dwarf Error: could not find partial DIE containing "
20925                "offset 0x%lx [in module %s]"),
20926                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20927
20928       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20929                   <= offset.sect_off);
20930       return dwarf2_per_objfile->all_comp_units[low-1];
20931     }
20932   else
20933     {
20934       this_cu = dwarf2_per_objfile->all_comp_units[low];
20935       if (low == dwarf2_per_objfile->n_comp_units - 1
20936           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20937         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20938       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20939       return this_cu;
20940     }
20941 }
20942
20943 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20944
20945 static void
20946 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20947 {
20948   memset (cu, 0, sizeof (*cu));
20949   per_cu->cu = cu;
20950   cu->per_cu = per_cu;
20951   cu->objfile = per_cu->objfile;
20952   obstack_init (&cu->comp_unit_obstack);
20953 }
20954
20955 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20956
20957 static void
20958 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20959                        enum language pretend_language)
20960 {
20961   struct attribute *attr;
20962
20963   /* Set the language we're debugging.  */
20964   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20965   if (attr)
20966     set_cu_language (DW_UNSND (attr), cu);
20967   else
20968     {
20969       cu->language = pretend_language;
20970       cu->language_defn = language_def (cu->language);
20971     }
20972
20973   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20974   if (attr)
20975     cu->producer = DW_STRING (attr);
20976 }
20977
20978 /* Release one cached compilation unit, CU.  We unlink it from the tree
20979    of compilation units, but we don't remove it from the read_in_chain;
20980    the caller is responsible for that.
20981    NOTE: DATA is a void * because this function is also used as a
20982    cleanup routine.  */
20983
20984 static void
20985 free_heap_comp_unit (void *data)
20986 {
20987   struct dwarf2_cu *cu = data;
20988
20989   gdb_assert (cu->per_cu != NULL);
20990   cu->per_cu->cu = NULL;
20991   cu->per_cu = NULL;
20992
20993   obstack_free (&cu->comp_unit_obstack, NULL);
20994
20995   xfree (cu);
20996 }
20997
20998 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20999    when we're finished with it.  We can't free the pointer itself, but be
21000    sure to unlink it from the cache.  Also release any associated storage.  */
21001
21002 static void
21003 free_stack_comp_unit (void *data)
21004 {
21005   struct dwarf2_cu *cu = data;
21006
21007   gdb_assert (cu->per_cu != NULL);
21008   cu->per_cu->cu = NULL;
21009   cu->per_cu = NULL;
21010
21011   obstack_free (&cu->comp_unit_obstack, NULL);
21012   cu->partial_dies = NULL;
21013 }
21014
21015 /* Free all cached compilation units.  */
21016
21017 static void
21018 free_cached_comp_units (void *data)
21019 {
21020   struct dwarf2_per_cu_data *per_cu, **last_chain;
21021
21022   per_cu = dwarf2_per_objfile->read_in_chain;
21023   last_chain = &dwarf2_per_objfile->read_in_chain;
21024   while (per_cu != NULL)
21025     {
21026       struct dwarf2_per_cu_data *next_cu;
21027
21028       next_cu = per_cu->cu->read_in_chain;
21029
21030       free_heap_comp_unit (per_cu->cu);
21031       *last_chain = next_cu;
21032
21033       per_cu = next_cu;
21034     }
21035 }
21036
21037 /* Increase the age counter on each cached compilation unit, and free
21038    any that are too old.  */
21039
21040 static void
21041 age_cached_comp_units (void)
21042 {
21043   struct dwarf2_per_cu_data *per_cu, **last_chain;
21044
21045   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
21046   per_cu = dwarf2_per_objfile->read_in_chain;
21047   while (per_cu != NULL)
21048     {
21049       per_cu->cu->last_used ++;
21050       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
21051         dwarf2_mark (per_cu->cu);
21052       per_cu = per_cu->cu->read_in_chain;
21053     }
21054
21055   per_cu = dwarf2_per_objfile->read_in_chain;
21056   last_chain = &dwarf2_per_objfile->read_in_chain;
21057   while (per_cu != NULL)
21058     {
21059       struct dwarf2_per_cu_data *next_cu;
21060
21061       next_cu = per_cu->cu->read_in_chain;
21062
21063       if (!per_cu->cu->mark)
21064         {
21065           free_heap_comp_unit (per_cu->cu);
21066           *last_chain = next_cu;
21067         }
21068       else
21069         last_chain = &per_cu->cu->read_in_chain;
21070
21071       per_cu = next_cu;
21072     }
21073 }
21074
21075 /* Remove a single compilation unit from the cache.  */
21076
21077 static void
21078 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
21079 {
21080   struct dwarf2_per_cu_data *per_cu, **last_chain;
21081
21082   per_cu = dwarf2_per_objfile->read_in_chain;
21083   last_chain = &dwarf2_per_objfile->read_in_chain;
21084   while (per_cu != NULL)
21085     {
21086       struct dwarf2_per_cu_data *next_cu;
21087
21088       next_cu = per_cu->cu->read_in_chain;
21089
21090       if (per_cu == target_per_cu)
21091         {
21092           free_heap_comp_unit (per_cu->cu);
21093           per_cu->cu = NULL;
21094           *last_chain = next_cu;
21095           break;
21096         }
21097       else
21098         last_chain = &per_cu->cu->read_in_chain;
21099
21100       per_cu = next_cu;
21101     }
21102 }
21103
21104 /* Release all extra memory associated with OBJFILE.  */
21105
21106 void
21107 dwarf2_free_objfile (struct objfile *objfile)
21108 {
21109   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21110
21111   if (dwarf2_per_objfile == NULL)
21112     return;
21113
21114   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
21115   free_cached_comp_units (NULL);
21116
21117   if (dwarf2_per_objfile->quick_file_names_table)
21118     htab_delete (dwarf2_per_objfile->quick_file_names_table);
21119
21120   /* Everything else should be on the objfile obstack.  */
21121 }
21122
21123 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
21124    We store these in a hash table separate from the DIEs, and preserve them
21125    when the DIEs are flushed out of cache.
21126
21127    The CU "per_cu" pointer is needed because offset alone is not enough to
21128    uniquely identify the type.  A file may have multiple .debug_types sections,
21129    or the type may come from a DWO file.  Furthermore, while it's more logical
21130    to use per_cu->section+offset, with Fission the section with the data is in
21131    the DWO file but we don't know that section at the point we need it.
21132    We have to use something in dwarf2_per_cu_data (or the pointer to it)
21133    because we can enter the lookup routine, get_die_type_at_offset, from
21134    outside this file, and thus won't necessarily have PER_CU->cu.
21135    Fortunately, PER_CU is stable for the life of the objfile.  */
21136
21137 struct dwarf2_per_cu_offset_and_type
21138 {
21139   const struct dwarf2_per_cu_data *per_cu;
21140   sect_offset offset;
21141   struct type *type;
21142 };
21143
21144 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
21145
21146 static hashval_t
21147 per_cu_offset_and_type_hash (const void *item)
21148 {
21149   const struct dwarf2_per_cu_offset_and_type *ofs = item;
21150
21151   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
21152 }
21153
21154 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
21155
21156 static int
21157 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
21158 {
21159   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
21160   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
21161
21162   return (ofs_lhs->per_cu == ofs_rhs->per_cu
21163           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
21164 }
21165
21166 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
21167    table if necessary.  For convenience, return TYPE.
21168
21169    The DIEs reading must have careful ordering to:
21170     * Not cause infite loops trying to read in DIEs as a prerequisite for
21171       reading current DIE.
21172     * Not trying to dereference contents of still incompletely read in types
21173       while reading in other DIEs.
21174     * Enable referencing still incompletely read in types just by a pointer to
21175       the type without accessing its fields.
21176
21177    Therefore caller should follow these rules:
21178      * Try to fetch any prerequisite types we may need to build this DIE type
21179        before building the type and calling set_die_type.
21180      * After building type call set_die_type for current DIE as soon as
21181        possible before fetching more types to complete the current type.
21182      * Make the type as complete as possible before fetching more types.  */
21183
21184 static struct type *
21185 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21186 {
21187   struct dwarf2_per_cu_offset_and_type **slot, ofs;
21188   struct objfile *objfile = cu->objfile;
21189
21190   /* For Ada types, make sure that the gnat-specific data is always
21191      initialized (if not already set).  There are a few types where
21192      we should not be doing so, because the type-specific area is
21193      already used to hold some other piece of info (eg: TYPE_CODE_FLT
21194      where the type-specific area is used to store the floatformat).
21195      But this is not a problem, because the gnat-specific information
21196      is actually not needed for these types.  */
21197   if (need_gnat_info (cu)
21198       && TYPE_CODE (type) != TYPE_CODE_FUNC
21199       && TYPE_CODE (type) != TYPE_CODE_FLT
21200       && !HAVE_GNAT_AUX_INFO (type))
21201     INIT_GNAT_SPECIFIC (type);
21202
21203   if (dwarf2_per_objfile->die_type_hash == NULL)
21204     {
21205       dwarf2_per_objfile->die_type_hash =
21206         htab_create_alloc_ex (127,
21207                               per_cu_offset_and_type_hash,
21208                               per_cu_offset_and_type_eq,
21209                               NULL,
21210                               &objfile->objfile_obstack,
21211                               hashtab_obstack_allocate,
21212                               dummy_obstack_deallocate);
21213     }
21214
21215   ofs.per_cu = cu->per_cu;
21216   ofs.offset = die->offset;
21217   ofs.type = type;
21218   slot = (struct dwarf2_per_cu_offset_and_type **)
21219     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
21220   if (*slot)
21221     complaint (&symfile_complaints,
21222                _("A problem internal to GDB: DIE 0x%x has type already set"),
21223                die->offset.sect_off);
21224   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
21225   **slot = ofs;
21226   return type;
21227 }
21228
21229 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
21230    or return NULL if the die does not have a saved type.  */
21231
21232 static struct type *
21233 get_die_type_at_offset (sect_offset offset,
21234                         struct dwarf2_per_cu_data *per_cu)
21235 {
21236   struct dwarf2_per_cu_offset_and_type *slot, ofs;
21237
21238   if (dwarf2_per_objfile->die_type_hash == NULL)
21239     return NULL;
21240
21241   ofs.per_cu = per_cu;
21242   ofs.offset = offset;
21243   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
21244   if (slot)
21245     return slot->type;
21246   else
21247     return NULL;
21248 }
21249
21250 /* Look up the type for DIE in CU in die_type_hash,
21251    or return NULL if DIE does not have a saved type.  */
21252
21253 static struct type *
21254 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
21255 {
21256   return get_die_type_at_offset (die->offset, cu->per_cu);
21257 }
21258
21259 /* Add a dependence relationship from CU to REF_PER_CU.  */
21260
21261 static void
21262 dwarf2_add_dependence (struct dwarf2_cu *cu,
21263                        struct dwarf2_per_cu_data *ref_per_cu)
21264 {
21265   void **slot;
21266
21267   if (cu->dependencies == NULL)
21268     cu->dependencies
21269       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
21270                               NULL, &cu->comp_unit_obstack,
21271                               hashtab_obstack_allocate,
21272                               dummy_obstack_deallocate);
21273
21274   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
21275   if (*slot == NULL)
21276     *slot = ref_per_cu;
21277 }
21278
21279 /* Subroutine of dwarf2_mark to pass to htab_traverse.
21280    Set the mark field in every compilation unit in the
21281    cache that we must keep because we are keeping CU.  */
21282
21283 static int
21284 dwarf2_mark_helper (void **slot, void *data)
21285 {
21286   struct dwarf2_per_cu_data *per_cu;
21287
21288   per_cu = (struct dwarf2_per_cu_data *) *slot;
21289
21290   /* cu->dependencies references may not yet have been ever read if QUIT aborts
21291      reading of the chain.  As such dependencies remain valid it is not much
21292      useful to track and undo them during QUIT cleanups.  */
21293   if (per_cu->cu == NULL)
21294     return 1;
21295
21296   if (per_cu->cu->mark)
21297     return 1;
21298   per_cu->cu->mark = 1;
21299
21300   if (per_cu->cu->dependencies != NULL)
21301     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
21302
21303   return 1;
21304 }
21305
21306 /* Set the mark field in CU and in every other compilation unit in the
21307    cache that we must keep because we are keeping CU.  */
21308
21309 static void
21310 dwarf2_mark (struct dwarf2_cu *cu)
21311 {
21312   if (cu->mark)
21313     return;
21314   cu->mark = 1;
21315   if (cu->dependencies != NULL)
21316     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
21317 }
21318
21319 static void
21320 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
21321 {
21322   while (per_cu)
21323     {
21324       per_cu->cu->mark = 0;
21325       per_cu = per_cu->cu->read_in_chain;
21326     }
21327 }
21328
21329 /* Trivial hash function for partial_die_info: the hash value of a DIE
21330    is its offset in .debug_info for this objfile.  */
21331
21332 static hashval_t
21333 partial_die_hash (const void *item)
21334 {
21335   const struct partial_die_info *part_die = item;
21336
21337   return part_die->offset.sect_off;
21338 }
21339
21340 /* Trivial comparison function for partial_die_info structures: two DIEs
21341    are equal if they have the same offset.  */
21342
21343 static int
21344 partial_die_eq (const void *item_lhs, const void *item_rhs)
21345 {
21346   const struct partial_die_info *part_die_lhs = item_lhs;
21347   const struct partial_die_info *part_die_rhs = item_rhs;
21348
21349   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
21350 }
21351
21352 static struct cmd_list_element *set_dwarf2_cmdlist;
21353 static struct cmd_list_element *show_dwarf2_cmdlist;
21354
21355 static void
21356 set_dwarf2_cmd (char *args, int from_tty)
21357 {
21358   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
21359 }
21360
21361 static void
21362 show_dwarf2_cmd (char *args, int from_tty)
21363 {
21364   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
21365 }
21366
21367 /* Free data associated with OBJFILE, if necessary.  */
21368
21369 static void
21370 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
21371 {
21372   struct dwarf2_per_objfile *data = d;
21373   int ix;
21374
21375   /* Make sure we don't accidentally use dwarf2_per_objfile while
21376      cleaning up.  */
21377   dwarf2_per_objfile = NULL;
21378
21379   for (ix = 0; ix < data->n_comp_units; ++ix)
21380    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
21381
21382   for (ix = 0; ix < data->n_type_units; ++ix)
21383     VEC_free (dwarf2_per_cu_ptr,
21384               data->all_type_units[ix]->per_cu.imported_symtabs);
21385   xfree (data->all_type_units);
21386
21387   VEC_free (dwarf2_section_info_def, data->types);
21388
21389   if (data->dwo_files)
21390     free_dwo_files (data->dwo_files, objfile);
21391   if (data->dwp_file)
21392     gdb_bfd_unref (data->dwp_file->dbfd);
21393
21394   if (data->dwz_file && data->dwz_file->dwz_bfd)
21395     gdb_bfd_unref (data->dwz_file->dwz_bfd);
21396 }
21397
21398 \f
21399 /* The "save gdb-index" command.  */
21400
21401 /* The contents of the hash table we create when building the string
21402    table.  */
21403 struct strtab_entry
21404 {
21405   offset_type offset;
21406   const char *str;
21407 };
21408
21409 /* Hash function for a strtab_entry.
21410
21411    Function is used only during write_hash_table so no index format backward
21412    compatibility is needed.  */
21413
21414 static hashval_t
21415 hash_strtab_entry (const void *e)
21416 {
21417   const struct strtab_entry *entry = e;
21418   return mapped_index_string_hash (INT_MAX, entry->str);
21419 }
21420
21421 /* Equality function for a strtab_entry.  */
21422
21423 static int
21424 eq_strtab_entry (const void *a, const void *b)
21425 {
21426   const struct strtab_entry *ea = a;
21427   const struct strtab_entry *eb = b;
21428   return !strcmp (ea->str, eb->str);
21429 }
21430
21431 /* Create a strtab_entry hash table.  */
21432
21433 static htab_t
21434 create_strtab (void)
21435 {
21436   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
21437                             xfree, xcalloc, xfree);
21438 }
21439
21440 /* Add a string to the constant pool.  Return the string's offset in
21441    host order.  */
21442
21443 static offset_type
21444 add_string (htab_t table, struct obstack *cpool, const char *str)
21445 {
21446   void **slot;
21447   struct strtab_entry entry;
21448   struct strtab_entry *result;
21449
21450   entry.str = str;
21451   slot = htab_find_slot (table, &entry, INSERT);
21452   if (*slot)
21453     result = *slot;
21454   else
21455     {
21456       result = XNEW (struct strtab_entry);
21457       result->offset = obstack_object_size (cpool);
21458       result->str = str;
21459       obstack_grow_str0 (cpool, str);
21460       *slot = result;
21461     }
21462   return result->offset;
21463 }
21464
21465 /* An entry in the symbol table.  */
21466 struct symtab_index_entry
21467 {
21468   /* The name of the symbol.  */
21469   const char *name;
21470   /* The offset of the name in the constant pool.  */
21471   offset_type index_offset;
21472   /* A sorted vector of the indices of all the CUs that hold an object
21473      of this name.  */
21474   VEC (offset_type) *cu_indices;
21475 };
21476
21477 /* The symbol table.  This is a power-of-2-sized hash table.  */
21478 struct mapped_symtab
21479 {
21480   offset_type n_elements;
21481   offset_type size;
21482   struct symtab_index_entry **data;
21483 };
21484
21485 /* Hash function for a symtab_index_entry.  */
21486
21487 static hashval_t
21488 hash_symtab_entry (const void *e)
21489 {
21490   const struct symtab_index_entry *entry = e;
21491   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
21492                          sizeof (offset_type) * VEC_length (offset_type,
21493                                                             entry->cu_indices),
21494                          0);
21495 }
21496
21497 /* Equality function for a symtab_index_entry.  */
21498
21499 static int
21500 eq_symtab_entry (const void *a, const void *b)
21501 {
21502   const struct symtab_index_entry *ea = a;
21503   const struct symtab_index_entry *eb = b;
21504   int len = VEC_length (offset_type, ea->cu_indices);
21505   if (len != VEC_length (offset_type, eb->cu_indices))
21506     return 0;
21507   return !memcmp (VEC_address (offset_type, ea->cu_indices),
21508                   VEC_address (offset_type, eb->cu_indices),
21509                   sizeof (offset_type) * len);
21510 }
21511
21512 /* Destroy a symtab_index_entry.  */
21513
21514 static void
21515 delete_symtab_entry (void *p)
21516 {
21517   struct symtab_index_entry *entry = p;
21518   VEC_free (offset_type, entry->cu_indices);
21519   xfree (entry);
21520 }
21521
21522 /* Create a hash table holding symtab_index_entry objects.  */
21523
21524 static htab_t
21525 create_symbol_hash_table (void)
21526 {
21527   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
21528                             delete_symtab_entry, xcalloc, xfree);
21529 }
21530
21531 /* Create a new mapped symtab object.  */
21532
21533 static struct mapped_symtab *
21534 create_mapped_symtab (void)
21535 {
21536   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
21537   symtab->n_elements = 0;
21538   symtab->size = 1024;
21539   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21540   return symtab;
21541 }
21542
21543 /* Destroy a mapped_symtab.  */
21544
21545 static void
21546 cleanup_mapped_symtab (void *p)
21547 {
21548   struct mapped_symtab *symtab = p;
21549   /* The contents of the array are freed when the other hash table is
21550      destroyed.  */
21551   xfree (symtab->data);
21552   xfree (symtab);
21553 }
21554
21555 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
21556    the slot.
21557    
21558    Function is used only during write_hash_table so no index format backward
21559    compatibility is needed.  */
21560
21561 static struct symtab_index_entry **
21562 find_slot (struct mapped_symtab *symtab, const char *name)
21563 {
21564   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
21565
21566   index = hash & (symtab->size - 1);
21567   step = ((hash * 17) & (symtab->size - 1)) | 1;
21568
21569   for (;;)
21570     {
21571       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
21572         return &symtab->data[index];
21573       index = (index + step) & (symtab->size - 1);
21574     }
21575 }
21576
21577 /* Expand SYMTAB's hash table.  */
21578
21579 static void
21580 hash_expand (struct mapped_symtab *symtab)
21581 {
21582   offset_type old_size = symtab->size;
21583   offset_type i;
21584   struct symtab_index_entry **old_entries = symtab->data;
21585
21586   symtab->size *= 2;
21587   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21588
21589   for (i = 0; i < old_size; ++i)
21590     {
21591       if (old_entries[i])
21592         {
21593           struct symtab_index_entry **slot = find_slot (symtab,
21594                                                         old_entries[i]->name);
21595           *slot = old_entries[i];
21596         }
21597     }
21598
21599   xfree (old_entries);
21600 }
21601
21602 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
21603    CU_INDEX is the index of the CU in which the symbol appears.
21604    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
21605
21606 static void
21607 add_index_entry (struct mapped_symtab *symtab, const char *name,
21608                  int is_static, gdb_index_symbol_kind kind,
21609                  offset_type cu_index)
21610 {
21611   struct symtab_index_entry **slot;
21612   offset_type cu_index_and_attrs;
21613
21614   ++symtab->n_elements;
21615   if (4 * symtab->n_elements / 3 >= symtab->size)
21616     hash_expand (symtab);
21617
21618   slot = find_slot (symtab, name);
21619   if (!*slot)
21620     {
21621       *slot = XNEW (struct symtab_index_entry);
21622       (*slot)->name = name;
21623       /* index_offset is set later.  */
21624       (*slot)->cu_indices = NULL;
21625     }
21626
21627   cu_index_and_attrs = 0;
21628   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
21629   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
21630   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
21631
21632   /* We don't want to record an index value twice as we want to avoid the
21633      duplication.
21634      We process all global symbols and then all static symbols
21635      (which would allow us to avoid the duplication by only having to check
21636      the last entry pushed), but a symbol could have multiple kinds in one CU.
21637      To keep things simple we don't worry about the duplication here and
21638      sort and uniqufy the list after we've processed all symbols.  */
21639   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
21640 }
21641
21642 /* qsort helper routine for uniquify_cu_indices.  */
21643
21644 static int
21645 offset_type_compare (const void *ap, const void *bp)
21646 {
21647   offset_type a = *(offset_type *) ap;
21648   offset_type b = *(offset_type *) bp;
21649
21650   return (a > b) - (b > a);
21651 }
21652
21653 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
21654
21655 static void
21656 uniquify_cu_indices (struct mapped_symtab *symtab)
21657 {
21658   int i;
21659
21660   for (i = 0; i < symtab->size; ++i)
21661     {
21662       struct symtab_index_entry *entry = symtab->data[i];
21663
21664       if (entry
21665           && entry->cu_indices != NULL)
21666         {
21667           unsigned int next_to_insert, next_to_check;
21668           offset_type last_value;
21669
21670           qsort (VEC_address (offset_type, entry->cu_indices),
21671                  VEC_length (offset_type, entry->cu_indices),
21672                  sizeof (offset_type), offset_type_compare);
21673
21674           last_value = VEC_index (offset_type, entry->cu_indices, 0);
21675           next_to_insert = 1;
21676           for (next_to_check = 1;
21677                next_to_check < VEC_length (offset_type, entry->cu_indices);
21678                ++next_to_check)
21679             {
21680               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
21681                   != last_value)
21682                 {
21683                   last_value = VEC_index (offset_type, entry->cu_indices,
21684                                           next_to_check);
21685                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
21686                                last_value);
21687                   ++next_to_insert;
21688                 }
21689             }
21690           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
21691         }
21692     }
21693 }
21694
21695 /* Add a vector of indices to the constant pool.  */
21696
21697 static offset_type
21698 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
21699                       struct symtab_index_entry *entry)
21700 {
21701   void **slot;
21702
21703   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
21704   if (!*slot)
21705     {
21706       offset_type len = VEC_length (offset_type, entry->cu_indices);
21707       offset_type val = MAYBE_SWAP (len);
21708       offset_type iter;
21709       int i;
21710
21711       *slot = entry;
21712       entry->index_offset = obstack_object_size (cpool);
21713
21714       obstack_grow (cpool, &val, sizeof (val));
21715       for (i = 0;
21716            VEC_iterate (offset_type, entry->cu_indices, i, iter);
21717            ++i)
21718         {
21719           val = MAYBE_SWAP (iter);
21720           obstack_grow (cpool, &val, sizeof (val));
21721         }
21722     }
21723   else
21724     {
21725       struct symtab_index_entry *old_entry = *slot;
21726       entry->index_offset = old_entry->index_offset;
21727       entry = old_entry;
21728     }
21729   return entry->index_offset;
21730 }
21731
21732 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
21733    constant pool entries going into the obstack CPOOL.  */
21734
21735 static void
21736 write_hash_table (struct mapped_symtab *symtab,
21737                   struct obstack *output, struct obstack *cpool)
21738 {
21739   offset_type i;
21740   htab_t symbol_hash_table;
21741   htab_t str_table;
21742
21743   symbol_hash_table = create_symbol_hash_table ();
21744   str_table = create_strtab ();
21745
21746   /* We add all the index vectors to the constant pool first, to
21747      ensure alignment is ok.  */
21748   for (i = 0; i < symtab->size; ++i)
21749     {
21750       if (symtab->data[i])
21751         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21752     }
21753
21754   /* Now write out the hash table.  */
21755   for (i = 0; i < symtab->size; ++i)
21756     {
21757       offset_type str_off, vec_off;
21758
21759       if (symtab->data[i])
21760         {
21761           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21762           vec_off = symtab->data[i]->index_offset;
21763         }
21764       else
21765         {
21766           /* While 0 is a valid constant pool index, it is not valid
21767              to have 0 for both offsets.  */
21768           str_off = 0;
21769           vec_off = 0;
21770         }
21771
21772       str_off = MAYBE_SWAP (str_off);
21773       vec_off = MAYBE_SWAP (vec_off);
21774
21775       obstack_grow (output, &str_off, sizeof (str_off));
21776       obstack_grow (output, &vec_off, sizeof (vec_off));
21777     }
21778
21779   htab_delete (str_table);
21780   htab_delete (symbol_hash_table);
21781 }
21782
21783 /* Struct to map psymtab to CU index in the index file.  */
21784 struct psymtab_cu_index_map
21785 {
21786   struct partial_symtab *psymtab;
21787   unsigned int cu_index;
21788 };
21789
21790 static hashval_t
21791 hash_psymtab_cu_index (const void *item)
21792 {
21793   const struct psymtab_cu_index_map *map = item;
21794
21795   return htab_hash_pointer (map->psymtab);
21796 }
21797
21798 static int
21799 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21800 {
21801   const struct psymtab_cu_index_map *lhs = item_lhs;
21802   const struct psymtab_cu_index_map *rhs = item_rhs;
21803
21804   return lhs->psymtab == rhs->psymtab;
21805 }
21806
21807 /* Helper struct for building the address table.  */
21808 struct addrmap_index_data
21809 {
21810   struct objfile *objfile;
21811   struct obstack *addr_obstack;
21812   htab_t cu_index_htab;
21813
21814   /* Non-zero if the previous_* fields are valid.
21815      We can't write an entry until we see the next entry (since it is only then
21816      that we know the end of the entry).  */
21817   int previous_valid;
21818   /* Index of the CU in the table of all CUs in the index file.  */
21819   unsigned int previous_cu_index;
21820   /* Start address of the CU.  */
21821   CORE_ADDR previous_cu_start;
21822 };
21823
21824 /* Write an address entry to OBSTACK.  */
21825
21826 static void
21827 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21828                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21829 {
21830   offset_type cu_index_to_write;
21831   gdb_byte addr[8];
21832   CORE_ADDR baseaddr;
21833
21834   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21835
21836   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21837   obstack_grow (obstack, addr, 8);
21838   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21839   obstack_grow (obstack, addr, 8);
21840   cu_index_to_write = MAYBE_SWAP (cu_index);
21841   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21842 }
21843
21844 /* Worker function for traversing an addrmap to build the address table.  */
21845
21846 static int
21847 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21848 {
21849   struct addrmap_index_data *data = datap;
21850   struct partial_symtab *pst = obj;
21851
21852   if (data->previous_valid)
21853     add_address_entry (data->objfile, data->addr_obstack,
21854                        data->previous_cu_start, start_addr,
21855                        data->previous_cu_index);
21856
21857   data->previous_cu_start = start_addr;
21858   if (pst != NULL)
21859     {
21860       struct psymtab_cu_index_map find_map, *map;
21861       find_map.psymtab = pst;
21862       map = htab_find (data->cu_index_htab, &find_map);
21863       gdb_assert (map != NULL);
21864       data->previous_cu_index = map->cu_index;
21865       data->previous_valid = 1;
21866     }
21867   else
21868       data->previous_valid = 0;
21869
21870   return 0;
21871 }
21872
21873 /* Write OBJFILE's address map to OBSTACK.
21874    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21875    in the index file.  */
21876
21877 static void
21878 write_address_map (struct objfile *objfile, struct obstack *obstack,
21879                    htab_t cu_index_htab)
21880 {
21881   struct addrmap_index_data addrmap_index_data;
21882
21883   /* When writing the address table, we have to cope with the fact that
21884      the addrmap iterator only provides the start of a region; we have to
21885      wait until the next invocation to get the start of the next region.  */
21886
21887   addrmap_index_data.objfile = objfile;
21888   addrmap_index_data.addr_obstack = obstack;
21889   addrmap_index_data.cu_index_htab = cu_index_htab;
21890   addrmap_index_data.previous_valid = 0;
21891
21892   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21893                    &addrmap_index_data);
21894
21895   /* It's highly unlikely the last entry (end address = 0xff...ff)
21896      is valid, but we should still handle it.
21897      The end address is recorded as the start of the next region, but that
21898      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21899      anyway.  */
21900   if (addrmap_index_data.previous_valid)
21901     add_address_entry (objfile, obstack,
21902                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21903                        addrmap_index_data.previous_cu_index);
21904 }
21905
21906 /* Return the symbol kind of PSYM.  */
21907
21908 static gdb_index_symbol_kind
21909 symbol_kind (struct partial_symbol *psym)
21910 {
21911   domain_enum domain = PSYMBOL_DOMAIN (psym);
21912   enum address_class aclass = PSYMBOL_CLASS (psym);
21913
21914   switch (domain)
21915     {
21916     case VAR_DOMAIN:
21917       switch (aclass)
21918         {
21919         case LOC_BLOCK:
21920           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21921         case LOC_TYPEDEF:
21922           return GDB_INDEX_SYMBOL_KIND_TYPE;
21923         case LOC_COMPUTED:
21924         case LOC_CONST_BYTES:
21925         case LOC_OPTIMIZED_OUT:
21926         case LOC_STATIC:
21927           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21928         case LOC_CONST:
21929           /* Note: It's currently impossible to recognize psyms as enum values
21930              short of reading the type info.  For now punt.  */
21931           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21932         default:
21933           /* There are other LOC_FOO values that one might want to classify
21934              as variables, but dwarf2read.c doesn't currently use them.  */
21935           return GDB_INDEX_SYMBOL_KIND_OTHER;
21936         }
21937     case STRUCT_DOMAIN:
21938       return GDB_INDEX_SYMBOL_KIND_TYPE;
21939     default:
21940       return GDB_INDEX_SYMBOL_KIND_OTHER;
21941     }
21942 }
21943
21944 /* Add a list of partial symbols to SYMTAB.  */
21945
21946 static void
21947 write_psymbols (struct mapped_symtab *symtab,
21948                 htab_t psyms_seen,
21949                 struct partial_symbol **psymp,
21950                 int count,
21951                 offset_type cu_index,
21952                 int is_static)
21953 {
21954   for (; count-- > 0; ++psymp)
21955     {
21956       struct partial_symbol *psym = *psymp;
21957       void **slot;
21958
21959       if (SYMBOL_LANGUAGE (psym) == language_ada)
21960         error (_("Ada is not currently supported by the index"));
21961
21962       /* Only add a given psymbol once.  */
21963       slot = htab_find_slot (psyms_seen, psym, INSERT);
21964       if (!*slot)
21965         {
21966           gdb_index_symbol_kind kind = symbol_kind (psym);
21967
21968           *slot = psym;
21969           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21970                            is_static, kind, cu_index);
21971         }
21972     }
21973 }
21974
21975 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21976    exception if there is an error.  */
21977
21978 static void
21979 write_obstack (FILE *file, struct obstack *obstack)
21980 {
21981   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21982               file)
21983       != obstack_object_size (obstack))
21984     error (_("couldn't data write to file"));
21985 }
21986
21987 /* Unlink a file if the argument is not NULL.  */
21988
21989 static void
21990 unlink_if_set (void *p)
21991 {
21992   char **filename = p;
21993   if (*filename)
21994     unlink (*filename);
21995 }
21996
21997 /* A helper struct used when iterating over debug_types.  */
21998 struct signatured_type_index_data
21999 {
22000   struct objfile *objfile;
22001   struct mapped_symtab *symtab;
22002   struct obstack *types_list;
22003   htab_t psyms_seen;
22004   int cu_index;
22005 };
22006
22007 /* A helper function that writes a single signatured_type to an
22008    obstack.  */
22009
22010 static int
22011 write_one_signatured_type (void **slot, void *d)
22012 {
22013   struct signatured_type_index_data *info = d;
22014   struct signatured_type *entry = (struct signatured_type *) *slot;
22015   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
22016   gdb_byte val[8];
22017
22018   write_psymbols (info->symtab,
22019                   info->psyms_seen,
22020                   info->objfile->global_psymbols.list
22021                   + psymtab->globals_offset,
22022                   psymtab->n_global_syms, info->cu_index,
22023                   0);
22024   write_psymbols (info->symtab,
22025                   info->psyms_seen,
22026                   info->objfile->static_psymbols.list
22027                   + psymtab->statics_offset,
22028                   psymtab->n_static_syms, info->cu_index,
22029                   1);
22030
22031   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22032                           entry->per_cu.offset.sect_off);
22033   obstack_grow (info->types_list, val, 8);
22034   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22035                           entry->type_offset_in_tu.cu_off);
22036   obstack_grow (info->types_list, val, 8);
22037   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
22038   obstack_grow (info->types_list, val, 8);
22039
22040   ++info->cu_index;
22041
22042   return 1;
22043 }
22044
22045 /* Recurse into all "included" dependencies and write their symbols as
22046    if they appeared in this psymtab.  */
22047
22048 static void
22049 recursively_write_psymbols (struct objfile *objfile,
22050                             struct partial_symtab *psymtab,
22051                             struct mapped_symtab *symtab,
22052                             htab_t psyms_seen,
22053                             offset_type cu_index)
22054 {
22055   int i;
22056
22057   for (i = 0; i < psymtab->number_of_dependencies; ++i)
22058     if (psymtab->dependencies[i]->user != NULL)
22059       recursively_write_psymbols (objfile, psymtab->dependencies[i],
22060                                   symtab, psyms_seen, cu_index);
22061
22062   write_psymbols (symtab,
22063                   psyms_seen,
22064                   objfile->global_psymbols.list + psymtab->globals_offset,
22065                   psymtab->n_global_syms, cu_index,
22066                   0);
22067   write_psymbols (symtab,
22068                   psyms_seen,
22069                   objfile->static_psymbols.list + psymtab->statics_offset,
22070                   psymtab->n_static_syms, cu_index,
22071                   1);
22072 }
22073
22074 /* Create an index file for OBJFILE in the directory DIR.  */
22075
22076 static void
22077 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
22078 {
22079   struct cleanup *cleanup;
22080   char *filename, *cleanup_filename;
22081   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
22082   struct obstack cu_list, types_cu_list;
22083   int i;
22084   FILE *out_file;
22085   struct mapped_symtab *symtab;
22086   offset_type val, size_of_contents, total_len;
22087   struct stat st;
22088   htab_t psyms_seen;
22089   htab_t cu_index_htab;
22090   struct psymtab_cu_index_map *psymtab_cu_index_map;
22091
22092   if (dwarf2_per_objfile->using_index)
22093     error (_("Cannot use an index to create the index"));
22094
22095   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
22096     error (_("Cannot make an index when the file has multiple .debug_types sections"));
22097
22098   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
22099     return;
22100
22101   if (stat (objfile_name (objfile), &st) < 0)
22102     perror_with_name (objfile_name (objfile));
22103
22104   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
22105                      INDEX_SUFFIX, (char *) NULL);
22106   cleanup = make_cleanup (xfree, filename);
22107
22108   out_file = gdb_fopen_cloexec (filename, "wb");
22109   if (!out_file)
22110     error (_("Can't open `%s' for writing"), filename);
22111
22112   cleanup_filename = filename;
22113   make_cleanup (unlink_if_set, &cleanup_filename);
22114
22115   symtab = create_mapped_symtab ();
22116   make_cleanup (cleanup_mapped_symtab, symtab);
22117
22118   obstack_init (&addr_obstack);
22119   make_cleanup_obstack_free (&addr_obstack);
22120
22121   obstack_init (&cu_list);
22122   make_cleanup_obstack_free (&cu_list);
22123
22124   obstack_init (&types_cu_list);
22125   make_cleanup_obstack_free (&types_cu_list);
22126
22127   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
22128                                   NULL, xcalloc, xfree);
22129   make_cleanup_htab_delete (psyms_seen);
22130
22131   /* While we're scanning CU's create a table that maps a psymtab pointer
22132      (which is what addrmap records) to its index (which is what is recorded
22133      in the index file).  This will later be needed to write the address
22134      table.  */
22135   cu_index_htab = htab_create_alloc (100,
22136                                      hash_psymtab_cu_index,
22137                                      eq_psymtab_cu_index,
22138                                      NULL, xcalloc, xfree);
22139   make_cleanup_htab_delete (cu_index_htab);
22140   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
22141     xmalloc (sizeof (struct psymtab_cu_index_map)
22142              * dwarf2_per_objfile->n_comp_units);
22143   make_cleanup (xfree, psymtab_cu_index_map);
22144
22145   /* The CU list is already sorted, so we don't need to do additional
22146      work here.  Also, the debug_types entries do not appear in
22147      all_comp_units, but only in their own hash table.  */
22148   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
22149     {
22150       struct dwarf2_per_cu_data *per_cu
22151         = dwarf2_per_objfile->all_comp_units[i];
22152       struct partial_symtab *psymtab = per_cu->v.psymtab;
22153       gdb_byte val[8];
22154       struct psymtab_cu_index_map *map;
22155       void **slot;
22156
22157       /* CU of a shared file from 'dwz -m' may be unused by this main file.
22158          It may be referenced from a local scope but in such case it does not
22159          need to be present in .gdb_index.  */
22160       if (psymtab == NULL)
22161         continue;
22162
22163       if (psymtab->user == NULL)
22164         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
22165
22166       map = &psymtab_cu_index_map[i];
22167       map->psymtab = psymtab;
22168       map->cu_index = i;
22169       slot = htab_find_slot (cu_index_htab, map, INSERT);
22170       gdb_assert (slot != NULL);
22171       gdb_assert (*slot == NULL);
22172       *slot = map;
22173
22174       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22175                               per_cu->offset.sect_off);
22176       obstack_grow (&cu_list, val, 8);
22177       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
22178       obstack_grow (&cu_list, val, 8);
22179     }
22180
22181   /* Dump the address map.  */
22182   write_address_map (objfile, &addr_obstack, cu_index_htab);
22183
22184   /* Write out the .debug_type entries, if any.  */
22185   if (dwarf2_per_objfile->signatured_types)
22186     {
22187       struct signatured_type_index_data sig_data;
22188
22189       sig_data.objfile = objfile;
22190       sig_data.symtab = symtab;
22191       sig_data.types_list = &types_cu_list;
22192       sig_data.psyms_seen = psyms_seen;
22193       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
22194       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
22195                               write_one_signatured_type, &sig_data);
22196     }
22197
22198   /* Now that we've processed all symbols we can shrink their cu_indices
22199      lists.  */
22200   uniquify_cu_indices (symtab);
22201
22202   obstack_init (&constant_pool);
22203   make_cleanup_obstack_free (&constant_pool);
22204   obstack_init (&symtab_obstack);
22205   make_cleanup_obstack_free (&symtab_obstack);
22206   write_hash_table (symtab, &symtab_obstack, &constant_pool);
22207
22208   obstack_init (&contents);
22209   make_cleanup_obstack_free (&contents);
22210   size_of_contents = 6 * sizeof (offset_type);
22211   total_len = size_of_contents;
22212
22213   /* The version number.  */
22214   val = MAYBE_SWAP (8);
22215   obstack_grow (&contents, &val, sizeof (val));
22216
22217   /* The offset of the CU list from the start of the file.  */
22218   val = MAYBE_SWAP (total_len);
22219   obstack_grow (&contents, &val, sizeof (val));
22220   total_len += obstack_object_size (&cu_list);
22221
22222   /* The offset of the types CU list from the start of the file.  */
22223   val = MAYBE_SWAP (total_len);
22224   obstack_grow (&contents, &val, sizeof (val));
22225   total_len += obstack_object_size (&types_cu_list);
22226
22227   /* The offset of the address table from the start of the file.  */
22228   val = MAYBE_SWAP (total_len);
22229   obstack_grow (&contents, &val, sizeof (val));
22230   total_len += obstack_object_size (&addr_obstack);
22231
22232   /* The offset of the symbol table from the start of the file.  */
22233   val = MAYBE_SWAP (total_len);
22234   obstack_grow (&contents, &val, sizeof (val));
22235   total_len += obstack_object_size (&symtab_obstack);
22236
22237   /* The offset of the constant pool from the start of the file.  */
22238   val = MAYBE_SWAP (total_len);
22239   obstack_grow (&contents, &val, sizeof (val));
22240   total_len += obstack_object_size (&constant_pool);
22241
22242   gdb_assert (obstack_object_size (&contents) == size_of_contents);
22243
22244   write_obstack (out_file, &contents);
22245   write_obstack (out_file, &cu_list);
22246   write_obstack (out_file, &types_cu_list);
22247   write_obstack (out_file, &addr_obstack);
22248   write_obstack (out_file, &symtab_obstack);
22249   write_obstack (out_file, &constant_pool);
22250
22251   fclose (out_file);
22252
22253   /* We want to keep the file, so we set cleanup_filename to NULL
22254      here.  See unlink_if_set.  */
22255   cleanup_filename = NULL;
22256
22257   do_cleanups (cleanup);
22258 }
22259
22260 /* Implementation of the `save gdb-index' command.
22261    
22262    Note that the file format used by this command is documented in the
22263    GDB manual.  Any changes here must be documented there.  */
22264
22265 static void
22266 save_gdb_index_command (char *arg, int from_tty)
22267 {
22268   struct objfile *objfile;
22269
22270   if (!arg || !*arg)
22271     error (_("usage: save gdb-index DIRECTORY"));
22272
22273   ALL_OBJFILES (objfile)
22274   {
22275     struct stat st;
22276
22277     /* If the objfile does not correspond to an actual file, skip it.  */
22278     if (stat (objfile_name (objfile), &st) < 0)
22279       continue;
22280
22281     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
22282     if (dwarf2_per_objfile)
22283       {
22284         volatile struct gdb_exception except;
22285
22286         TRY_CATCH (except, RETURN_MASK_ERROR)
22287           {
22288             write_psymtabs_to_index (objfile, arg);
22289           }
22290         if (except.reason < 0)
22291           exception_fprintf (gdb_stderr, except,
22292                              _("Error while writing index for `%s': "),
22293                              objfile_name (objfile));
22294       }
22295   }
22296 }
22297
22298 \f
22299
22300 int dwarf2_always_disassemble;
22301
22302 static void
22303 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
22304                                 struct cmd_list_element *c, const char *value)
22305 {
22306   fprintf_filtered (file,
22307                     _("Whether to always disassemble "
22308                       "DWARF expressions is %s.\n"),
22309                     value);
22310 }
22311
22312 static void
22313 show_check_physname (struct ui_file *file, int from_tty,
22314                      struct cmd_list_element *c, const char *value)
22315 {
22316   fprintf_filtered (file,
22317                     _("Whether to check \"physname\" is %s.\n"),
22318                     value);
22319 }
22320
22321 void _initialize_dwarf2_read (void);
22322
22323 void
22324 _initialize_dwarf2_read (void)
22325 {
22326   struct cmd_list_element *c;
22327
22328   dwarf2_objfile_data_key
22329     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
22330
22331   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
22332 Set DWARF 2 specific variables.\n\
22333 Configure DWARF 2 variables such as the cache size"),
22334                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
22335                   0/*allow-unknown*/, &maintenance_set_cmdlist);
22336
22337   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
22338 Show DWARF 2 specific variables\n\
22339 Show DWARF 2 variables such as the cache size"),
22340                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
22341                   0/*allow-unknown*/, &maintenance_show_cmdlist);
22342
22343   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
22344                             &dwarf2_max_cache_age, _("\
22345 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
22346 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
22347 A higher limit means that cached compilation units will be stored\n\
22348 in memory longer, and more total memory will be used.  Zero disables\n\
22349 caching, which can slow down startup."),
22350                             NULL,
22351                             show_dwarf2_max_cache_age,
22352                             &set_dwarf2_cmdlist,
22353                             &show_dwarf2_cmdlist);
22354
22355   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
22356                            &dwarf2_always_disassemble, _("\
22357 Set whether `info address' always disassembles DWARF expressions."), _("\
22358 Show whether `info address' always disassembles DWARF expressions."), _("\
22359 When enabled, DWARF expressions are always printed in an assembly-like\n\
22360 syntax.  When disabled, expressions will be printed in a more\n\
22361 conversational style, when possible."),
22362                            NULL,
22363                            show_dwarf2_always_disassemble,
22364                            &set_dwarf2_cmdlist,
22365                            &show_dwarf2_cmdlist);
22366
22367   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
22368 Set debugging of the dwarf2 reader."), _("\
22369 Show debugging of the dwarf2 reader."), _("\
22370 When enabled, debugging messages are printed during dwarf2 reading\n\
22371 and symtab expansion."),
22372                             NULL,
22373                             NULL,
22374                             &setdebuglist, &showdebuglist);
22375
22376   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
22377 Set debugging of the dwarf2 DIE reader."), _("\
22378 Show debugging of the dwarf2 DIE reader."), _("\
22379 When enabled (non-zero), DIEs are dumped after they are read in.\n\
22380 The value is the maximum depth to print."),
22381                              NULL,
22382                              NULL,
22383                              &setdebuglist, &showdebuglist);
22384
22385   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
22386 Set cross-checking of \"physname\" code against demangler."), _("\
22387 Show cross-checking of \"physname\" code against demangler."), _("\
22388 When enabled, GDB's internal \"physname\" code is checked against\n\
22389 the demangler."),
22390                            NULL, show_check_physname,
22391                            &setdebuglist, &showdebuglist);
22392
22393   add_setshow_boolean_cmd ("use-deprecated-index-sections",
22394                            no_class, &use_deprecated_index_sections, _("\
22395 Set whether to use deprecated gdb_index sections."), _("\
22396 Show whether to use deprecated gdb_index sections."), _("\
22397 When enabled, deprecated .gdb_index sections are used anyway.\n\
22398 Normally they are ignored either because of a missing feature or\n\
22399 performance issue.\n\
22400 Warning: This option must be enabled before gdb reads the file."),
22401                            NULL,
22402                            NULL,
22403                            &setlist, &showlist);
22404
22405   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
22406                _("\
22407 Save a gdb-index file.\n\
22408 Usage: save gdb-index DIRECTORY"),
22409                &save_cmdlist);
22410   set_cmd_completer (c, filename_completer);
22411
22412   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
22413                                                         &dwarf2_locexpr_funcs);
22414   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
22415                                                         &dwarf2_loclist_funcs);
22416
22417   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
22418                                         &dwarf2_block_frame_base_locexpr_funcs);
22419   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
22420                                         &dwarf2_block_frame_base_loclist_funcs);
22421 }