fix PR symtab/15597
[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   size_t buildid_len;
2369   bfd_byte *buildid;
2370
2371   if (dwarf2_per_objfile->dwz_file != NULL)
2372     return dwarf2_per_objfile->dwz_file;
2373
2374   bfd_set_error (bfd_error_no_error);
2375   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2376                                       &buildid_len, &buildid);
2377   if (data == NULL)
2378     {
2379       if (bfd_get_error () == bfd_error_no_error)
2380         return NULL;
2381       error (_("could not read '.gnu_debugaltlink' section: %s"),
2382              bfd_errmsg (bfd_get_error ()));
2383     }
2384   cleanup = make_cleanup (xfree, data);
2385   make_cleanup (xfree, buildid);
2386
2387   filename = (const char *) data;
2388   if (!IS_ABSOLUTE_PATH (filename))
2389     {
2390       char *abs = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2391       char *rel;
2392
2393       make_cleanup (xfree, abs);
2394       abs = ldirname (abs);
2395       make_cleanup (xfree, abs);
2396
2397       rel = concat (abs, SLASH_STRING, filename, (char *) NULL);
2398       make_cleanup (xfree, rel);
2399       filename = rel;
2400     }
2401
2402   /* First try the file name given in the section.  If that doesn't
2403      work, try to use the build-id instead.  */
2404   dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
2405   if (dwz_bfd != NULL)
2406     {
2407       if (!build_id_verify (dwz_bfd, buildid_len, buildid))
2408         {
2409           gdb_bfd_unref (dwz_bfd);
2410           dwz_bfd = NULL;
2411         }
2412     }
2413
2414   if (dwz_bfd == NULL)
2415     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2416
2417   if (dwz_bfd == NULL)
2418     error (_("could not find '.gnu_debugaltlink' file for %s"),
2419            objfile_name (dwarf2_per_objfile->objfile));
2420
2421   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2422                            struct dwz_file);
2423   result->dwz_bfd = dwz_bfd;
2424
2425   bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
2426
2427   do_cleanups (cleanup);
2428
2429   dwarf2_per_objfile->dwz_file = result;
2430   return result;
2431 }
2432 \f
2433 /* DWARF quick_symbols_functions support.  */
2434
2435 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2436    unique line tables, so we maintain a separate table of all .debug_line
2437    derived entries to support the sharing.
2438    All the quick functions need is the list of file names.  We discard the
2439    line_header when we're done and don't need to record it here.  */
2440 struct quick_file_names
2441 {
2442   /* The data used to construct the hash key.  */
2443   struct stmt_list_hash hash;
2444
2445   /* The number of entries in file_names, real_names.  */
2446   unsigned int num_file_names;
2447
2448   /* The file names from the line table, after being run through
2449      file_full_name.  */
2450   const char **file_names;
2451
2452   /* The file names from the line table after being run through
2453      gdb_realpath.  These are computed lazily.  */
2454   const char **real_names;
2455 };
2456
2457 /* When using the index (and thus not using psymtabs), each CU has an
2458    object of this type.  This is used to hold information needed by
2459    the various "quick" methods.  */
2460 struct dwarf2_per_cu_quick_data
2461 {
2462   /* The file table.  This can be NULL if there was no file table
2463      or it's currently not read in.
2464      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2465   struct quick_file_names *file_names;
2466
2467   /* The corresponding symbol table.  This is NULL if symbols for this
2468      CU have not yet been read.  */
2469   struct symtab *symtab;
2470
2471   /* A temporary mark bit used when iterating over all CUs in
2472      expand_symtabs_matching.  */
2473   unsigned int mark : 1;
2474
2475   /* True if we've tried to read the file table and found there isn't one.
2476      There will be no point in trying to read it again next time.  */
2477   unsigned int no_file_data : 1;
2478 };
2479
2480 /* Utility hash function for a stmt_list_hash.  */
2481
2482 static hashval_t
2483 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2484 {
2485   hashval_t v = 0;
2486
2487   if (stmt_list_hash->dwo_unit != NULL)
2488     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2489   v += stmt_list_hash->line_offset.sect_off;
2490   return v;
2491 }
2492
2493 /* Utility equality function for a stmt_list_hash.  */
2494
2495 static int
2496 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2497                     const struct stmt_list_hash *rhs)
2498 {
2499   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2500     return 0;
2501   if (lhs->dwo_unit != NULL
2502       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2503     return 0;
2504
2505   return lhs->line_offset.sect_off == rhs->line_offset.sect_off;
2506 }
2507
2508 /* Hash function for a quick_file_names.  */
2509
2510 static hashval_t
2511 hash_file_name_entry (const void *e)
2512 {
2513   const struct quick_file_names *file_data = e;
2514
2515   return hash_stmt_list_entry (&file_data->hash);
2516 }
2517
2518 /* Equality function for a quick_file_names.  */
2519
2520 static int
2521 eq_file_name_entry (const void *a, const void *b)
2522 {
2523   const struct quick_file_names *ea = a;
2524   const struct quick_file_names *eb = b;
2525
2526   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2527 }
2528
2529 /* Delete function for a quick_file_names.  */
2530
2531 static void
2532 delete_file_name_entry (void *e)
2533 {
2534   struct quick_file_names *file_data = e;
2535   int i;
2536
2537   for (i = 0; i < file_data->num_file_names; ++i)
2538     {
2539       xfree ((void*) file_data->file_names[i]);
2540       if (file_data->real_names)
2541         xfree ((void*) file_data->real_names[i]);
2542     }
2543
2544   /* The space for the struct itself lives on objfile_obstack,
2545      so we don't free it here.  */
2546 }
2547
2548 /* Create a quick_file_names hash table.  */
2549
2550 static htab_t
2551 create_quick_file_names_table (unsigned int nr_initial_entries)
2552 {
2553   return htab_create_alloc (nr_initial_entries,
2554                             hash_file_name_entry, eq_file_name_entry,
2555                             delete_file_name_entry, xcalloc, xfree);
2556 }
2557
2558 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2559    have to be created afterwards.  You should call age_cached_comp_units after
2560    processing PER_CU->CU.  dw2_setup must have been already called.  */
2561
2562 static void
2563 load_cu (struct dwarf2_per_cu_data *per_cu)
2564 {
2565   if (per_cu->is_debug_types)
2566     load_full_type_unit (per_cu);
2567   else
2568     load_full_comp_unit (per_cu, language_minimal);
2569
2570   gdb_assert (per_cu->cu != NULL);
2571
2572   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2573 }
2574
2575 /* Read in the symbols for PER_CU.  */
2576
2577 static void
2578 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2579 {
2580   struct cleanup *back_to;
2581
2582   /* Skip type_unit_groups, reading the type units they contain
2583      is handled elsewhere.  */
2584   if (IS_TYPE_UNIT_GROUP (per_cu))
2585     return;
2586
2587   back_to = make_cleanup (dwarf2_release_queue, NULL);
2588
2589   if (dwarf2_per_objfile->using_index
2590       ? per_cu->v.quick->symtab == NULL
2591       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2592     {
2593       queue_comp_unit (per_cu, language_minimal);
2594       load_cu (per_cu);
2595
2596       /* If we just loaded a CU from a DWO, and we're working with an index
2597          that may badly handle TUs, load all the TUs in that DWO as well.
2598          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2599       if (!per_cu->is_debug_types
2600           && per_cu->cu->dwo_unit != NULL
2601           && dwarf2_per_objfile->index_table != NULL
2602           && dwarf2_per_objfile->index_table->version <= 7
2603           /* DWP files aren't supported yet.  */
2604           && get_dwp_file () == NULL)
2605         queue_and_load_all_dwo_tus (per_cu);
2606     }
2607
2608   process_queue ();
2609
2610   /* Age the cache, releasing compilation units that have not
2611      been used recently.  */
2612   age_cached_comp_units ();
2613
2614   do_cleanups (back_to);
2615 }
2616
2617 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2618    the objfile from which this CU came.  Returns the resulting symbol
2619    table.  */
2620
2621 static struct symtab *
2622 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2623 {
2624   gdb_assert (dwarf2_per_objfile->using_index);
2625   if (!per_cu->v.quick->symtab)
2626     {
2627       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2628       increment_reading_symtab ();
2629       dw2_do_instantiate_symtab (per_cu);
2630       process_cu_includes ();
2631       do_cleanups (back_to);
2632     }
2633   return per_cu->v.quick->symtab;
2634 }
2635
2636 /* Return the CU given its index.
2637
2638    This is intended for loops like:
2639
2640    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2641                     + dwarf2_per_objfile->n_type_units); ++i)
2642      {
2643        struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
2644
2645        ...;
2646      }
2647 */
2648
2649 static struct dwarf2_per_cu_data *
2650 dw2_get_cu (int index)
2651 {
2652   if (index >= dwarf2_per_objfile->n_comp_units)
2653     {
2654       index -= dwarf2_per_objfile->n_comp_units;
2655       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2656       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2657     }
2658
2659   return dwarf2_per_objfile->all_comp_units[index];
2660 }
2661
2662 /* Return the primary CU given its index.
2663    The difference between this function and dw2_get_cu is in the handling
2664    of type units (TUs).  Here we return the type_unit_group object.
2665
2666    This is intended for loops like:
2667
2668    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2669                     + dwarf2_per_objfile->n_type_unit_groups); ++i)
2670      {
2671        struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
2672
2673        ...;
2674      }
2675 */
2676
2677 static struct dwarf2_per_cu_data *
2678 dw2_get_primary_cu (int index)
2679 {
2680   if (index >= dwarf2_per_objfile->n_comp_units)
2681     {
2682       index -= dwarf2_per_objfile->n_comp_units;
2683       gdb_assert (index < dwarf2_per_objfile->n_type_unit_groups);
2684       return &dwarf2_per_objfile->all_type_unit_groups[index]->per_cu;
2685     }
2686
2687   return dwarf2_per_objfile->all_comp_units[index];
2688 }
2689
2690 /* A helper for create_cus_from_index that handles a given list of
2691    CUs.  */
2692
2693 static void
2694 create_cus_from_index_list (struct objfile *objfile,
2695                             const gdb_byte *cu_list, offset_type n_elements,
2696                             struct dwarf2_section_info *section,
2697                             int is_dwz,
2698                             int base_offset)
2699 {
2700   offset_type i;
2701
2702   for (i = 0; i < n_elements; i += 2)
2703     {
2704       struct dwarf2_per_cu_data *the_cu;
2705       ULONGEST offset, length;
2706
2707       gdb_static_assert (sizeof (ULONGEST) >= 8);
2708       offset = extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2709       length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2710       cu_list += 2 * 8;
2711
2712       the_cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2713                                struct dwarf2_per_cu_data);
2714       the_cu->offset.sect_off = offset;
2715       the_cu->length = length;
2716       the_cu->objfile = objfile;
2717       the_cu->section = section;
2718       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2719                                         struct dwarf2_per_cu_quick_data);
2720       the_cu->is_dwz = is_dwz;
2721       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
2722     }
2723 }
2724
2725 /* Read the CU list from the mapped index, and use it to create all
2726    the CU objects for this objfile.  */
2727
2728 static void
2729 create_cus_from_index (struct objfile *objfile,
2730                        const gdb_byte *cu_list, offset_type cu_list_elements,
2731                        const gdb_byte *dwz_list, offset_type dwz_elements)
2732 {
2733   struct dwz_file *dwz;
2734
2735   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2736   dwarf2_per_objfile->all_comp_units
2737     = obstack_alloc (&objfile->objfile_obstack,
2738                      dwarf2_per_objfile->n_comp_units
2739                      * sizeof (struct dwarf2_per_cu_data *));
2740
2741   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
2742                               &dwarf2_per_objfile->info, 0, 0);
2743
2744   if (dwz_elements == 0)
2745     return;
2746
2747   dwz = dwarf2_get_dwz_file ();
2748   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
2749                               cu_list_elements / 2);
2750 }
2751
2752 /* Create the signatured type hash table from the index.  */
2753
2754 static void
2755 create_signatured_type_table_from_index (struct objfile *objfile,
2756                                          struct dwarf2_section_info *section,
2757                                          const gdb_byte *bytes,
2758                                          offset_type elements)
2759 {
2760   offset_type i;
2761   htab_t sig_types_hash;
2762
2763   dwarf2_per_objfile->n_type_units = elements / 3;
2764   dwarf2_per_objfile->all_type_units
2765     = xmalloc (dwarf2_per_objfile->n_type_units
2766                * sizeof (struct signatured_type *));
2767
2768   sig_types_hash = allocate_signatured_type_table (objfile);
2769
2770   for (i = 0; i < elements; i += 3)
2771     {
2772       struct signatured_type *sig_type;
2773       ULONGEST offset, type_offset_in_tu, signature;
2774       void **slot;
2775
2776       gdb_static_assert (sizeof (ULONGEST) >= 8);
2777       offset = extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
2778       type_offset_in_tu = extract_unsigned_integer (bytes + 8, 8,
2779                                                     BFD_ENDIAN_LITTLE);
2780       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
2781       bytes += 3 * 8;
2782
2783       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2784                                  struct signatured_type);
2785       sig_type->signature = signature;
2786       sig_type->type_offset_in_tu.cu_off = type_offset_in_tu;
2787       sig_type->per_cu.is_debug_types = 1;
2788       sig_type->per_cu.section = section;
2789       sig_type->per_cu.offset.sect_off = offset;
2790       sig_type->per_cu.objfile = objfile;
2791       sig_type->per_cu.v.quick
2792         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2793                           struct dwarf2_per_cu_quick_data);
2794
2795       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
2796       *slot = sig_type;
2797
2798       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
2799     }
2800
2801   dwarf2_per_objfile->signatured_types = sig_types_hash;
2802 }
2803
2804 /* Read the address map data from the mapped index, and use it to
2805    populate the objfile's psymtabs_addrmap.  */
2806
2807 static void
2808 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
2809 {
2810   const gdb_byte *iter, *end;
2811   struct obstack temp_obstack;
2812   struct addrmap *mutable_map;
2813   struct cleanup *cleanup;
2814   CORE_ADDR baseaddr;
2815
2816   obstack_init (&temp_obstack);
2817   cleanup = make_cleanup_obstack_free (&temp_obstack);
2818   mutable_map = addrmap_create_mutable (&temp_obstack);
2819
2820   iter = index->address_table;
2821   end = iter + index->address_table_size;
2822
2823   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
2824
2825   while (iter < end)
2826     {
2827       ULONGEST hi, lo, cu_index;
2828       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2829       iter += 8;
2830       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
2831       iter += 8;
2832       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
2833       iter += 4;
2834
2835       if (lo > hi)
2836         {
2837           complaint (&symfile_complaints,
2838                      _(".gdb_index address table has invalid range (%s - %s)"),
2839                      hex_string (lo), hex_string (hi));
2840           continue;
2841         }
2842
2843       if (cu_index >= dwarf2_per_objfile->n_comp_units)
2844         {
2845           complaint (&symfile_complaints,
2846                      _(".gdb_index address table has invalid CU number %u"),
2847                      (unsigned) cu_index);
2848           continue;
2849         }
2850
2851       addrmap_set_empty (mutable_map, lo + baseaddr, hi + baseaddr - 1,
2852                          dw2_get_cu (cu_index));
2853     }
2854
2855   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
2856                                                     &objfile->objfile_obstack);
2857   do_cleanups (cleanup);
2858 }
2859
2860 /* The hash function for strings in the mapped index.  This is the same as
2861    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
2862    implementation.  This is necessary because the hash function is tied to the
2863    format of the mapped index file.  The hash values do not have to match with
2864    SYMBOL_HASH_NEXT.
2865    
2866    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
2867
2868 static hashval_t
2869 mapped_index_string_hash (int index_version, const void *p)
2870 {
2871   const unsigned char *str = (const unsigned char *) p;
2872   hashval_t r = 0;
2873   unsigned char c;
2874
2875   while ((c = *str++) != 0)
2876     {
2877       if (index_version >= 5)
2878         c = tolower (c);
2879       r = r * 67 + c - 113;
2880     }
2881
2882   return r;
2883 }
2884
2885 /* Find a slot in the mapped index INDEX for the object named NAME.
2886    If NAME is found, set *VEC_OUT to point to the CU vector in the
2887    constant pool and return 1.  If NAME cannot be found, return 0.  */
2888
2889 static int
2890 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
2891                           offset_type **vec_out)
2892 {
2893   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
2894   offset_type hash;
2895   offset_type slot, step;
2896   int (*cmp) (const char *, const char *);
2897
2898   if (current_language->la_language == language_cplus
2899       || current_language->la_language == language_java
2900       || current_language->la_language == language_fortran)
2901     {
2902       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
2903          not contain any.  */
2904       const char *paren = strchr (name, '(');
2905
2906       if (paren)
2907         {
2908           char *dup;
2909
2910           dup = xmalloc (paren - name + 1);
2911           memcpy (dup, name, paren - name);
2912           dup[paren - name] = 0;
2913
2914           make_cleanup (xfree, dup);
2915           name = dup;
2916         }
2917     }
2918
2919   /* Index version 4 did not support case insensitive searches.  But the
2920      indices for case insensitive languages are built in lowercase, therefore
2921      simulate our NAME being searched is also lowercased.  */
2922   hash = mapped_index_string_hash ((index->version == 4
2923                                     && case_sensitivity == case_sensitive_off
2924                                     ? 5 : index->version),
2925                                    name);
2926
2927   slot = hash & (index->symbol_table_slots - 1);
2928   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
2929   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
2930
2931   for (;;)
2932     {
2933       /* Convert a slot number to an offset into the table.  */
2934       offset_type i = 2 * slot;
2935       const char *str;
2936       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
2937         {
2938           do_cleanups (back_to);
2939           return 0;
2940         }
2941
2942       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
2943       if (!cmp (name, str))
2944         {
2945           *vec_out = (offset_type *) (index->constant_pool
2946                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
2947           do_cleanups (back_to);
2948           return 1;
2949         }
2950
2951       slot = (slot + step) & (index->symbol_table_slots - 1);
2952     }
2953 }
2954
2955 /* A helper function that reads the .gdb_index from SECTION and fills
2956    in MAP.  FILENAME is the name of the file containing the section;
2957    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
2958    ok to use deprecated sections.
2959
2960    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
2961    out parameters that are filled in with information about the CU and
2962    TU lists in the section.
2963
2964    Returns 1 if all went well, 0 otherwise.  */
2965
2966 static int
2967 read_index_from_section (struct objfile *objfile,
2968                          const char *filename,
2969                          int deprecated_ok,
2970                          struct dwarf2_section_info *section,
2971                          struct mapped_index *map,
2972                          const gdb_byte **cu_list,
2973                          offset_type *cu_list_elements,
2974                          const gdb_byte **types_list,
2975                          offset_type *types_list_elements)
2976 {
2977   const gdb_byte *addr;
2978   offset_type version;
2979   offset_type *metadata;
2980   int i;
2981
2982   if (dwarf2_section_empty_p (section))
2983     return 0;
2984
2985   /* Older elfutils strip versions could keep the section in the main
2986      executable while splitting it for the separate debug info file.  */
2987   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
2988     return 0;
2989
2990   dwarf2_read_section (objfile, section);
2991
2992   addr = section->buffer;
2993   /* Version check.  */
2994   version = MAYBE_SWAP (*(offset_type *) addr);
2995   /* Versions earlier than 3 emitted every copy of a psymbol.  This
2996      causes the index to behave very poorly for certain requests.  Version 3
2997      contained incomplete addrmap.  So, it seems better to just ignore such
2998      indices.  */
2999   if (version < 4)
3000     {
3001       static int warning_printed = 0;
3002       if (!warning_printed)
3003         {
3004           warning (_("Skipping obsolete .gdb_index section in %s."),
3005                    filename);
3006           warning_printed = 1;
3007         }
3008       return 0;
3009     }
3010   /* Index version 4 uses a different hash function than index version
3011      5 and later.
3012
3013      Versions earlier than 6 did not emit psymbols for inlined
3014      functions.  Using these files will cause GDB not to be able to
3015      set breakpoints on inlined functions by name, so we ignore these
3016      indices unless the user has done
3017      "set use-deprecated-index-sections on".  */
3018   if (version < 6 && !deprecated_ok)
3019     {
3020       static int warning_printed = 0;
3021       if (!warning_printed)
3022         {
3023           warning (_("\
3024 Skipping deprecated .gdb_index section in %s.\n\
3025 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3026 to use the section anyway."),
3027                    filename);
3028           warning_printed = 1;
3029         }
3030       return 0;
3031     }
3032   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3033      of the TU (for symbols coming from TUs).  It's just a performance bug, and
3034      we can't distinguish gdb-generated indices from gold-generated ones, so
3035      nothing to do here.  */
3036
3037   /* Indexes with higher version than the one supported by GDB may be no
3038      longer backward compatible.  */
3039   if (version > 8)
3040     return 0;
3041
3042   map->version = version;
3043   map->total_size = section->size;
3044
3045   metadata = (offset_type *) (addr + sizeof (offset_type));
3046
3047   i = 0;
3048   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3049   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3050                        / 8);
3051   ++i;
3052
3053   *types_list = addr + MAYBE_SWAP (metadata[i]);
3054   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3055                            - MAYBE_SWAP (metadata[i]))
3056                           / 8);
3057   ++i;
3058
3059   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3060   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3061                              - MAYBE_SWAP (metadata[i]));
3062   ++i;
3063
3064   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3065   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3066                               - MAYBE_SWAP (metadata[i]))
3067                              / (2 * sizeof (offset_type)));
3068   ++i;
3069
3070   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3071
3072   return 1;
3073 }
3074
3075
3076 /* Read the index file.  If everything went ok, initialize the "quick"
3077    elements of all the CUs and return 1.  Otherwise, return 0.  */
3078
3079 static int
3080 dwarf2_read_index (struct objfile *objfile)
3081 {
3082   struct mapped_index local_map, *map;
3083   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3084   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3085   struct dwz_file *dwz;
3086
3087   if (!read_index_from_section (objfile, objfile_name (objfile),
3088                                 use_deprecated_index_sections,
3089                                 &dwarf2_per_objfile->gdb_index, &local_map,
3090                                 &cu_list, &cu_list_elements,
3091                                 &types_list, &types_list_elements))
3092     return 0;
3093
3094   /* Don't use the index if it's empty.  */
3095   if (local_map.symbol_table_slots == 0)
3096     return 0;
3097
3098   /* If there is a .dwz file, read it so we can get its CU list as
3099      well.  */
3100   dwz = dwarf2_get_dwz_file ();
3101   if (dwz != NULL)
3102     {
3103       struct mapped_index dwz_map;
3104       const gdb_byte *dwz_types_ignore;
3105       offset_type dwz_types_elements_ignore;
3106
3107       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3108                                     1,
3109                                     &dwz->gdb_index, &dwz_map,
3110                                     &dwz_list, &dwz_list_elements,
3111                                     &dwz_types_ignore,
3112                                     &dwz_types_elements_ignore))
3113         {
3114           warning (_("could not read '.gdb_index' section from %s; skipping"),
3115                    bfd_get_filename (dwz->dwz_bfd));
3116           return 0;
3117         }
3118     }
3119
3120   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3121                          dwz_list_elements);
3122
3123   if (types_list_elements)
3124     {
3125       struct dwarf2_section_info *section;
3126
3127       /* We can only handle a single .debug_types when we have an
3128          index.  */
3129       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3130         return 0;
3131
3132       section = VEC_index (dwarf2_section_info_def,
3133                            dwarf2_per_objfile->types, 0);
3134
3135       create_signatured_type_table_from_index (objfile, section, types_list,
3136                                                types_list_elements);
3137     }
3138
3139   create_addrmap_from_index (objfile, &local_map);
3140
3141   map = obstack_alloc (&objfile->objfile_obstack, sizeof (struct mapped_index));
3142   *map = local_map;
3143
3144   dwarf2_per_objfile->index_table = map;
3145   dwarf2_per_objfile->using_index = 1;
3146   dwarf2_per_objfile->quick_file_names_table =
3147     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3148
3149   return 1;
3150 }
3151
3152 /* A helper for the "quick" functions which sets the global
3153    dwarf2_per_objfile according to OBJFILE.  */
3154
3155 static void
3156 dw2_setup (struct objfile *objfile)
3157 {
3158   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
3159   gdb_assert (dwarf2_per_objfile);
3160 }
3161
3162 /* die_reader_func for dw2_get_file_names.  */
3163
3164 static void
3165 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3166                            const gdb_byte *info_ptr,
3167                            struct die_info *comp_unit_die,
3168                            int has_children,
3169                            void *data)
3170 {
3171   struct dwarf2_cu *cu = reader->cu;
3172   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3173   struct objfile *objfile = dwarf2_per_objfile->objfile;
3174   struct dwarf2_per_cu_data *lh_cu;
3175   struct line_header *lh;
3176   struct attribute *attr;
3177   int i;
3178   const char *name, *comp_dir;
3179   void **slot;
3180   struct quick_file_names *qfn;
3181   unsigned int line_offset;
3182
3183   gdb_assert (! this_cu->is_debug_types);
3184
3185   /* Our callers never want to match partial units -- instead they
3186      will match the enclosing full CU.  */
3187   if (comp_unit_die->tag == DW_TAG_partial_unit)
3188     {
3189       this_cu->v.quick->no_file_data = 1;
3190       return;
3191     }
3192
3193   lh_cu = this_cu;
3194   lh = NULL;
3195   slot = NULL;
3196   line_offset = 0;
3197
3198   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3199   if (attr)
3200     {
3201       struct quick_file_names find_entry;
3202
3203       line_offset = DW_UNSND (attr);
3204
3205       /* We may have already read in this line header (TU line header sharing).
3206          If we have we're done.  */
3207       find_entry.hash.dwo_unit = cu->dwo_unit;
3208       find_entry.hash.line_offset.sect_off = line_offset;
3209       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3210                              &find_entry, INSERT);
3211       if (*slot != NULL)
3212         {
3213           lh_cu->v.quick->file_names = *slot;
3214           return;
3215         }
3216
3217       lh = dwarf_decode_line_header (line_offset, cu);
3218     }
3219   if (lh == NULL)
3220     {
3221       lh_cu->v.quick->no_file_data = 1;
3222       return;
3223     }
3224
3225   qfn = obstack_alloc (&objfile->objfile_obstack, sizeof (*qfn));
3226   qfn->hash.dwo_unit = cu->dwo_unit;
3227   qfn->hash.line_offset.sect_off = line_offset;
3228   gdb_assert (slot != NULL);
3229   *slot = qfn;
3230
3231   find_file_and_directory (comp_unit_die, cu, &name, &comp_dir);
3232
3233   qfn->num_file_names = lh->num_file_names;
3234   qfn->file_names = obstack_alloc (&objfile->objfile_obstack,
3235                                    lh->num_file_names * sizeof (char *));
3236   for (i = 0; i < lh->num_file_names; ++i)
3237     qfn->file_names[i] = file_full_name (i + 1, lh, comp_dir);
3238   qfn->real_names = NULL;
3239
3240   free_line_header (lh);
3241
3242   lh_cu->v.quick->file_names = qfn;
3243 }
3244
3245 /* A helper for the "quick" functions which attempts to read the line
3246    table for THIS_CU.  */
3247
3248 static struct quick_file_names *
3249 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3250 {
3251   /* This should never be called for TUs.  */
3252   gdb_assert (! this_cu->is_debug_types);
3253   /* Nor type unit groups.  */
3254   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3255
3256   if (this_cu->v.quick->file_names != NULL)
3257     return this_cu->v.quick->file_names;
3258   /* If we know there is no line data, no point in looking again.  */
3259   if (this_cu->v.quick->no_file_data)
3260     return NULL;
3261
3262   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3263
3264   if (this_cu->v.quick->no_file_data)
3265     return NULL;
3266   return this_cu->v.quick->file_names;
3267 }
3268
3269 /* A helper for the "quick" functions which computes and caches the
3270    real path for a given file name from the line table.  */
3271
3272 static const char *
3273 dw2_get_real_path (struct objfile *objfile,
3274                    struct quick_file_names *qfn, int index)
3275 {
3276   if (qfn->real_names == NULL)
3277     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3278                                       qfn->num_file_names, sizeof (char *));
3279
3280   if (qfn->real_names[index] == NULL)
3281     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]);
3282
3283   return qfn->real_names[index];
3284 }
3285
3286 static struct symtab *
3287 dw2_find_last_source_symtab (struct objfile *objfile)
3288 {
3289   int index;
3290
3291   dw2_setup (objfile);
3292   index = dwarf2_per_objfile->n_comp_units - 1;
3293   return dw2_instantiate_symtab (dw2_get_cu (index));
3294 }
3295
3296 /* Traversal function for dw2_forget_cached_source_info.  */
3297
3298 static int
3299 dw2_free_cached_file_names (void **slot, void *info)
3300 {
3301   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3302
3303   if (file_data->real_names)
3304     {
3305       int i;
3306
3307       for (i = 0; i < file_data->num_file_names; ++i)
3308         {
3309           xfree ((void*) file_data->real_names[i]);
3310           file_data->real_names[i] = NULL;
3311         }
3312     }
3313
3314   return 1;
3315 }
3316
3317 static void
3318 dw2_forget_cached_source_info (struct objfile *objfile)
3319 {
3320   dw2_setup (objfile);
3321
3322   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3323                           dw2_free_cached_file_names, NULL);
3324 }
3325
3326 /* Helper function for dw2_map_symtabs_matching_filename that expands
3327    the symtabs and calls the iterator.  */
3328
3329 static int
3330 dw2_map_expand_apply (struct objfile *objfile,
3331                       struct dwarf2_per_cu_data *per_cu,
3332                       const char *name, const char *real_path,
3333                       int (*callback) (struct symtab *, void *),
3334                       void *data)
3335 {
3336   struct symtab *last_made = objfile->symtabs;
3337
3338   /* Don't visit already-expanded CUs.  */
3339   if (per_cu->v.quick->symtab)
3340     return 0;
3341
3342   /* This may expand more than one symtab, and we want to iterate over
3343      all of them.  */
3344   dw2_instantiate_symtab (per_cu);
3345
3346   return iterate_over_some_symtabs (name, real_path, callback, data,
3347                                     objfile->symtabs, last_made);
3348 }
3349
3350 /* Implementation of the map_symtabs_matching_filename method.  */
3351
3352 static int
3353 dw2_map_symtabs_matching_filename (struct objfile *objfile, const char *name,
3354                                    const char *real_path,
3355                                    int (*callback) (struct symtab *, void *),
3356                                    void *data)
3357 {
3358   int i;
3359   const char *name_basename = lbasename (name);
3360
3361   dw2_setup (objfile);
3362
3363   /* The rule is CUs specify all the files, including those used by
3364      any TU, so there's no need to scan TUs here.  */
3365
3366   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3367     {
3368       int j;
3369       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3370       struct quick_file_names *file_data;
3371
3372       /* We only need to look at symtabs not already expanded.  */
3373       if (per_cu->v.quick->symtab)
3374         continue;
3375
3376       file_data = dw2_get_file_names (per_cu);
3377       if (file_data == NULL)
3378         continue;
3379
3380       for (j = 0; j < file_data->num_file_names; ++j)
3381         {
3382           const char *this_name = file_data->file_names[j];
3383           const char *this_real_name;
3384
3385           if (compare_filenames_for_search (this_name, name))
3386             {
3387               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3388                                         callback, data))
3389                 return 1;
3390               continue;
3391             }
3392
3393           /* Before we invoke realpath, which can get expensive when many
3394              files are involved, do a quick comparison of the basenames.  */
3395           if (! basenames_may_differ
3396               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3397             continue;
3398
3399           this_real_name = dw2_get_real_path (objfile, file_data, j);
3400           if (compare_filenames_for_search (this_real_name, name))
3401             {
3402               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3403                                         callback, data))
3404                 return 1;
3405               continue;
3406             }
3407
3408           if (real_path != NULL)
3409             {
3410               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3411               gdb_assert (IS_ABSOLUTE_PATH (name));
3412               if (this_real_name != NULL
3413                   && FILENAME_CMP (real_path, this_real_name) == 0)
3414                 {
3415                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3416                                             callback, data))
3417                     return 1;
3418                   continue;
3419                 }
3420             }
3421         }
3422     }
3423
3424   return 0;
3425 }
3426
3427 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3428
3429 struct dw2_symtab_iterator
3430 {
3431   /* The internalized form of .gdb_index.  */
3432   struct mapped_index *index;
3433   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3434   int want_specific_block;
3435   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3436      Unused if !WANT_SPECIFIC_BLOCK.  */
3437   int block_index;
3438   /* The kind of symbol we're looking for.  */
3439   domain_enum domain;
3440   /* The list of CUs from the index entry of the symbol,
3441      or NULL if not found.  */
3442   offset_type *vec;
3443   /* The next element in VEC to look at.  */
3444   int next;
3445   /* The number of elements in VEC, or zero if there is no match.  */
3446   int length;
3447 };
3448
3449 /* Initialize the index symtab iterator ITER.
3450    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3451    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3452
3453 static void
3454 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3455                       struct mapped_index *index,
3456                       int want_specific_block,
3457                       int block_index,
3458                       domain_enum domain,
3459                       const char *name)
3460 {
3461   iter->index = index;
3462   iter->want_specific_block = want_specific_block;
3463   iter->block_index = block_index;
3464   iter->domain = domain;
3465   iter->next = 0;
3466
3467   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3468     iter->length = MAYBE_SWAP (*iter->vec);
3469   else
3470     {
3471       iter->vec = NULL;
3472       iter->length = 0;
3473     }
3474 }
3475
3476 /* Return the next matching CU or NULL if there are no more.  */
3477
3478 static struct dwarf2_per_cu_data *
3479 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3480 {
3481   for ( ; iter->next < iter->length; ++iter->next)
3482     {
3483       offset_type cu_index_and_attrs =
3484         MAYBE_SWAP (iter->vec[iter->next + 1]);
3485       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3486       struct dwarf2_per_cu_data *per_cu;
3487       int want_static = iter->block_index != GLOBAL_BLOCK;
3488       /* This value is only valid for index versions >= 7.  */
3489       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3490       gdb_index_symbol_kind symbol_kind =
3491         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3492       /* Only check the symbol attributes if they're present.
3493          Indices prior to version 7 don't record them,
3494          and indices >= 7 may elide them for certain symbols
3495          (gold does this).  */
3496       int attrs_valid =
3497         (iter->index->version >= 7
3498          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3499
3500       /* Don't crash on bad data.  */
3501       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3502                        + dwarf2_per_objfile->n_type_units))
3503         {
3504           complaint (&symfile_complaints,
3505                      _(".gdb_index entry has bad CU index"
3506                        " [in module %s]"),
3507                      objfile_name (dwarf2_per_objfile->objfile));
3508           continue;
3509         }
3510
3511       per_cu = dw2_get_cu (cu_index);
3512
3513       /* Skip if already read in.  */
3514       if (per_cu->v.quick->symtab)
3515         continue;
3516
3517       if (attrs_valid
3518           && iter->want_specific_block
3519           && want_static != is_static)
3520         continue;
3521
3522       /* Only check the symbol's kind if it has one.  */
3523       if (attrs_valid)
3524         {
3525           switch (iter->domain)
3526             {
3527             case VAR_DOMAIN:
3528               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3529                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3530                   /* Some types are also in VAR_DOMAIN.  */
3531                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3532                 continue;
3533               break;
3534             case STRUCT_DOMAIN:
3535               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3536                 continue;
3537               break;
3538             case LABEL_DOMAIN:
3539               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3540                 continue;
3541               break;
3542             default:
3543               break;
3544             }
3545         }
3546
3547       ++iter->next;
3548       return per_cu;
3549     }
3550
3551   return NULL;
3552 }
3553
3554 static struct symtab *
3555 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3556                    const char *name, domain_enum domain)
3557 {
3558   struct symtab *stab_best = NULL;
3559   struct mapped_index *index;
3560
3561   dw2_setup (objfile);
3562
3563   index = dwarf2_per_objfile->index_table;
3564
3565   /* index is NULL if OBJF_READNOW.  */
3566   if (index)
3567     {
3568       struct dw2_symtab_iterator iter;
3569       struct dwarf2_per_cu_data *per_cu;
3570
3571       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3572
3573       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3574         {
3575           struct symbol *sym = NULL;
3576           struct symtab *stab = dw2_instantiate_symtab (per_cu);
3577
3578           /* Some caution must be observed with overloaded functions
3579              and methods, since the index will not contain any overload
3580              information (but NAME might contain it).  */
3581           if (stab->primary)
3582             {
3583               struct blockvector *bv = BLOCKVECTOR (stab);
3584               struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3585
3586               sym = lookup_block_symbol (block, name, domain);
3587             }
3588
3589           if (sym && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
3590             {
3591               if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
3592                 return stab;
3593
3594               stab_best = stab;
3595             }
3596
3597           /* Keep looking through other CUs.  */
3598         }
3599     }
3600
3601   return stab_best;
3602 }
3603
3604 static void
3605 dw2_print_stats (struct objfile *objfile)
3606 {
3607   int i, total, count;
3608
3609   dw2_setup (objfile);
3610   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3611   count = 0;
3612   for (i = 0; i < total; ++i)
3613     {
3614       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3615
3616       if (!per_cu->v.quick->symtab)
3617         ++count;
3618     }
3619   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3620   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3621 }
3622
3623 /* This dumps minimal information about the index.
3624    It is called via "mt print objfiles".
3625    One use is to verify .gdb_index has been loaded by the
3626    gdb.dwarf2/gdb-index.exp testcase.  */
3627
3628 static void
3629 dw2_dump (struct objfile *objfile)
3630 {
3631   dw2_setup (objfile);
3632   gdb_assert (dwarf2_per_objfile->using_index);
3633   printf_filtered (".gdb_index:");
3634   if (dwarf2_per_objfile->index_table != NULL)
3635     {
3636       printf_filtered (" version %d\n",
3637                        dwarf2_per_objfile->index_table->version);
3638     }
3639   else
3640     printf_filtered (" faked for \"readnow\"\n");
3641   printf_filtered ("\n");
3642 }
3643
3644 static void
3645 dw2_relocate (struct objfile *objfile,
3646               const struct section_offsets *new_offsets,
3647               const struct section_offsets *delta)
3648 {
3649   /* There's nothing to relocate here.  */
3650 }
3651
3652 static void
3653 dw2_expand_symtabs_for_function (struct objfile *objfile,
3654                                  const char *func_name)
3655 {
3656   struct mapped_index *index;
3657
3658   dw2_setup (objfile);
3659
3660   index = dwarf2_per_objfile->index_table;
3661
3662   /* index is NULL if OBJF_READNOW.  */
3663   if (index)
3664     {
3665       struct dw2_symtab_iterator iter;
3666       struct dwarf2_per_cu_data *per_cu;
3667
3668       /* Note: It doesn't matter what we pass for block_index here.  */
3669       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3670                             func_name);
3671
3672       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3673         dw2_instantiate_symtab (per_cu);
3674     }
3675 }
3676
3677 static void
3678 dw2_expand_all_symtabs (struct objfile *objfile)
3679 {
3680   int i;
3681
3682   dw2_setup (objfile);
3683
3684   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3685                    + dwarf2_per_objfile->n_type_units); ++i)
3686     {
3687       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3688
3689       dw2_instantiate_symtab (per_cu);
3690     }
3691 }
3692
3693 static void
3694 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
3695                                   const char *fullname)
3696 {
3697   int i;
3698
3699   dw2_setup (objfile);
3700
3701   /* We don't need to consider type units here.
3702      This is only called for examining code, e.g. expand_line_sal.
3703      There can be an order of magnitude (or more) more type units
3704      than comp units, and we avoid them if we can.  */
3705
3706   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3707     {
3708       int j;
3709       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3710       struct quick_file_names *file_data;
3711
3712       /* We only need to look at symtabs not already expanded.  */
3713       if (per_cu->v.quick->symtab)
3714         continue;
3715
3716       file_data = dw2_get_file_names (per_cu);
3717       if (file_data == NULL)
3718         continue;
3719
3720       for (j = 0; j < file_data->num_file_names; ++j)
3721         {
3722           const char *this_fullname = file_data->file_names[j];
3723
3724           if (filename_cmp (this_fullname, fullname) == 0)
3725             {
3726               dw2_instantiate_symtab (per_cu);
3727               break;
3728             }
3729         }
3730     }
3731 }
3732
3733 static void
3734 dw2_map_matching_symbols (struct objfile *objfile,
3735                           const char * name, domain_enum namespace,
3736                           int global,
3737                           int (*callback) (struct block *,
3738                                            struct symbol *, void *),
3739                           void *data, symbol_compare_ftype *match,
3740                           symbol_compare_ftype *ordered_compare)
3741 {
3742   /* Currently unimplemented; used for Ada.  The function can be called if the
3743      current language is Ada for a non-Ada objfile using GNU index.  As Ada
3744      does not look for non-Ada symbols this function should just return.  */
3745 }
3746
3747 static void
3748 dw2_expand_symtabs_matching
3749   (struct objfile *objfile,
3750    int (*file_matcher) (const char *, void *, int basenames),
3751    int (*name_matcher) (const char *, void *),
3752    enum search_domain kind,
3753    void *data)
3754 {
3755   int i;
3756   offset_type iter;
3757   struct mapped_index *index;
3758
3759   dw2_setup (objfile);
3760
3761   /* index_table is NULL if OBJF_READNOW.  */
3762   if (!dwarf2_per_objfile->index_table)
3763     return;
3764   index = dwarf2_per_objfile->index_table;
3765
3766   if (file_matcher != NULL)
3767     {
3768       struct cleanup *cleanup;
3769       htab_t visited_found, visited_not_found;
3770
3771       visited_found = htab_create_alloc (10,
3772                                          htab_hash_pointer, htab_eq_pointer,
3773                                          NULL, xcalloc, xfree);
3774       cleanup = make_cleanup_htab_delete (visited_found);
3775       visited_not_found = htab_create_alloc (10,
3776                                              htab_hash_pointer, htab_eq_pointer,
3777                                              NULL, xcalloc, xfree);
3778       make_cleanup_htab_delete (visited_not_found);
3779
3780       /* The rule is CUs specify all the files, including those used by
3781          any TU, so there's no need to scan TUs here.  */
3782
3783       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3784         {
3785           int j;
3786           struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
3787           struct quick_file_names *file_data;
3788           void **slot;
3789
3790           per_cu->v.quick->mark = 0;
3791
3792           /* We only need to look at symtabs not already expanded.  */
3793           if (per_cu->v.quick->symtab)
3794             continue;
3795
3796           file_data = dw2_get_file_names (per_cu);
3797           if (file_data == NULL)
3798             continue;
3799
3800           if (htab_find (visited_not_found, file_data) != NULL)
3801             continue;
3802           else if (htab_find (visited_found, file_data) != NULL)
3803             {
3804               per_cu->v.quick->mark = 1;
3805               continue;
3806             }
3807
3808           for (j = 0; j < file_data->num_file_names; ++j)
3809             {
3810               const char *this_real_name;
3811
3812               if (file_matcher (file_data->file_names[j], data, 0))
3813                 {
3814                   per_cu->v.quick->mark = 1;
3815                   break;
3816                 }
3817
3818               /* Before we invoke realpath, which can get expensive when many
3819                  files are involved, do a quick comparison of the basenames.  */
3820               if (!basenames_may_differ
3821                   && !file_matcher (lbasename (file_data->file_names[j]),
3822                                     data, 1))
3823                 continue;
3824
3825               this_real_name = dw2_get_real_path (objfile, file_data, j);
3826               if (file_matcher (this_real_name, data, 0))
3827                 {
3828                   per_cu->v.quick->mark = 1;
3829                   break;
3830                 }
3831             }
3832
3833           slot = htab_find_slot (per_cu->v.quick->mark
3834                                  ? visited_found
3835                                  : visited_not_found,
3836                                  file_data, INSERT);
3837           *slot = file_data;
3838         }
3839
3840       do_cleanups (cleanup);
3841     }
3842
3843   for (iter = 0; iter < index->symbol_table_slots; ++iter)
3844     {
3845       offset_type idx = 2 * iter;
3846       const char *name;
3847       offset_type *vec, vec_len, vec_idx;
3848
3849       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
3850         continue;
3851
3852       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
3853
3854       if (! (*name_matcher) (name, data))
3855         continue;
3856
3857       /* The name was matched, now expand corresponding CUs that were
3858          marked.  */
3859       vec = (offset_type *) (index->constant_pool
3860                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
3861       vec_len = MAYBE_SWAP (vec[0]);
3862       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
3863         {
3864           struct dwarf2_per_cu_data *per_cu;
3865           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
3866           gdb_index_symbol_kind symbol_kind =
3867             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3868           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3869           /* Only check the symbol attributes if they're present.
3870              Indices prior to version 7 don't record them,
3871              and indices >= 7 may elide them for certain symbols
3872              (gold does this).  */
3873           int attrs_valid =
3874             (index->version >= 7
3875              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3876
3877           /* Only check the symbol's kind if it has one.  */
3878           if (attrs_valid)
3879             {
3880               switch (kind)
3881                 {
3882                 case VARIABLES_DOMAIN:
3883                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
3884                     continue;
3885                   break;
3886                 case FUNCTIONS_DOMAIN:
3887                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
3888                     continue;
3889                   break;
3890                 case TYPES_DOMAIN:
3891                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3892                     continue;
3893                   break;
3894                 default:
3895                   break;
3896                 }
3897             }
3898
3899           /* Don't crash on bad data.  */
3900           if (cu_index >= (dwarf2_per_objfile->n_comp_units
3901                            + dwarf2_per_objfile->n_type_units))
3902             {
3903               complaint (&symfile_complaints,
3904                          _(".gdb_index entry has bad CU index"
3905                            " [in module %s]"), objfile_name (objfile));
3906               continue;
3907             }
3908
3909           per_cu = dw2_get_cu (cu_index);
3910           if (file_matcher == NULL || per_cu->v.quick->mark)
3911             dw2_instantiate_symtab (per_cu);
3912         }
3913     }
3914 }
3915
3916 /* A helper for dw2_find_pc_sect_symtab which finds the most specific
3917    symtab.  */
3918
3919 static struct symtab *
3920 recursively_find_pc_sect_symtab (struct symtab *symtab, CORE_ADDR pc)
3921 {
3922   int i;
3923
3924   if (BLOCKVECTOR (symtab) != NULL
3925       && blockvector_contains_pc (BLOCKVECTOR (symtab), pc))
3926     return symtab;
3927
3928   if (symtab->includes == NULL)
3929     return NULL;
3930
3931   for (i = 0; symtab->includes[i]; ++i)
3932     {
3933       struct symtab *s = symtab->includes[i];
3934
3935       s = recursively_find_pc_sect_symtab (s, pc);
3936       if (s != NULL)
3937         return s;
3938     }
3939
3940   return NULL;
3941 }
3942
3943 static struct symtab *
3944 dw2_find_pc_sect_symtab (struct objfile *objfile,
3945                          struct minimal_symbol *msymbol,
3946                          CORE_ADDR pc,
3947                          struct obj_section *section,
3948                          int warn_if_readin)
3949 {
3950   struct dwarf2_per_cu_data *data;
3951   struct symtab *result;
3952
3953   dw2_setup (objfile);
3954
3955   if (!objfile->psymtabs_addrmap)
3956     return NULL;
3957
3958   data = addrmap_find (objfile->psymtabs_addrmap, pc);
3959   if (!data)
3960     return NULL;
3961
3962   if (warn_if_readin && data->v.quick->symtab)
3963     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
3964              paddress (get_objfile_arch (objfile), pc));
3965
3966   result = recursively_find_pc_sect_symtab (dw2_instantiate_symtab (data), pc);
3967   gdb_assert (result != NULL);
3968   return result;
3969 }
3970
3971 static void
3972 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
3973                           void *data, int need_fullname)
3974 {
3975   int i;
3976   struct cleanup *cleanup;
3977   htab_t visited = htab_create_alloc (10, htab_hash_pointer, htab_eq_pointer,
3978                                       NULL, xcalloc, xfree);
3979
3980   cleanup = make_cleanup_htab_delete (visited);
3981   dw2_setup (objfile);
3982
3983   /* The rule is CUs specify all the files, including those used by
3984      any TU, so there's no need to scan TUs here.
3985      We can ignore file names coming from already-expanded CUs.  */
3986
3987   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3988     {
3989       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3990
3991       if (per_cu->v.quick->symtab)
3992         {
3993           void **slot = htab_find_slot (visited, per_cu->v.quick->file_names,
3994                                         INSERT);
3995
3996           *slot = per_cu->v.quick->file_names;
3997         }
3998     }
3999
4000   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4001     {
4002       int j;
4003       struct dwarf2_per_cu_data *per_cu = dw2_get_primary_cu (i);
4004       struct quick_file_names *file_data;
4005       void **slot;
4006
4007       /* We only need to look at symtabs not already expanded.  */
4008       if (per_cu->v.quick->symtab)
4009         continue;
4010
4011       file_data = dw2_get_file_names (per_cu);
4012       if (file_data == NULL)
4013         continue;
4014
4015       slot = htab_find_slot (visited, file_data, INSERT);
4016       if (*slot)
4017         {
4018           /* Already visited.  */
4019           continue;
4020         }
4021       *slot = file_data;
4022
4023       for (j = 0; j < file_data->num_file_names; ++j)
4024         {
4025           const char *this_real_name;
4026
4027           if (need_fullname)
4028             this_real_name = dw2_get_real_path (objfile, file_data, j);
4029           else
4030             this_real_name = NULL;
4031           (*fun) (file_data->file_names[j], this_real_name, data);
4032         }
4033     }
4034
4035   do_cleanups (cleanup);
4036 }
4037
4038 static int
4039 dw2_has_symbols (struct objfile *objfile)
4040 {
4041   return 1;
4042 }
4043
4044 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4045 {
4046   dw2_has_symbols,
4047   dw2_find_last_source_symtab,
4048   dw2_forget_cached_source_info,
4049   dw2_map_symtabs_matching_filename,
4050   dw2_lookup_symbol,
4051   dw2_print_stats,
4052   dw2_dump,
4053   dw2_relocate,
4054   dw2_expand_symtabs_for_function,
4055   dw2_expand_all_symtabs,
4056   dw2_expand_symtabs_with_fullname,
4057   dw2_map_matching_symbols,
4058   dw2_expand_symtabs_matching,
4059   dw2_find_pc_sect_symtab,
4060   dw2_map_symbol_filenames
4061 };
4062
4063 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4064    file will use psymtabs, or 1 if using the GNU index.  */
4065
4066 int
4067 dwarf2_initialize_objfile (struct objfile *objfile)
4068 {
4069   /* If we're about to read full symbols, don't bother with the
4070      indices.  In this case we also don't care if some other debug
4071      format is making psymtabs, because they are all about to be
4072      expanded anyway.  */
4073   if ((objfile->flags & OBJF_READNOW))
4074     {
4075       int i;
4076
4077       dwarf2_per_objfile->using_index = 1;
4078       create_all_comp_units (objfile);
4079       create_all_type_units (objfile);
4080       dwarf2_per_objfile->quick_file_names_table =
4081         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4082
4083       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4084                        + dwarf2_per_objfile->n_type_units); ++i)
4085         {
4086           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4087
4088           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4089                                             struct dwarf2_per_cu_quick_data);
4090         }
4091
4092       /* Return 1 so that gdb sees the "quick" functions.  However,
4093          these functions will be no-ops because we will have expanded
4094          all symtabs.  */
4095       return 1;
4096     }
4097
4098   if (dwarf2_read_index (objfile))
4099     return 1;
4100
4101   return 0;
4102 }
4103
4104 \f
4105
4106 /* Build a partial symbol table.  */
4107
4108 void
4109 dwarf2_build_psymtabs (struct objfile *objfile)
4110 {
4111   volatile struct gdb_exception except;
4112
4113   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4114     {
4115       init_psymbol_list (objfile, 1024);
4116     }
4117
4118   TRY_CATCH (except, RETURN_MASK_ERROR)
4119     {
4120       /* This isn't really ideal: all the data we allocate on the
4121          objfile's obstack is still uselessly kept around.  However,
4122          freeing it seems unsafe.  */
4123       struct cleanup *cleanups = make_cleanup_discard_psymtabs (objfile);
4124
4125       dwarf2_build_psymtabs_hard (objfile);
4126       discard_cleanups (cleanups);
4127     }
4128   if (except.reason < 0)
4129     exception_print (gdb_stderr, except);
4130 }
4131
4132 /* Return the total length of the CU described by HEADER.  */
4133
4134 static unsigned int
4135 get_cu_length (const struct comp_unit_head *header)
4136 {
4137   return header->initial_length_size + header->length;
4138 }
4139
4140 /* Return TRUE if OFFSET is within CU_HEADER.  */
4141
4142 static inline int
4143 offset_in_cu_p (const struct comp_unit_head *cu_header, sect_offset offset)
4144 {
4145   sect_offset bottom = { cu_header->offset.sect_off };
4146   sect_offset top = { cu_header->offset.sect_off + get_cu_length (cu_header) };
4147
4148   return (offset.sect_off >= bottom.sect_off && offset.sect_off < top.sect_off);
4149 }
4150
4151 /* Find the base address of the compilation unit for range lists and
4152    location lists.  It will normally be specified by DW_AT_low_pc.
4153    In DWARF-3 draft 4, the base address could be overridden by
4154    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4155    compilation units with discontinuous ranges.  */
4156
4157 static void
4158 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4159 {
4160   struct attribute *attr;
4161
4162   cu->base_known = 0;
4163   cu->base_address = 0;
4164
4165   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4166   if (attr)
4167     {
4168       cu->base_address = DW_ADDR (attr);
4169       cu->base_known = 1;
4170     }
4171   else
4172     {
4173       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4174       if (attr)
4175         {
4176           cu->base_address = DW_ADDR (attr);
4177           cu->base_known = 1;
4178         }
4179     }
4180 }
4181
4182 /* Read in the comp unit header information from the debug_info at info_ptr.
4183    NOTE: This leaves members offset, first_die_offset to be filled in
4184    by the caller.  */
4185
4186 static const gdb_byte *
4187 read_comp_unit_head (struct comp_unit_head *cu_header,
4188                      const gdb_byte *info_ptr, bfd *abfd)
4189 {
4190   int signed_addr;
4191   unsigned int bytes_read;
4192
4193   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4194   cu_header->initial_length_size = bytes_read;
4195   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4196   info_ptr += bytes_read;
4197   cu_header->version = read_2_bytes (abfd, info_ptr);
4198   info_ptr += 2;
4199   cu_header->abbrev_offset.sect_off = read_offset (abfd, info_ptr, cu_header,
4200                                              &bytes_read);
4201   info_ptr += bytes_read;
4202   cu_header->addr_size = read_1_byte (abfd, info_ptr);
4203   info_ptr += 1;
4204   signed_addr = bfd_get_sign_extend_vma (abfd);
4205   if (signed_addr < 0)
4206     internal_error (__FILE__, __LINE__,
4207                     _("read_comp_unit_head: dwarf from non elf file"));
4208   cu_header->signed_addr_p = signed_addr;
4209
4210   return info_ptr;
4211 }
4212
4213 /* Helper function that returns the proper abbrev section for
4214    THIS_CU.  */
4215
4216 static struct dwarf2_section_info *
4217 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4218 {
4219   struct dwarf2_section_info *abbrev;
4220
4221   if (this_cu->is_dwz)
4222     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4223   else
4224     abbrev = &dwarf2_per_objfile->abbrev;
4225
4226   return abbrev;
4227 }
4228
4229 /* Subroutine of read_and_check_comp_unit_head and
4230    read_and_check_type_unit_head to simplify them.
4231    Perform various error checking on the header.  */
4232
4233 static void
4234 error_check_comp_unit_head (struct comp_unit_head *header,
4235                             struct dwarf2_section_info *section,
4236                             struct dwarf2_section_info *abbrev_section)
4237 {
4238   bfd *abfd = get_section_bfd_owner (section);
4239   const char *filename = get_section_file_name (section);
4240
4241   if (header->version != 2 && header->version != 3 && header->version != 4)
4242     error (_("Dwarf Error: wrong version in compilation unit header "
4243            "(is %d, should be 2, 3, or 4) [in module %s]"), header->version,
4244            filename);
4245
4246   if (header->abbrev_offset.sect_off
4247       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4248     error (_("Dwarf Error: bad offset (0x%lx) in compilation unit header "
4249            "(offset 0x%lx + 6) [in module %s]"),
4250            (long) header->abbrev_offset.sect_off, (long) header->offset.sect_off,
4251            filename);
4252
4253   /* Cast to unsigned long to use 64-bit arithmetic when possible to
4254      avoid potential 32-bit overflow.  */
4255   if (((unsigned long) header->offset.sect_off + get_cu_length (header))
4256       > section->size)
4257     error (_("Dwarf Error: bad length (0x%lx) in compilation unit header "
4258            "(offset 0x%lx + 0) [in module %s]"),
4259            (long) header->length, (long) header->offset.sect_off,
4260            filename);
4261 }
4262
4263 /* Read in a CU/TU header and perform some basic error checking.
4264    The contents of the header are stored in HEADER.
4265    The result is a pointer to the start of the first DIE.  */
4266
4267 static const gdb_byte *
4268 read_and_check_comp_unit_head (struct comp_unit_head *header,
4269                                struct dwarf2_section_info *section,
4270                                struct dwarf2_section_info *abbrev_section,
4271                                const gdb_byte *info_ptr,
4272                                int is_debug_types_section)
4273 {
4274   const gdb_byte *beg_of_comp_unit = info_ptr;
4275   bfd *abfd = get_section_bfd_owner (section);
4276
4277   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4278
4279   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4280
4281   /* If we're reading a type unit, skip over the signature and
4282      type_offset fields.  */
4283   if (is_debug_types_section)
4284     info_ptr += 8 /*signature*/ + header->offset_size;
4285
4286   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4287
4288   error_check_comp_unit_head (header, section, abbrev_section);
4289
4290   return info_ptr;
4291 }
4292
4293 /* Read in the types comp unit header information from .debug_types entry at
4294    types_ptr.  The result is a pointer to one past the end of the header.  */
4295
4296 static const gdb_byte *
4297 read_and_check_type_unit_head (struct comp_unit_head *header,
4298                                struct dwarf2_section_info *section,
4299                                struct dwarf2_section_info *abbrev_section,
4300                                const gdb_byte *info_ptr,
4301                                ULONGEST *signature,
4302                                cu_offset *type_offset_in_tu)
4303 {
4304   const gdb_byte *beg_of_comp_unit = info_ptr;
4305   bfd *abfd = get_section_bfd_owner (section);
4306
4307   header->offset.sect_off = beg_of_comp_unit - section->buffer;
4308
4309   info_ptr = read_comp_unit_head (header, info_ptr, abfd);
4310
4311   /* If we're reading a type unit, skip over the signature and
4312      type_offset fields.  */
4313   if (signature != NULL)
4314     *signature = read_8_bytes (abfd, info_ptr);
4315   info_ptr += 8;
4316   if (type_offset_in_tu != NULL)
4317     type_offset_in_tu->cu_off = read_offset_1 (abfd, info_ptr,
4318                                                header->offset_size);
4319   info_ptr += header->offset_size;
4320
4321   header->first_die_offset.cu_off = info_ptr - beg_of_comp_unit;
4322
4323   error_check_comp_unit_head (header, section, abbrev_section);
4324
4325   return info_ptr;
4326 }
4327
4328 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4329
4330 static sect_offset
4331 read_abbrev_offset (struct dwarf2_section_info *section,
4332                     sect_offset offset)
4333 {
4334   bfd *abfd = get_section_bfd_owner (section);
4335   const gdb_byte *info_ptr;
4336   unsigned int length, initial_length_size, offset_size;
4337   sect_offset abbrev_offset;
4338
4339   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4340   info_ptr = section->buffer + offset.sect_off;
4341   length = read_initial_length (abfd, info_ptr, &initial_length_size);
4342   offset_size = initial_length_size == 4 ? 4 : 8;
4343   info_ptr += initial_length_size + 2 /*version*/;
4344   abbrev_offset.sect_off = read_offset_1 (abfd, info_ptr, offset_size);
4345   return abbrev_offset;
4346 }
4347
4348 /* Allocate a new partial symtab for file named NAME and mark this new
4349    partial symtab as being an include of PST.  */
4350
4351 static void
4352 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4353                                struct objfile *objfile)
4354 {
4355   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4356
4357   if (!IS_ABSOLUTE_PATH (subpst->filename))
4358     {
4359       /* It shares objfile->objfile_obstack.  */
4360       subpst->dirname = pst->dirname;
4361     }
4362
4363   subpst->section_offsets = pst->section_offsets;
4364   subpst->textlow = 0;
4365   subpst->texthigh = 0;
4366
4367   subpst->dependencies = (struct partial_symtab **)
4368     obstack_alloc (&objfile->objfile_obstack,
4369                    sizeof (struct partial_symtab *));
4370   subpst->dependencies[0] = pst;
4371   subpst->number_of_dependencies = 1;
4372
4373   subpst->globals_offset = 0;
4374   subpst->n_global_syms = 0;
4375   subpst->statics_offset = 0;
4376   subpst->n_static_syms = 0;
4377   subpst->symtab = NULL;
4378   subpst->read_symtab = pst->read_symtab;
4379   subpst->readin = 0;
4380
4381   /* No private part is necessary for include psymtabs.  This property
4382      can be used to differentiate between such include psymtabs and
4383      the regular ones.  */
4384   subpst->read_symtab_private = NULL;
4385 }
4386
4387 /* Read the Line Number Program data and extract the list of files
4388    included by the source file represented by PST.  Build an include
4389    partial symtab for each of these included files.  */
4390
4391 static void
4392 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4393                                struct die_info *die,
4394                                struct partial_symtab *pst)
4395 {
4396   struct line_header *lh = NULL;
4397   struct attribute *attr;
4398
4399   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4400   if (attr)
4401     lh = dwarf_decode_line_header (DW_UNSND (attr), cu);
4402   if (lh == NULL)
4403     return;  /* No linetable, so no includes.  */
4404
4405   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4406   dwarf_decode_lines (lh, pst->dirname, cu, pst, 1);
4407
4408   free_line_header (lh);
4409 }
4410
4411 static hashval_t
4412 hash_signatured_type (const void *item)
4413 {
4414   const struct signatured_type *sig_type = item;
4415
4416   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4417   return sig_type->signature;
4418 }
4419
4420 static int
4421 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4422 {
4423   const struct signatured_type *lhs = item_lhs;
4424   const struct signatured_type *rhs = item_rhs;
4425
4426   return lhs->signature == rhs->signature;
4427 }
4428
4429 /* Allocate a hash table for signatured types.  */
4430
4431 static htab_t
4432 allocate_signatured_type_table (struct objfile *objfile)
4433 {
4434   return htab_create_alloc_ex (41,
4435                                hash_signatured_type,
4436                                eq_signatured_type,
4437                                NULL,
4438                                &objfile->objfile_obstack,
4439                                hashtab_obstack_allocate,
4440                                dummy_obstack_deallocate);
4441 }
4442
4443 /* A helper function to add a signatured type CU to a table.  */
4444
4445 static int
4446 add_signatured_type_cu_to_table (void **slot, void *datum)
4447 {
4448   struct signatured_type *sigt = *slot;
4449   struct signatured_type ***datap = datum;
4450
4451   **datap = sigt;
4452   ++*datap;
4453
4454   return 1;
4455 }
4456
4457 /* Create the hash table of all entries in the .debug_types
4458    (or .debug_types.dwo) section(s).
4459    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4460    otherwise it is NULL.
4461
4462    The result is a pointer to the hash table or NULL if there are no types.
4463
4464    Note: This function processes DWO files only, not DWP files.  */
4465
4466 static htab_t
4467 create_debug_types_hash_table (struct dwo_file *dwo_file,
4468                                VEC (dwarf2_section_info_def) *types)
4469 {
4470   struct objfile *objfile = dwarf2_per_objfile->objfile;
4471   htab_t types_htab = NULL;
4472   int ix;
4473   struct dwarf2_section_info *section;
4474   struct dwarf2_section_info *abbrev_section;
4475
4476   if (VEC_empty (dwarf2_section_info_def, types))
4477     return NULL;
4478
4479   abbrev_section = (dwo_file != NULL
4480                     ? &dwo_file->sections.abbrev
4481                     : &dwarf2_per_objfile->abbrev);
4482
4483   if (dwarf2_read_debug)
4484     fprintf_unfiltered (gdb_stdlog, "Reading .debug_types%s for %s:\n",
4485                         dwo_file ? ".dwo" : "",
4486                         get_section_file_name (abbrev_section));
4487
4488   for (ix = 0;
4489        VEC_iterate (dwarf2_section_info_def, types, ix, section);
4490        ++ix)
4491     {
4492       bfd *abfd;
4493       const gdb_byte *info_ptr, *end_ptr;
4494
4495       dwarf2_read_section (objfile, section);
4496       info_ptr = section->buffer;
4497
4498       if (info_ptr == NULL)
4499         continue;
4500
4501       /* We can't set abfd until now because the section may be empty or
4502          not present, in which case the bfd is unknown.  */
4503       abfd = get_section_bfd_owner (section);
4504
4505       /* We don't use init_cutu_and_read_dies_simple, or some such, here
4506          because we don't need to read any dies: the signature is in the
4507          header.  */
4508
4509       end_ptr = info_ptr + section->size;
4510       while (info_ptr < end_ptr)
4511         {
4512           sect_offset offset;
4513           cu_offset type_offset_in_tu;
4514           ULONGEST signature;
4515           struct signatured_type *sig_type;
4516           struct dwo_unit *dwo_tu;
4517           void **slot;
4518           const gdb_byte *ptr = info_ptr;
4519           struct comp_unit_head header;
4520           unsigned int length;
4521
4522           offset.sect_off = ptr - section->buffer;
4523
4524           /* We need to read the type's signature in order to build the hash
4525              table, but we don't need anything else just yet.  */
4526
4527           ptr = read_and_check_type_unit_head (&header, section,
4528                                                abbrev_section, ptr,
4529                                                &signature, &type_offset_in_tu);
4530
4531           length = get_cu_length (&header);
4532
4533           /* Skip dummy type units.  */
4534           if (ptr >= info_ptr + length
4535               || peek_abbrev_code (abfd, ptr) == 0)
4536             {
4537               info_ptr += length;
4538               continue;
4539             }
4540
4541           if (types_htab == NULL)
4542             {
4543               if (dwo_file)
4544                 types_htab = allocate_dwo_unit_table (objfile);
4545               else
4546                 types_htab = allocate_signatured_type_table (objfile);
4547             }
4548
4549           if (dwo_file)
4550             {
4551               sig_type = NULL;
4552               dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4553                                        struct dwo_unit);
4554               dwo_tu->dwo_file = dwo_file;
4555               dwo_tu->signature = signature;
4556               dwo_tu->type_offset_in_tu = type_offset_in_tu;
4557               dwo_tu->section = section;
4558               dwo_tu->offset = offset;
4559               dwo_tu->length = length;
4560             }
4561           else
4562             {
4563               /* N.B.: type_offset is not usable if this type uses a DWO file.
4564                  The real type_offset is in the DWO file.  */
4565               dwo_tu = NULL;
4566               sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4567                                          struct signatured_type);
4568               sig_type->signature = signature;
4569               sig_type->type_offset_in_tu = type_offset_in_tu;
4570               sig_type->per_cu.objfile = objfile;
4571               sig_type->per_cu.is_debug_types = 1;
4572               sig_type->per_cu.section = section;
4573               sig_type->per_cu.offset = offset;
4574               sig_type->per_cu.length = length;
4575             }
4576
4577           slot = htab_find_slot (types_htab,
4578                                  dwo_file ? (void*) dwo_tu : (void *) sig_type,
4579                                  INSERT);
4580           gdb_assert (slot != NULL);
4581           if (*slot != NULL)
4582             {
4583               sect_offset dup_offset;
4584
4585               if (dwo_file)
4586                 {
4587                   const struct dwo_unit *dup_tu = *slot;
4588
4589                   dup_offset = dup_tu->offset;
4590                 }
4591               else
4592                 {
4593                   const struct signatured_type *dup_tu = *slot;
4594
4595                   dup_offset = dup_tu->per_cu.offset;
4596                 }
4597
4598               complaint (&symfile_complaints,
4599                          _("debug type entry at offset 0x%x is duplicate to"
4600                            " the entry at offset 0x%x, signature %s"),
4601                          offset.sect_off, dup_offset.sect_off,
4602                          hex_string (signature));
4603             }
4604           *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4605
4606           if (dwarf2_read_debug)
4607             fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4608                                 offset.sect_off,
4609                                 hex_string (signature));
4610
4611           info_ptr += length;
4612         }
4613     }
4614
4615   return types_htab;
4616 }
4617
4618 /* Create the hash table of all entries in the .debug_types section,
4619    and initialize all_type_units.
4620    The result is zero if there is an error (e.g. missing .debug_types section),
4621    otherwise non-zero.  */
4622
4623 static int
4624 create_all_type_units (struct objfile *objfile)
4625 {
4626   htab_t types_htab;
4627   struct signatured_type **iter;
4628
4629   types_htab = create_debug_types_hash_table (NULL, dwarf2_per_objfile->types);
4630   if (types_htab == NULL)
4631     {
4632       dwarf2_per_objfile->signatured_types = NULL;
4633       return 0;
4634     }
4635
4636   dwarf2_per_objfile->signatured_types = types_htab;
4637
4638   dwarf2_per_objfile->n_type_units = htab_elements (types_htab);
4639   dwarf2_per_objfile->all_type_units
4640     = xmalloc (dwarf2_per_objfile->n_type_units
4641                * sizeof (struct signatured_type *));
4642   iter = &dwarf2_per_objfile->all_type_units[0];
4643   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
4644   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
4645               == dwarf2_per_objfile->n_type_units);
4646
4647   return 1;
4648 }
4649
4650 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
4651    Fill in SIG_ENTRY with DWO_ENTRY.  */
4652
4653 static void
4654 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
4655                                   struct signatured_type *sig_entry,
4656                                   struct dwo_unit *dwo_entry)
4657 {
4658   /* Make sure we're not clobbering something we don't expect to.  */
4659   gdb_assert (! sig_entry->per_cu.queued);
4660   gdb_assert (sig_entry->per_cu.cu == NULL);
4661   gdb_assert (sig_entry->per_cu.v.quick != NULL);
4662   gdb_assert (sig_entry->per_cu.v.quick->symtab == NULL);
4663   gdb_assert (sig_entry->signature == dwo_entry->signature);
4664   gdb_assert (sig_entry->type_offset_in_section.sect_off == 0);
4665   gdb_assert (sig_entry->type_unit_group == NULL);
4666   gdb_assert (sig_entry->dwo_unit == NULL);
4667
4668   sig_entry->per_cu.section = dwo_entry->section;
4669   sig_entry->per_cu.offset = dwo_entry->offset;
4670   sig_entry->per_cu.length = dwo_entry->length;
4671   sig_entry->per_cu.reading_dwo_directly = 1;
4672   sig_entry->per_cu.objfile = objfile;
4673   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
4674   sig_entry->dwo_unit = dwo_entry;
4675 }
4676
4677 /* Subroutine of lookup_signatured_type.
4678    If we haven't read the TU yet, create the signatured_type data structure
4679    for a TU to be read in directly from a DWO file, bypassing the stub.
4680    This is the "Stay in DWO Optimization": When there is no DWP file and we're
4681    using .gdb_index, then when reading a CU we want to stay in the DWO file
4682    containing that CU.  Otherwise we could end up reading several other DWO
4683    files (due to comdat folding) to process the transitive closure of all the
4684    mentioned TUs, and that can be slow.  The current DWO file will have every
4685    type signature that it needs.
4686    We only do this for .gdb_index because in the psymtab case we already have
4687    to read all the DWOs to build the type unit groups.  */
4688
4689 static struct signatured_type *
4690 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4691 {
4692   struct objfile *objfile = dwarf2_per_objfile->objfile;
4693   struct dwo_file *dwo_file;
4694   struct dwo_unit find_dwo_entry, *dwo_entry;
4695   struct signatured_type find_sig_entry, *sig_entry;
4696
4697   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4698
4699   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
4700      dwo_unit of the TU itself.  */
4701   dwo_file = cu->dwo_unit->dwo_file;
4702
4703   /* We only ever need to read in one copy of a signatured type.
4704      Just use the global signatured_types array.  If this is the first time
4705      we're reading this type, replace the recorded data from .gdb_index with
4706      this TU.  */
4707
4708   if (dwarf2_per_objfile->signatured_types == NULL)
4709     return NULL;
4710   find_sig_entry.signature = sig;
4711   sig_entry = htab_find (dwarf2_per_objfile->signatured_types, &find_sig_entry);
4712   if (sig_entry == NULL)
4713     return NULL;
4714
4715   /* We can get here with the TU already read, *or* in the process of being
4716      read.  Don't reassign it if that's the case.  Also note that if the TU is
4717      already being read, it may not have come from a DWO, the program may be
4718      a mix of Fission-compiled code and non-Fission-compiled code.  */
4719   /* Have we already tried to read this TU?  */
4720   if (sig_entry->per_cu.tu_read)
4721     return sig_entry;
4722
4723   /* Ok, this is the first time we're reading this TU.  */
4724   if (dwo_file->tus == NULL)
4725     return NULL;
4726   find_dwo_entry.signature = sig;
4727   dwo_entry = htab_find (dwo_file->tus, &find_dwo_entry);
4728   if (dwo_entry == NULL)
4729     return NULL;
4730
4731   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4732   sig_entry->per_cu.tu_read = 1;
4733   return sig_entry;
4734 }
4735
4736 /* Subroutine of lookup_dwp_signatured_type.
4737    Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.  */
4738
4739 static struct signatured_type *
4740 add_type_unit (ULONGEST sig)
4741 {
4742   struct objfile *objfile = dwarf2_per_objfile->objfile;
4743   int n_type_units = dwarf2_per_objfile->n_type_units;
4744   struct signatured_type *sig_type;
4745   void **slot;
4746
4747   ++n_type_units;
4748   dwarf2_per_objfile->all_type_units =
4749     xrealloc (dwarf2_per_objfile->all_type_units,
4750               n_type_units * sizeof (struct signatured_type *));
4751   dwarf2_per_objfile->n_type_units = n_type_units;
4752   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4753                              struct signatured_type);
4754   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
4755   sig_type->signature = sig;
4756   sig_type->per_cu.is_debug_types = 1;
4757   sig_type->per_cu.v.quick =
4758     OBSTACK_ZALLOC (&objfile->objfile_obstack,
4759                     struct dwarf2_per_cu_quick_data);
4760   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
4761                          sig_type, INSERT);
4762   gdb_assert (*slot == NULL);
4763   *slot = sig_type;
4764   /* The rest of sig_type must be filled in by the caller.  */
4765   return sig_type;
4766 }
4767
4768 /* Subroutine of lookup_signatured_type.
4769    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
4770    then try the DWP file.
4771    Normally this "can't happen", but if there's a bug in signature
4772    generation and/or the DWP file is built incorrectly, it can happen.
4773    Using the type directly from the DWP file means we don't have the stub
4774    which has some useful attributes (e.g., DW_AT_comp_dir), but they're
4775    not critical.  [Eventually the stub may go away for type units anyway.]  */
4776
4777 static struct signatured_type *
4778 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4779 {
4780   struct objfile *objfile = dwarf2_per_objfile->objfile;
4781   struct dwp_file *dwp_file = get_dwp_file ();
4782   struct dwo_unit *dwo_entry;
4783   struct signatured_type find_sig_entry, *sig_entry;
4784
4785   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
4786   gdb_assert (dwp_file != NULL);
4787
4788   if (dwarf2_per_objfile->signatured_types != NULL)
4789     {
4790       find_sig_entry.signature = sig;
4791       sig_entry = htab_find (dwarf2_per_objfile->signatured_types,
4792                              &find_sig_entry);
4793       if (sig_entry != NULL)
4794         return sig_entry;
4795     }
4796
4797   /* This is the "shouldn't happen" case.
4798      Try the DWP file and hope for the best.  */
4799   if (dwp_file->tus == NULL)
4800     return NULL;
4801   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
4802                                       sig, 1 /* is_debug_types */);
4803   if (dwo_entry == NULL)
4804     return NULL;
4805
4806   sig_entry = add_type_unit (sig);
4807   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
4808
4809   /* The caller will signal a complaint if we return NULL.
4810      Here we don't return NULL but we still want to complain.  */
4811   complaint (&symfile_complaints,
4812              _("Bad type signature %s referenced by %s at 0x%x,"
4813                " coping by using copy in DWP [in module %s]"),
4814              hex_string (sig),
4815              cu->per_cu->is_debug_types ? "TU" : "CU",
4816              cu->per_cu->offset.sect_off,
4817              objfile_name (objfile));
4818
4819   return sig_entry;
4820 }
4821
4822 /* Lookup a signature based type for DW_FORM_ref_sig8.
4823    Returns NULL if signature SIG is not present in the table.
4824    It is up to the caller to complain about this.  */
4825
4826 static struct signatured_type *
4827 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
4828 {
4829   if (cu->dwo_unit
4830       && dwarf2_per_objfile->using_index)
4831     {
4832       /* We're in a DWO/DWP file, and we're using .gdb_index.
4833          These cases require special processing.  */
4834       if (get_dwp_file () == NULL)
4835         return lookup_dwo_signatured_type (cu, sig);
4836       else
4837         return lookup_dwp_signatured_type (cu, sig);
4838     }
4839   else
4840     {
4841       struct signatured_type find_entry, *entry;
4842
4843       if (dwarf2_per_objfile->signatured_types == NULL)
4844         return NULL;
4845       find_entry.signature = sig;
4846       entry = htab_find (dwarf2_per_objfile->signatured_types, &find_entry);
4847       return entry;
4848     }
4849 }
4850 \f
4851 /* Low level DIE reading support.  */
4852
4853 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
4854
4855 static void
4856 init_cu_die_reader (struct die_reader_specs *reader,
4857                     struct dwarf2_cu *cu,
4858                     struct dwarf2_section_info *section,
4859                     struct dwo_file *dwo_file)
4860 {
4861   gdb_assert (section->readin && section->buffer != NULL);
4862   reader->abfd = get_section_bfd_owner (section);
4863   reader->cu = cu;
4864   reader->dwo_file = dwo_file;
4865   reader->die_section = section;
4866   reader->buffer = section->buffer;
4867   reader->buffer_end = section->buffer + section->size;
4868   reader->comp_dir = NULL;
4869 }
4870
4871 /* Subroutine of init_cutu_and_read_dies to simplify it.
4872    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
4873    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
4874    already.
4875
4876    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
4877    from it to the DIE in the DWO.  If NULL we are skipping the stub.
4878    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
4879    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
4880    attribute of the referencing CU.  Exactly one of STUB_COMP_UNIT_DIE and
4881    COMP_DIR must be non-NULL.
4882    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
4883    are filled in with the info of the DIE from the DWO file.
4884    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
4885    provided an abbrev table to use.
4886    The result is non-zero if a valid (non-dummy) DIE was found.  */
4887
4888 static int
4889 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
4890                         struct dwo_unit *dwo_unit,
4891                         int abbrev_table_provided,
4892                         struct die_info *stub_comp_unit_die,
4893                         const char *stub_comp_dir,
4894                         struct die_reader_specs *result_reader,
4895                         const gdb_byte **result_info_ptr,
4896                         struct die_info **result_comp_unit_die,
4897                         int *result_has_children)
4898 {
4899   struct objfile *objfile = dwarf2_per_objfile->objfile;
4900   struct dwarf2_cu *cu = this_cu->cu;
4901   struct dwarf2_section_info *section;
4902   bfd *abfd;
4903   const gdb_byte *begin_info_ptr, *info_ptr;
4904   const char *comp_dir_string;
4905   ULONGEST signature; /* Or dwo_id.  */
4906   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
4907   int i,num_extra_attrs;
4908   struct dwarf2_section_info *dwo_abbrev_section;
4909   struct attribute *attr;
4910   struct attribute comp_dir_attr;
4911   struct die_info *comp_unit_die;
4912
4913   /* Both can't be provided.  */
4914   gdb_assert (! (stub_comp_unit_die && stub_comp_dir));
4915
4916   /* These attributes aren't processed until later:
4917      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
4918      However, the attribute is found in the stub which we won't have later.
4919      In order to not impose this complication on the rest of the code,
4920      we read them here and copy them to the DWO CU/TU die.  */
4921
4922   stmt_list = NULL;
4923   low_pc = NULL;
4924   high_pc = NULL;
4925   ranges = NULL;
4926   comp_dir = NULL;
4927
4928   if (stub_comp_unit_die != NULL)
4929     {
4930       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
4931          DWO file.  */
4932       if (! this_cu->is_debug_types)
4933         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
4934       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
4935       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
4936       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
4937       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
4938
4939       /* There should be a DW_AT_addr_base attribute here (if needed).
4940          We need the value before we can process DW_FORM_GNU_addr_index.  */
4941       cu->addr_base = 0;
4942       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
4943       if (attr)
4944         cu->addr_base = DW_UNSND (attr);
4945
4946       /* There should be a DW_AT_ranges_base attribute here (if needed).
4947          We need the value before we can process DW_AT_ranges.  */
4948       cu->ranges_base = 0;
4949       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
4950       if (attr)
4951         cu->ranges_base = DW_UNSND (attr);
4952     }
4953   else if (stub_comp_dir != NULL)
4954     {
4955       /* Reconstruct the comp_dir attribute to simplify the code below.  */
4956       comp_dir = (struct attribute *)
4957         obstack_alloc (&cu->comp_unit_obstack, sizeof (*comp_dir));
4958       comp_dir->name = DW_AT_comp_dir;
4959       comp_dir->form = DW_FORM_string;
4960       DW_STRING_IS_CANONICAL (comp_dir) = 0;
4961       DW_STRING (comp_dir) = stub_comp_dir;
4962     }
4963
4964   /* Set up for reading the DWO CU/TU.  */
4965   cu->dwo_unit = dwo_unit;
4966   section = dwo_unit->section;
4967   dwarf2_read_section (objfile, section);
4968   abfd = get_section_bfd_owner (section);
4969   begin_info_ptr = info_ptr = section->buffer + dwo_unit->offset.sect_off;
4970   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
4971   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
4972
4973   if (this_cu->is_debug_types)
4974     {
4975       ULONGEST header_signature;
4976       cu_offset type_offset_in_tu;
4977       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
4978
4979       info_ptr = read_and_check_type_unit_head (&cu->header, section,
4980                                                 dwo_abbrev_section,
4981                                                 info_ptr,
4982                                                 &header_signature,
4983                                                 &type_offset_in_tu);
4984       /* This is not an assert because it can be caused by bad debug info.  */
4985       if (sig_type->signature != header_signature)
4986         {
4987           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
4988                    " TU at offset 0x%x [in module %s]"),
4989                  hex_string (sig_type->signature),
4990                  hex_string (header_signature),
4991                  dwo_unit->offset.sect_off,
4992                  bfd_get_filename (abfd));
4993         }
4994       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
4995       /* For DWOs coming from DWP files, we don't know the CU length
4996          nor the type's offset in the TU until now.  */
4997       dwo_unit->length = get_cu_length (&cu->header);
4998       dwo_unit->type_offset_in_tu = type_offset_in_tu;
4999
5000       /* Establish the type offset that can be used to lookup the type.
5001          For DWO files, we don't know it until now.  */
5002       sig_type->type_offset_in_section.sect_off =
5003         dwo_unit->offset.sect_off + dwo_unit->type_offset_in_tu.cu_off;
5004     }
5005   else
5006     {
5007       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5008                                                 dwo_abbrev_section,
5009                                                 info_ptr, 0);
5010       gdb_assert (dwo_unit->offset.sect_off == cu->header.offset.sect_off);
5011       /* For DWOs coming from DWP files, we don't know the CU length
5012          until now.  */
5013       dwo_unit->length = get_cu_length (&cu->header);
5014     }
5015
5016   /* Replace the CU's original abbrev table with the DWO's.
5017      Reminder: We can't read the abbrev table until we've read the header.  */
5018   if (abbrev_table_provided)
5019     {
5020       /* Don't free the provided abbrev table, the caller of
5021          init_cutu_and_read_dies owns it.  */
5022       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5023       /* Ensure the DWO abbrev table gets freed.  */
5024       make_cleanup (dwarf2_free_abbrev_table, cu);
5025     }
5026   else
5027     {
5028       dwarf2_free_abbrev_table (cu);
5029       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5030       /* Leave any existing abbrev table cleanup as is.  */
5031     }
5032
5033   /* Read in the die, but leave space to copy over the attributes
5034      from the stub.  This has the benefit of simplifying the rest of
5035      the code - all the work to maintain the illusion of a single
5036      DW_TAG_{compile,type}_unit DIE is done here.  */
5037   num_extra_attrs = ((stmt_list != NULL)
5038                      + (low_pc != NULL)
5039                      + (high_pc != NULL)
5040                      + (ranges != NULL)
5041                      + (comp_dir != NULL));
5042   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5043                               result_has_children, num_extra_attrs);
5044
5045   /* Copy over the attributes from the stub to the DIE we just read in.  */
5046   comp_unit_die = *result_comp_unit_die;
5047   i = comp_unit_die->num_attrs;
5048   if (stmt_list != NULL)
5049     comp_unit_die->attrs[i++] = *stmt_list;
5050   if (low_pc != NULL)
5051     comp_unit_die->attrs[i++] = *low_pc;
5052   if (high_pc != NULL)
5053     comp_unit_die->attrs[i++] = *high_pc;
5054   if (ranges != NULL)
5055     comp_unit_die->attrs[i++] = *ranges;
5056   if (comp_dir != NULL)
5057     comp_unit_die->attrs[i++] = *comp_dir;
5058   comp_unit_die->num_attrs += num_extra_attrs;
5059
5060   if (dwarf2_die_debug)
5061     {
5062       fprintf_unfiltered (gdb_stdlog,
5063                           "Read die from %s@0x%x of %s:\n",
5064                           get_section_name (section),
5065                           (unsigned) (begin_info_ptr - section->buffer),
5066                           bfd_get_filename (abfd));
5067       dump_die (comp_unit_die, dwarf2_die_debug);
5068     }
5069
5070   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5071      TUs by skipping the stub and going directly to the entry in the DWO file.
5072      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5073      to get it via circuitous means.  Blech.  */
5074   if (comp_dir != NULL)
5075     result_reader->comp_dir = DW_STRING (comp_dir);
5076
5077   /* Skip dummy compilation units.  */
5078   if (info_ptr >= begin_info_ptr + dwo_unit->length
5079       || peek_abbrev_code (abfd, info_ptr) == 0)
5080     return 0;
5081
5082   *result_info_ptr = info_ptr;
5083   return 1;
5084 }
5085
5086 /* Subroutine of init_cutu_and_read_dies to simplify it.
5087    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5088    Returns NULL if the specified DWO unit cannot be found.  */
5089
5090 static struct dwo_unit *
5091 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5092                  struct die_info *comp_unit_die)
5093 {
5094   struct dwarf2_cu *cu = this_cu->cu;
5095   struct attribute *attr;
5096   ULONGEST signature;
5097   struct dwo_unit *dwo_unit;
5098   const char *comp_dir, *dwo_name;
5099
5100   gdb_assert (cu != NULL);
5101
5102   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5103   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5104   gdb_assert (attr != NULL);
5105   dwo_name = DW_STRING (attr);
5106   comp_dir = NULL;
5107   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5108   if (attr)
5109     comp_dir = DW_STRING (attr);
5110
5111   if (this_cu->is_debug_types)
5112     {
5113       struct signatured_type *sig_type;
5114
5115       /* Since this_cu is the first member of struct signatured_type,
5116          we can go from a pointer to one to a pointer to the other.  */
5117       sig_type = (struct signatured_type *) this_cu;
5118       signature = sig_type->signature;
5119       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5120     }
5121   else
5122     {
5123       struct attribute *attr;
5124
5125       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5126       if (! attr)
5127         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5128                  " [in module %s]"),
5129                dwo_name, objfile_name (this_cu->objfile));
5130       signature = DW_UNSND (attr);
5131       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5132                                        signature);
5133     }
5134
5135   return dwo_unit;
5136 }
5137
5138 /* Subroutine of init_cutu_and_read_dies to simplify it.
5139    Read a TU directly from a DWO file, bypassing the stub.  */
5140
5141 static void
5142 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu, int keep,
5143                            die_reader_func_ftype *die_reader_func,
5144                            void *data)
5145 {
5146   struct dwarf2_cu *cu;
5147   struct signatured_type *sig_type;
5148   struct cleanup *cleanups, *free_cu_cleanup;
5149   struct die_reader_specs reader;
5150   const gdb_byte *info_ptr;
5151   struct die_info *comp_unit_die;
5152   int has_children;
5153
5154   /* Verify we can do the following downcast, and that we have the
5155      data we need.  */
5156   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5157   sig_type = (struct signatured_type *) this_cu;
5158   gdb_assert (sig_type->dwo_unit != NULL);
5159
5160   cleanups = make_cleanup (null_cleanup, NULL);
5161
5162   gdb_assert (this_cu->cu == NULL);
5163   cu = xmalloc (sizeof (*cu));
5164   init_one_comp_unit (cu, this_cu);
5165   /* If an error occurs while loading, release our storage.  */
5166   free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5167
5168   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5169                               0 /* abbrev_table_provided */,
5170                               NULL /* stub_comp_unit_die */,
5171                               sig_type->dwo_unit->dwo_file->comp_dir,
5172                               &reader, &info_ptr,
5173                               &comp_unit_die, &has_children) == 0)
5174     {
5175       /* Dummy die.  */
5176       do_cleanups (cleanups);
5177       return;
5178     }
5179
5180   /* All the "real" work is done here.  */
5181   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5182
5183   /* This duplicates some code in init_cutu_and_read_dies,
5184      but the alternative is making the latter more complex.
5185      This function is only for the special case of using DWO files directly:
5186      no point in overly complicating the general case just to handle this.  */
5187   if (keep)
5188     {
5189       /* We've successfully allocated this compilation unit.  Let our
5190          caller clean it up when finished with it.  */
5191       discard_cleanups (free_cu_cleanup);
5192
5193       /* We can only discard free_cu_cleanup and all subsequent cleanups.
5194          So we have to manually free the abbrev table.  */
5195       dwarf2_free_abbrev_table (cu);
5196
5197       /* Link this CU into read_in_chain.  */
5198       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5199       dwarf2_per_objfile->read_in_chain = this_cu;
5200     }
5201   else
5202     do_cleanups (free_cu_cleanup);
5203
5204   do_cleanups (cleanups);
5205 }
5206
5207 /* Initialize a CU (or TU) and read its DIEs.
5208    If the CU defers to a DWO file, read the DWO file as well.
5209
5210    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5211    Otherwise the table specified in the comp unit header is read in and used.
5212    This is an optimization for when we already have the abbrev table.
5213
5214    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5215    Otherwise, a new CU is allocated with xmalloc.
5216
5217    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5218    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5219
5220    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5221    linker) then DIE_READER_FUNC will not get called.  */
5222
5223 static void
5224 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5225                          struct abbrev_table *abbrev_table,
5226                          int use_existing_cu, int keep,
5227                          die_reader_func_ftype *die_reader_func,
5228                          void *data)
5229 {
5230   struct objfile *objfile = dwarf2_per_objfile->objfile;
5231   struct dwarf2_section_info *section = this_cu->section;
5232   bfd *abfd = get_section_bfd_owner (section);
5233   struct dwarf2_cu *cu;
5234   const gdb_byte *begin_info_ptr, *info_ptr;
5235   struct die_reader_specs reader;
5236   struct die_info *comp_unit_die;
5237   int has_children;
5238   struct attribute *attr;
5239   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5240   struct signatured_type *sig_type = NULL;
5241   struct dwarf2_section_info *abbrev_section;
5242   /* Non-zero if CU currently points to a DWO file and we need to
5243      reread it.  When this happens we need to reread the skeleton die
5244      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5245   int rereading_dwo_cu = 0;
5246
5247   if (dwarf2_die_debug)
5248     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5249                         this_cu->is_debug_types ? "type" : "comp",
5250                         this_cu->offset.sect_off);
5251
5252   if (use_existing_cu)
5253     gdb_assert (keep);
5254
5255   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5256      file (instead of going through the stub), short-circuit all of this.  */
5257   if (this_cu->reading_dwo_directly)
5258     {
5259       /* Narrow down the scope of possibilities to have to understand.  */
5260       gdb_assert (this_cu->is_debug_types);
5261       gdb_assert (abbrev_table == NULL);
5262       gdb_assert (!use_existing_cu);
5263       init_tu_and_read_dwo_dies (this_cu, keep, die_reader_func, data);
5264       return;
5265     }
5266
5267   cleanups = make_cleanup (null_cleanup, NULL);
5268
5269   /* This is cheap if the section is already read in.  */
5270   dwarf2_read_section (objfile, section);
5271
5272   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5273
5274   abbrev_section = get_abbrev_section_for_cu (this_cu);
5275
5276   if (use_existing_cu && this_cu->cu != NULL)
5277     {
5278       cu = this_cu->cu;
5279
5280       /* If this CU is from a DWO file we need to start over, we need to
5281          refetch the attributes from the skeleton CU.
5282          This could be optimized by retrieving those attributes from when we
5283          were here the first time: the previous comp_unit_die was stored in
5284          comp_unit_obstack.  But there's no data yet that we need this
5285          optimization.  */
5286       if (cu->dwo_unit != NULL)
5287         rereading_dwo_cu = 1;
5288     }
5289   else
5290     {
5291       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5292       gdb_assert (this_cu->cu == NULL);
5293
5294       cu = xmalloc (sizeof (*cu));
5295       init_one_comp_unit (cu, this_cu);
5296
5297       /* If an error occurs while loading, release our storage.  */
5298       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5299     }
5300
5301   /* Get the header.  */
5302   if (cu->header.first_die_offset.cu_off != 0 && ! rereading_dwo_cu)
5303     {
5304       /* We already have the header, there's no need to read it in again.  */
5305       info_ptr += cu->header.first_die_offset.cu_off;
5306     }
5307   else
5308     {
5309       if (this_cu->is_debug_types)
5310         {
5311           ULONGEST signature;
5312           cu_offset type_offset_in_tu;
5313
5314           info_ptr = read_and_check_type_unit_head (&cu->header, section,
5315                                                     abbrev_section, info_ptr,
5316                                                     &signature,
5317                                                     &type_offset_in_tu);
5318
5319           /* Since per_cu is the first member of struct signatured_type,
5320              we can go from a pointer to one to a pointer to the other.  */
5321           sig_type = (struct signatured_type *) this_cu;
5322           gdb_assert (sig_type->signature == signature);
5323           gdb_assert (sig_type->type_offset_in_tu.cu_off
5324                       == type_offset_in_tu.cu_off);
5325           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5326
5327           /* LENGTH has not been set yet for type units if we're
5328              using .gdb_index.  */
5329           this_cu->length = get_cu_length (&cu->header);
5330
5331           /* Establish the type offset that can be used to lookup the type.  */
5332           sig_type->type_offset_in_section.sect_off =
5333             this_cu->offset.sect_off + sig_type->type_offset_in_tu.cu_off;
5334         }
5335       else
5336         {
5337           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5338                                                     abbrev_section,
5339                                                     info_ptr, 0);
5340
5341           gdb_assert (this_cu->offset.sect_off == cu->header.offset.sect_off);
5342           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5343         }
5344     }
5345
5346   /* Skip dummy compilation units.  */
5347   if (info_ptr >= begin_info_ptr + this_cu->length
5348       || peek_abbrev_code (abfd, info_ptr) == 0)
5349     {
5350       do_cleanups (cleanups);
5351       return;
5352     }
5353
5354   /* If we don't have them yet, read the abbrevs for this compilation unit.
5355      And if we need to read them now, make sure they're freed when we're
5356      done.  Note that it's important that if the CU had an abbrev table
5357      on entry we don't free it when we're done: Somewhere up the call stack
5358      it may be in use.  */
5359   if (abbrev_table != NULL)
5360     {
5361       gdb_assert (cu->abbrev_table == NULL);
5362       gdb_assert (cu->header.abbrev_offset.sect_off
5363                   == abbrev_table->offset.sect_off);
5364       cu->abbrev_table = abbrev_table;
5365     }
5366   else if (cu->abbrev_table == NULL)
5367     {
5368       dwarf2_read_abbrevs (cu, abbrev_section);
5369       make_cleanup (dwarf2_free_abbrev_table, cu);
5370     }
5371   else if (rereading_dwo_cu)
5372     {
5373       dwarf2_free_abbrev_table (cu);
5374       dwarf2_read_abbrevs (cu, abbrev_section);
5375     }
5376
5377   /* Read the top level CU/TU die.  */
5378   init_cu_die_reader (&reader, cu, section, NULL);
5379   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5380
5381   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5382      from the DWO file.
5383      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5384      DWO CU, that this test will fail (the attribute will not be present).  */
5385   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5386   if (attr)
5387     {
5388       struct dwo_unit *dwo_unit;
5389       struct die_info *dwo_comp_unit_die;
5390
5391       if (has_children)
5392         {
5393           complaint (&symfile_complaints,
5394                      _("compilation unit with DW_AT_GNU_dwo_name"
5395                        " has children (offset 0x%x) [in module %s]"),
5396                      this_cu->offset.sect_off, bfd_get_filename (abfd));
5397         }
5398       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5399       if (dwo_unit != NULL)
5400         {
5401           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5402                                       abbrev_table != NULL,
5403                                       comp_unit_die, NULL,
5404                                       &reader, &info_ptr,
5405                                       &dwo_comp_unit_die, &has_children) == 0)
5406             {
5407               /* Dummy die.  */
5408               do_cleanups (cleanups);
5409               return;
5410             }
5411           comp_unit_die = dwo_comp_unit_die;
5412         }
5413       else
5414         {
5415           /* Yikes, we couldn't find the rest of the DIE, we only have
5416              the stub.  A complaint has already been logged.  There's
5417              not much more we can do except pass on the stub DIE to
5418              die_reader_func.  We don't want to throw an error on bad
5419              debug info.  */
5420         }
5421     }
5422
5423   /* All of the above is setup for this call.  Yikes.  */
5424   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5425
5426   /* Done, clean up.  */
5427   if (free_cu_cleanup != NULL)
5428     {
5429       if (keep)
5430         {
5431           /* We've successfully allocated this compilation unit.  Let our
5432              caller clean it up when finished with it.  */
5433           discard_cleanups (free_cu_cleanup);
5434
5435           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5436              So we have to manually free the abbrev table.  */
5437           dwarf2_free_abbrev_table (cu);
5438
5439           /* Link this CU into read_in_chain.  */
5440           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5441           dwarf2_per_objfile->read_in_chain = this_cu;
5442         }
5443       else
5444         do_cleanups (free_cu_cleanup);
5445     }
5446
5447   do_cleanups (cleanups);
5448 }
5449
5450 /* Read CU/TU THIS_CU in section SECTION,
5451    but do not follow DW_AT_GNU_dwo_name if present.
5452    DWOP_FILE, if non-NULL, is the DWO/DWP file to read (the caller is assumed
5453    to have already done the lookup to find the DWO/DWP file).
5454
5455    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5456    THIS_CU->is_debug_types, but nothing else.
5457
5458    We fill in THIS_CU->length.
5459
5460    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5461    linker) then DIE_READER_FUNC will not get called.
5462
5463    THIS_CU->cu is always freed when done.
5464    This is done in order to not leave THIS_CU->cu in a state where we have
5465    to care whether it refers to the "main" CU or the DWO CU.  */
5466
5467 static void
5468 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5469                                    struct dwarf2_section_info *abbrev_section,
5470                                    struct dwo_file *dwo_file,
5471                                    die_reader_func_ftype *die_reader_func,
5472                                    void *data)
5473 {
5474   struct objfile *objfile = dwarf2_per_objfile->objfile;
5475   struct dwarf2_section_info *section = this_cu->section;
5476   bfd *abfd = get_section_bfd_owner (section);
5477   struct dwarf2_cu cu;
5478   const gdb_byte *begin_info_ptr, *info_ptr;
5479   struct die_reader_specs reader;
5480   struct cleanup *cleanups;
5481   struct die_info *comp_unit_die;
5482   int has_children;
5483
5484   if (dwarf2_die_debug)
5485     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5486                         this_cu->is_debug_types ? "type" : "comp",
5487                         this_cu->offset.sect_off);
5488
5489   gdb_assert (this_cu->cu == NULL);
5490
5491   /* This is cheap if the section is already read in.  */
5492   dwarf2_read_section (objfile, section);
5493
5494   init_one_comp_unit (&cu, this_cu);
5495
5496   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5497
5498   begin_info_ptr = info_ptr = section->buffer + this_cu->offset.sect_off;
5499   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5500                                             abbrev_section, info_ptr,
5501                                             this_cu->is_debug_types);
5502
5503   this_cu->length = get_cu_length (&cu.header);
5504
5505   /* Skip dummy compilation units.  */
5506   if (info_ptr >= begin_info_ptr + this_cu->length
5507       || peek_abbrev_code (abfd, info_ptr) == 0)
5508     {
5509       do_cleanups (cleanups);
5510       return;
5511     }
5512
5513   dwarf2_read_abbrevs (&cu, abbrev_section);
5514   make_cleanup (dwarf2_free_abbrev_table, &cu);
5515
5516   init_cu_die_reader (&reader, &cu, section, dwo_file);
5517   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5518
5519   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5520
5521   do_cleanups (cleanups);
5522 }
5523
5524 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5525    does not lookup the specified DWO file.
5526    This cannot be used to read DWO files.
5527
5528    THIS_CU->cu is always freed when done.
5529    This is done in order to not leave THIS_CU->cu in a state where we have
5530    to care whether it refers to the "main" CU or the DWO CU.
5531    We can revisit this if the data shows there's a performance issue.  */
5532
5533 static void
5534 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5535                                 die_reader_func_ftype *die_reader_func,
5536                                 void *data)
5537 {
5538   init_cutu_and_read_dies_no_follow (this_cu,
5539                                      get_abbrev_section_for_cu (this_cu),
5540                                      NULL,
5541                                      die_reader_func, data);
5542 }
5543 \f
5544 /* Type Unit Groups.
5545
5546    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5547    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5548    so that all types coming from the same compilation (.o file) are grouped
5549    together.  A future step could be to put the types in the same symtab as
5550    the CU the types ultimately came from.  */
5551
5552 static hashval_t
5553 hash_type_unit_group (const void *item)
5554 {
5555   const struct type_unit_group *tu_group = item;
5556
5557   return hash_stmt_list_entry (&tu_group->hash);
5558 }
5559
5560 static int
5561 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
5562 {
5563   const struct type_unit_group *lhs = item_lhs;
5564   const struct type_unit_group *rhs = item_rhs;
5565
5566   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
5567 }
5568
5569 /* Allocate a hash table for type unit groups.  */
5570
5571 static htab_t
5572 allocate_type_unit_groups_table (void)
5573 {
5574   return htab_create_alloc_ex (3,
5575                                hash_type_unit_group,
5576                                eq_type_unit_group,
5577                                NULL,
5578                                &dwarf2_per_objfile->objfile->objfile_obstack,
5579                                hashtab_obstack_allocate,
5580                                dummy_obstack_deallocate);
5581 }
5582
5583 /* Type units that don't have DW_AT_stmt_list are grouped into their own
5584    partial symtabs.  We combine several TUs per psymtab to not let the size
5585    of any one psymtab grow too big.  */
5586 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
5587 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
5588
5589 /* Helper routine for get_type_unit_group.
5590    Create the type_unit_group object used to hold one or more TUs.  */
5591
5592 static struct type_unit_group *
5593 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
5594 {
5595   struct objfile *objfile = dwarf2_per_objfile->objfile;
5596   struct dwarf2_per_cu_data *per_cu;
5597   struct type_unit_group *tu_group;
5598
5599   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5600                              struct type_unit_group);
5601   per_cu = &tu_group->per_cu;
5602   per_cu->objfile = objfile;
5603
5604   if (dwarf2_per_objfile->using_index)
5605     {
5606       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5607                                         struct dwarf2_per_cu_quick_data);
5608     }
5609   else
5610     {
5611       unsigned int line_offset = line_offset_struct.sect_off;
5612       struct partial_symtab *pst;
5613       char *name;
5614
5615       /* Give the symtab a useful name for debug purposes.  */
5616       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
5617         name = xstrprintf ("<type_units_%d>",
5618                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
5619       else
5620         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
5621
5622       pst = create_partial_symtab (per_cu, name);
5623       pst->anonymous = 1;
5624
5625       xfree (name);
5626     }
5627
5628   tu_group->hash.dwo_unit = cu->dwo_unit;
5629   tu_group->hash.line_offset = line_offset_struct;
5630
5631   return tu_group;
5632 }
5633
5634 /* Look up the type_unit_group for type unit CU, and create it if necessary.
5635    STMT_LIST is a DW_AT_stmt_list attribute.  */
5636
5637 static struct type_unit_group *
5638 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
5639 {
5640   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5641   struct type_unit_group *tu_group;
5642   void **slot;
5643   unsigned int line_offset;
5644   struct type_unit_group type_unit_group_for_lookup;
5645
5646   if (dwarf2_per_objfile->type_unit_groups == NULL)
5647     {
5648       dwarf2_per_objfile->type_unit_groups =
5649         allocate_type_unit_groups_table ();
5650     }
5651
5652   /* Do we need to create a new group, or can we use an existing one?  */
5653
5654   if (stmt_list)
5655     {
5656       line_offset = DW_UNSND (stmt_list);
5657       ++tu_stats->nr_symtab_sharers;
5658     }
5659   else
5660     {
5661       /* Ugh, no stmt_list.  Rare, but we have to handle it.
5662          We can do various things here like create one group per TU or
5663          spread them over multiple groups to split up the expansion work.
5664          To avoid worst case scenarios (too many groups or too large groups)
5665          we, umm, group them in bunches.  */
5666       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
5667                      | (tu_stats->nr_stmt_less_type_units
5668                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
5669       ++tu_stats->nr_stmt_less_type_units;
5670     }
5671
5672   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
5673   type_unit_group_for_lookup.hash.line_offset.sect_off = line_offset;
5674   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
5675                          &type_unit_group_for_lookup, INSERT);
5676   if (*slot != NULL)
5677     {
5678       tu_group = *slot;
5679       gdb_assert (tu_group != NULL);
5680     }
5681   else
5682     {
5683       sect_offset line_offset_struct;
5684
5685       line_offset_struct.sect_off = line_offset;
5686       tu_group = create_type_unit_group (cu, line_offset_struct);
5687       *slot = tu_group;
5688       ++tu_stats->nr_symtabs;
5689     }
5690
5691   return tu_group;
5692 }
5693
5694 /* Struct used to sort TUs by their abbreviation table offset.  */
5695
5696 struct tu_abbrev_offset
5697 {
5698   struct signatured_type *sig_type;
5699   sect_offset abbrev_offset;
5700 };
5701
5702 /* Helper routine for build_type_unit_groups, passed to qsort.  */
5703
5704 static int
5705 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
5706 {
5707   const struct tu_abbrev_offset * const *a = ap;
5708   const struct tu_abbrev_offset * const *b = bp;
5709   unsigned int aoff = (*a)->abbrev_offset.sect_off;
5710   unsigned int boff = (*b)->abbrev_offset.sect_off;
5711
5712   return (aoff > boff) - (aoff < boff);
5713 }
5714
5715 /* A helper function to add a type_unit_group to a table.  */
5716
5717 static int
5718 add_type_unit_group_to_table (void **slot, void *datum)
5719 {
5720   struct type_unit_group *tu_group = *slot;
5721   struct type_unit_group ***datap = datum;
5722
5723   **datap = tu_group;
5724   ++*datap;
5725
5726   return 1;
5727 }
5728
5729 /* Efficiently read all the type units, calling init_cutu_and_read_dies on
5730    each one passing FUNC,DATA.
5731
5732    The efficiency is because we sort TUs by the abbrev table they use and
5733    only read each abbrev table once.  In one program there are 200K TUs
5734    sharing 8K abbrev tables.
5735
5736    The main purpose of this function is to support building the
5737    dwarf2_per_objfile->type_unit_groups table.
5738    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
5739    can collapse the search space by grouping them by stmt_list.
5740    The savings can be significant, in the same program from above the 200K TUs
5741    share 8K stmt_list tables.
5742
5743    FUNC is expected to call get_type_unit_group, which will create the
5744    struct type_unit_group if necessary and add it to
5745    dwarf2_per_objfile->type_unit_groups.  */
5746
5747 static void
5748 build_type_unit_groups (die_reader_func_ftype *func, void *data)
5749 {
5750   struct objfile *objfile = dwarf2_per_objfile->objfile;
5751   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
5752   struct cleanup *cleanups;
5753   struct abbrev_table *abbrev_table;
5754   sect_offset abbrev_offset;
5755   struct tu_abbrev_offset *sorted_by_abbrev;
5756   struct type_unit_group **iter;
5757   int i;
5758
5759   /* It's up to the caller to not call us multiple times.  */
5760   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
5761
5762   if (dwarf2_per_objfile->n_type_units == 0)
5763     return;
5764
5765   /* TUs typically share abbrev tables, and there can be way more TUs than
5766      abbrev tables.  Sort by abbrev table to reduce the number of times we
5767      read each abbrev table in.
5768      Alternatives are to punt or to maintain a cache of abbrev tables.
5769      This is simpler and efficient enough for now.
5770
5771      Later we group TUs by their DW_AT_stmt_list value (as this defines the
5772      symtab to use).  Typically TUs with the same abbrev offset have the same
5773      stmt_list value too so in practice this should work well.
5774
5775      The basic algorithm here is:
5776
5777       sort TUs by abbrev table
5778       for each TU with same abbrev table:
5779         read abbrev table if first user
5780         read TU top level DIE
5781           [IWBN if DWO skeletons had DW_AT_stmt_list]
5782         call FUNC  */
5783
5784   if (dwarf2_read_debug)
5785     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
5786
5787   /* Sort in a separate table to maintain the order of all_type_units
5788      for .gdb_index: TU indices directly index all_type_units.  */
5789   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
5790                               dwarf2_per_objfile->n_type_units);
5791   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5792     {
5793       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
5794
5795       sorted_by_abbrev[i].sig_type = sig_type;
5796       sorted_by_abbrev[i].abbrev_offset =
5797         read_abbrev_offset (sig_type->per_cu.section,
5798                             sig_type->per_cu.offset);
5799     }
5800   cleanups = make_cleanup (xfree, sorted_by_abbrev);
5801   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
5802          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
5803
5804   /* Note: In the .gdb_index case, get_type_unit_group may have already been
5805      called any number of times, so we don't reset tu_stats here.  */
5806
5807   abbrev_offset.sect_off = ~(unsigned) 0;
5808   abbrev_table = NULL;
5809   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
5810
5811   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
5812     {
5813       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
5814
5815       /* Switch to the next abbrev table if necessary.  */
5816       if (abbrev_table == NULL
5817           || tu->abbrev_offset.sect_off != abbrev_offset.sect_off)
5818         {
5819           if (abbrev_table != NULL)
5820             {
5821               abbrev_table_free (abbrev_table);
5822               /* Reset to NULL in case abbrev_table_read_table throws
5823                  an error: abbrev_table_free_cleanup will get called.  */
5824               abbrev_table = NULL;
5825             }
5826           abbrev_offset = tu->abbrev_offset;
5827           abbrev_table =
5828             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
5829                                      abbrev_offset);
5830           ++tu_stats->nr_uniq_abbrev_tables;
5831         }
5832
5833       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
5834                                func, data);
5835     }
5836
5837   /* type_unit_groups can be NULL if there is an error in the debug info.
5838      Just create an empty table so the rest of gdb doesn't have to watch
5839      for this error case.  */
5840   if (dwarf2_per_objfile->type_unit_groups == NULL)
5841     {
5842       dwarf2_per_objfile->type_unit_groups =
5843         allocate_type_unit_groups_table ();
5844       dwarf2_per_objfile->n_type_unit_groups = 0;
5845     }
5846
5847   /* Create a vector of pointers to primary type units to make it easy to
5848      iterate over them and CUs.  See dw2_get_primary_cu.  */
5849   dwarf2_per_objfile->n_type_unit_groups =
5850     htab_elements (dwarf2_per_objfile->type_unit_groups);
5851   dwarf2_per_objfile->all_type_unit_groups =
5852     obstack_alloc (&objfile->objfile_obstack,
5853                    dwarf2_per_objfile->n_type_unit_groups
5854                    * sizeof (struct type_unit_group *));
5855   iter = &dwarf2_per_objfile->all_type_unit_groups[0];
5856   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
5857                           add_type_unit_group_to_table, &iter);
5858   gdb_assert (iter - &dwarf2_per_objfile->all_type_unit_groups[0]
5859               == dwarf2_per_objfile->n_type_unit_groups);
5860
5861   do_cleanups (cleanups);
5862
5863   if (dwarf2_read_debug)
5864     {
5865       fprintf_unfiltered (gdb_stdlog, "Done building type unit groups:\n");
5866       fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
5867                           dwarf2_per_objfile->n_type_units);
5868       fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
5869                           tu_stats->nr_uniq_abbrev_tables);
5870       fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
5871                           tu_stats->nr_symtabs);
5872       fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
5873                           tu_stats->nr_symtab_sharers);
5874       fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
5875                           tu_stats->nr_stmt_less_type_units);
5876     }
5877 }
5878 \f
5879 /* Partial symbol tables.  */
5880
5881 /* Create a psymtab named NAME and assign it to PER_CU.
5882
5883    The caller must fill in the following details:
5884    dirname, textlow, texthigh.  */
5885
5886 static struct partial_symtab *
5887 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
5888 {
5889   struct objfile *objfile = per_cu->objfile;
5890   struct partial_symtab *pst;
5891
5892   pst = start_psymtab_common (objfile, objfile->section_offsets,
5893                               name, 0,
5894                               objfile->global_psymbols.next,
5895                               objfile->static_psymbols.next);
5896
5897   pst->psymtabs_addrmap_supported = 1;
5898
5899   /* This is the glue that links PST into GDB's symbol API.  */
5900   pst->read_symtab_private = per_cu;
5901   pst->read_symtab = dwarf2_read_symtab;
5902   per_cu->v.psymtab = pst;
5903
5904   return pst;
5905 }
5906
5907 /* The DATA object passed to process_psymtab_comp_unit_reader has this
5908    type.  */
5909
5910 struct process_psymtab_comp_unit_data
5911 {
5912   /* True if we are reading a DW_TAG_partial_unit.  */
5913
5914   int want_partial_unit;
5915
5916   /* The "pretend" language that is used if the CU doesn't declare a
5917      language.  */
5918
5919   enum language pretend_language;
5920 };
5921
5922 /* die_reader_func for process_psymtab_comp_unit.  */
5923
5924 static void
5925 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
5926                                   const gdb_byte *info_ptr,
5927                                   struct die_info *comp_unit_die,
5928                                   int has_children,
5929                                   void *data)
5930 {
5931   struct dwarf2_cu *cu = reader->cu;
5932   struct objfile *objfile = cu->objfile;
5933   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
5934   struct attribute *attr;
5935   CORE_ADDR baseaddr;
5936   CORE_ADDR best_lowpc = 0, best_highpc = 0;
5937   struct partial_symtab *pst;
5938   int has_pc_info;
5939   const char *filename;
5940   struct process_psymtab_comp_unit_data *info = data;
5941
5942   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
5943     return;
5944
5945   gdb_assert (! per_cu->is_debug_types);
5946
5947   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
5948
5949   cu->list_in_scope = &file_symbols;
5950
5951   /* Allocate a new partial symbol table structure.  */
5952   attr = dwarf2_attr (comp_unit_die, DW_AT_name, cu);
5953   if (attr == NULL || !DW_STRING (attr))
5954     filename = "";
5955   else
5956     filename = DW_STRING (attr);
5957
5958   pst = create_partial_symtab (per_cu, filename);
5959
5960   /* This must be done before calling dwarf2_build_include_psymtabs.  */
5961   attr = dwarf2_attr (comp_unit_die, DW_AT_comp_dir, cu);
5962   if (attr != NULL)
5963     pst->dirname = DW_STRING (attr);
5964
5965   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
5966
5967   dwarf2_find_base_address (comp_unit_die, cu);
5968
5969   /* Possibly set the default values of LOWPC and HIGHPC from
5970      `DW_AT_ranges'.  */
5971   has_pc_info = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
5972                                       &best_highpc, cu, pst);
5973   if (has_pc_info == 1 && best_lowpc < best_highpc)
5974     /* Store the contiguous range if it is not empty; it can be empty for
5975        CUs with no code.  */
5976     addrmap_set_empty (objfile->psymtabs_addrmap,
5977                        best_lowpc + baseaddr,
5978                        best_highpc + baseaddr - 1, pst);
5979
5980   /* Check if comp unit has_children.
5981      If so, read the rest of the partial symbols from this comp unit.
5982      If not, there's no more debug_info for this comp unit.  */
5983   if (has_children)
5984     {
5985       struct partial_die_info *first_die;
5986       CORE_ADDR lowpc, highpc;
5987
5988       lowpc = ((CORE_ADDR) -1);
5989       highpc = ((CORE_ADDR) 0);
5990
5991       first_die = load_partial_dies (reader, info_ptr, 1);
5992
5993       scan_partial_symbols (first_die, &lowpc, &highpc,
5994                             ! has_pc_info, cu);
5995
5996       /* If we didn't find a lowpc, set it to highpc to avoid
5997          complaints from `maint check'.  */
5998       if (lowpc == ((CORE_ADDR) -1))
5999         lowpc = highpc;
6000
6001       /* If the compilation unit didn't have an explicit address range,
6002          then use the information extracted from its child dies.  */
6003       if (! has_pc_info)
6004         {
6005           best_lowpc = lowpc;
6006           best_highpc = highpc;
6007         }
6008     }
6009   pst->textlow = best_lowpc + baseaddr;
6010   pst->texthigh = best_highpc + baseaddr;
6011
6012   pst->n_global_syms = objfile->global_psymbols.next -
6013     (objfile->global_psymbols.list + pst->globals_offset);
6014   pst->n_static_syms = objfile->static_psymbols.next -
6015     (objfile->static_psymbols.list + pst->statics_offset);
6016   sort_pst_symbols (objfile, pst);
6017
6018   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6019     {
6020       int i;
6021       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6022       struct dwarf2_per_cu_data *iter;
6023
6024       /* Fill in 'dependencies' here; we fill in 'users' in a
6025          post-pass.  */
6026       pst->number_of_dependencies = len;
6027       pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6028                                          len * sizeof (struct symtab *));
6029       for (i = 0;
6030            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6031                         i, iter);
6032            ++i)
6033         pst->dependencies[i] = iter->v.psymtab;
6034
6035       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6036     }
6037
6038   /* Get the list of files included in the current compilation unit,
6039      and build a psymtab for each of them.  */
6040   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6041
6042   if (dwarf2_read_debug)
6043     {
6044       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6045
6046       fprintf_unfiltered (gdb_stdlog,
6047                           "Psymtab for %s unit @0x%x: %s - %s"
6048                           ", %d global, %d static syms\n",
6049                           per_cu->is_debug_types ? "type" : "comp",
6050                           per_cu->offset.sect_off,
6051                           paddress (gdbarch, pst->textlow),
6052                           paddress (gdbarch, pst->texthigh),
6053                           pst->n_global_syms, pst->n_static_syms);
6054     }
6055 }
6056
6057 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6058    Process compilation unit THIS_CU for a psymtab.  */
6059
6060 static void
6061 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6062                            int want_partial_unit,
6063                            enum language pretend_language)
6064 {
6065   struct process_psymtab_comp_unit_data info;
6066
6067   /* If this compilation unit was already read in, free the
6068      cached copy in order to read it in again.  This is
6069      necessary because we skipped some symbols when we first
6070      read in the compilation unit (see load_partial_dies).
6071      This problem could be avoided, but the benefit is unclear.  */
6072   if (this_cu->cu != NULL)
6073     free_one_cached_comp_unit (this_cu);
6074
6075   gdb_assert (! this_cu->is_debug_types);
6076   info.want_partial_unit = want_partial_unit;
6077   info.pretend_language = pretend_language;
6078   init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6079                            process_psymtab_comp_unit_reader,
6080                            &info);
6081
6082   /* Age out any secondary CUs.  */
6083   age_cached_comp_units ();
6084 }
6085
6086 /* Reader function for build_type_psymtabs.  */
6087
6088 static void
6089 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6090                             const gdb_byte *info_ptr,
6091                             struct die_info *type_unit_die,
6092                             int has_children,
6093                             void *data)
6094 {
6095   struct objfile *objfile = dwarf2_per_objfile->objfile;
6096   struct dwarf2_cu *cu = reader->cu;
6097   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6098   struct signatured_type *sig_type;
6099   struct type_unit_group *tu_group;
6100   struct attribute *attr;
6101   struct partial_die_info *first_die;
6102   CORE_ADDR lowpc, highpc;
6103   struct partial_symtab *pst;
6104
6105   gdb_assert (data == NULL);
6106   gdb_assert (per_cu->is_debug_types);
6107   sig_type = (struct signatured_type *) per_cu;
6108
6109   if (! has_children)
6110     return;
6111
6112   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6113   tu_group = get_type_unit_group (cu, attr);
6114
6115   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6116
6117   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6118   cu->list_in_scope = &file_symbols;
6119   pst = create_partial_symtab (per_cu, "");
6120   pst->anonymous = 1;
6121
6122   first_die = load_partial_dies (reader, info_ptr, 1);
6123
6124   lowpc = (CORE_ADDR) -1;
6125   highpc = (CORE_ADDR) 0;
6126   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6127
6128   pst->n_global_syms = objfile->global_psymbols.next -
6129     (objfile->global_psymbols.list + pst->globals_offset);
6130   pst->n_static_syms = objfile->static_psymbols.next -
6131     (objfile->static_psymbols.list + pst->statics_offset);
6132   sort_pst_symbols (objfile, pst);
6133 }
6134
6135 /* Traversal function for build_type_psymtabs.  */
6136
6137 static int
6138 build_type_psymtab_dependencies (void **slot, void *info)
6139 {
6140   struct objfile *objfile = dwarf2_per_objfile->objfile;
6141   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6142   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6143   struct partial_symtab *pst = per_cu->v.psymtab;
6144   int len = VEC_length (sig_type_ptr, tu_group->tus);
6145   struct signatured_type *iter;
6146   int i;
6147
6148   gdb_assert (len > 0);
6149   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6150
6151   pst->number_of_dependencies = len;
6152   pst->dependencies = obstack_alloc (&objfile->objfile_obstack,
6153                                      len * sizeof (struct psymtab *));
6154   for (i = 0;
6155        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6156        ++i)
6157     {
6158       gdb_assert (iter->per_cu.is_debug_types);
6159       pst->dependencies[i] = iter->per_cu.v.psymtab;
6160       iter->type_unit_group = tu_group;
6161     }
6162
6163   VEC_free (sig_type_ptr, tu_group->tus);
6164
6165   return 1;
6166 }
6167
6168 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6169    Build partial symbol tables for the .debug_types comp-units.  */
6170
6171 static void
6172 build_type_psymtabs (struct objfile *objfile)
6173 {
6174   if (! create_all_type_units (objfile))
6175     return;
6176
6177   build_type_unit_groups (build_type_psymtabs_reader, NULL);
6178
6179   /* Now that all TUs have been processed we can fill in the dependencies.  */
6180   htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6181                           build_type_psymtab_dependencies, NULL);
6182 }
6183
6184 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6185
6186 static void
6187 psymtabs_addrmap_cleanup (void *o)
6188 {
6189   struct objfile *objfile = o;
6190
6191   objfile->psymtabs_addrmap = NULL;
6192 }
6193
6194 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6195
6196 static void
6197 set_partial_user (struct objfile *objfile)
6198 {
6199   int i;
6200
6201   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6202     {
6203       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6204       struct partial_symtab *pst = per_cu->v.psymtab;
6205       int j;
6206
6207       if (pst == NULL)
6208         continue;
6209
6210       for (j = 0; j < pst->number_of_dependencies; ++j)
6211         {
6212           /* Set the 'user' field only if it is not already set.  */
6213           if (pst->dependencies[j]->user == NULL)
6214             pst->dependencies[j]->user = pst;
6215         }
6216     }
6217 }
6218
6219 /* Build the partial symbol table by doing a quick pass through the
6220    .debug_info and .debug_abbrev sections.  */
6221
6222 static void
6223 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6224 {
6225   struct cleanup *back_to, *addrmap_cleanup;
6226   struct obstack temp_obstack;
6227   int i;
6228
6229   if (dwarf2_read_debug)
6230     {
6231       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6232                           objfile_name (objfile));
6233     }
6234
6235   dwarf2_per_objfile->reading_partial_symbols = 1;
6236
6237   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6238
6239   /* Any cached compilation units will be linked by the per-objfile
6240      read_in_chain.  Make sure to free them when we're done.  */
6241   back_to = make_cleanup (free_cached_comp_units, NULL);
6242
6243   build_type_psymtabs (objfile);
6244
6245   create_all_comp_units (objfile);
6246
6247   /* Create a temporary address map on a temporary obstack.  We later
6248      copy this to the final obstack.  */
6249   obstack_init (&temp_obstack);
6250   make_cleanup_obstack_free (&temp_obstack);
6251   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6252   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6253
6254   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6255     {
6256       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
6257
6258       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6259     }
6260
6261   set_partial_user (objfile);
6262
6263   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6264                                                     &objfile->objfile_obstack);
6265   discard_cleanups (addrmap_cleanup);
6266
6267   do_cleanups (back_to);
6268
6269   if (dwarf2_read_debug)
6270     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6271                         objfile_name (objfile));
6272 }
6273
6274 /* die_reader_func for load_partial_comp_unit.  */
6275
6276 static void
6277 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6278                                const gdb_byte *info_ptr,
6279                                struct die_info *comp_unit_die,
6280                                int has_children,
6281                                void *data)
6282 {
6283   struct dwarf2_cu *cu = reader->cu;
6284
6285   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6286
6287   /* Check if comp unit has_children.
6288      If so, read the rest of the partial symbols from this comp unit.
6289      If not, there's no more debug_info for this comp unit.  */
6290   if (has_children)
6291     load_partial_dies (reader, info_ptr, 0);
6292 }
6293
6294 /* Load the partial DIEs for a secondary CU into memory.
6295    This is also used when rereading a primary CU with load_all_dies.  */
6296
6297 static void
6298 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6299 {
6300   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6301                            load_partial_comp_unit_reader, NULL);
6302 }
6303
6304 static void
6305 read_comp_units_from_section (struct objfile *objfile,
6306                               struct dwarf2_section_info *section,
6307                               unsigned int is_dwz,
6308                               int *n_allocated,
6309                               int *n_comp_units,
6310                               struct dwarf2_per_cu_data ***all_comp_units)
6311 {
6312   const gdb_byte *info_ptr;
6313   bfd *abfd = get_section_bfd_owner (section);
6314
6315   if (dwarf2_read_debug)
6316     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6317                         get_section_name (section),
6318                         get_section_file_name (section));
6319
6320   dwarf2_read_section (objfile, section);
6321
6322   info_ptr = section->buffer;
6323
6324   while (info_ptr < section->buffer + section->size)
6325     {
6326       unsigned int length, initial_length_size;
6327       struct dwarf2_per_cu_data *this_cu;
6328       sect_offset offset;
6329
6330       offset.sect_off = info_ptr - section->buffer;
6331
6332       /* Read just enough information to find out where the next
6333          compilation unit is.  */
6334       length = read_initial_length (abfd, info_ptr, &initial_length_size);
6335
6336       /* Save the compilation unit for later lookup.  */
6337       this_cu = obstack_alloc (&objfile->objfile_obstack,
6338                                sizeof (struct dwarf2_per_cu_data));
6339       memset (this_cu, 0, sizeof (*this_cu));
6340       this_cu->offset = offset;
6341       this_cu->length = length + initial_length_size;
6342       this_cu->is_dwz = is_dwz;
6343       this_cu->objfile = objfile;
6344       this_cu->section = section;
6345
6346       if (*n_comp_units == *n_allocated)
6347         {
6348           *n_allocated *= 2;
6349           *all_comp_units = xrealloc (*all_comp_units,
6350                                       *n_allocated
6351                                       * sizeof (struct dwarf2_per_cu_data *));
6352         }
6353       (*all_comp_units)[*n_comp_units] = this_cu;
6354       ++*n_comp_units;
6355
6356       info_ptr = info_ptr + this_cu->length;
6357     }
6358 }
6359
6360 /* Create a list of all compilation units in OBJFILE.
6361    This is only done for -readnow and building partial symtabs.  */
6362
6363 static void
6364 create_all_comp_units (struct objfile *objfile)
6365 {
6366   int n_allocated;
6367   int n_comp_units;
6368   struct dwarf2_per_cu_data **all_comp_units;
6369   struct dwz_file *dwz;
6370
6371   n_comp_units = 0;
6372   n_allocated = 10;
6373   all_comp_units = xmalloc (n_allocated
6374                             * sizeof (struct dwarf2_per_cu_data *));
6375
6376   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info, 0,
6377                                 &n_allocated, &n_comp_units, &all_comp_units);
6378
6379   dwz = dwarf2_get_dwz_file ();
6380   if (dwz != NULL)
6381     read_comp_units_from_section (objfile, &dwz->info, 1,
6382                                   &n_allocated, &n_comp_units,
6383                                   &all_comp_units);
6384
6385   dwarf2_per_objfile->all_comp_units
6386     = obstack_alloc (&objfile->objfile_obstack,
6387                      n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6388   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6389           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6390   xfree (all_comp_units);
6391   dwarf2_per_objfile->n_comp_units = n_comp_units;
6392 }
6393
6394 /* Process all loaded DIEs for compilation unit CU, starting at
6395    FIRST_DIE.  The caller should pass NEED_PC == 1 if the compilation
6396    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6397    DW_AT_ranges).  If NEED_PC is set, then this function will set
6398    *LOWPC and *HIGHPC to the lowest and highest PC values found in CU
6399    and record the covered ranges in the addrmap.  */
6400
6401 static void
6402 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6403                       CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6404 {
6405   struct partial_die_info *pdi;
6406
6407   /* Now, march along the PDI's, descending into ones which have
6408      interesting children but skipping the children of the other ones,
6409      until we reach the end of the compilation unit.  */
6410
6411   pdi = first_die;
6412
6413   while (pdi != NULL)
6414     {
6415       fixup_partial_die (pdi, cu);
6416
6417       /* Anonymous namespaces or modules have no name but have interesting
6418          children, so we need to look at them.  Ditto for anonymous
6419          enums.  */
6420
6421       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6422           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6423           || pdi->tag == DW_TAG_imported_unit)
6424         {
6425           switch (pdi->tag)
6426             {
6427             case DW_TAG_subprogram:
6428               add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6429               break;
6430             case DW_TAG_constant:
6431             case DW_TAG_variable:
6432             case DW_TAG_typedef:
6433             case DW_TAG_union_type:
6434               if (!pdi->is_declaration)
6435                 {
6436                   add_partial_symbol (pdi, cu);
6437                 }
6438               break;
6439             case DW_TAG_class_type:
6440             case DW_TAG_interface_type:
6441             case DW_TAG_structure_type:
6442               if (!pdi->is_declaration)
6443                 {
6444                   add_partial_symbol (pdi, cu);
6445                 }
6446               break;
6447             case DW_TAG_enumeration_type:
6448               if (!pdi->is_declaration)
6449                 add_partial_enumeration (pdi, cu);
6450               break;
6451             case DW_TAG_base_type:
6452             case DW_TAG_subrange_type:
6453               /* File scope base type definitions are added to the partial
6454                  symbol table.  */
6455               add_partial_symbol (pdi, cu);
6456               break;
6457             case DW_TAG_namespace:
6458               add_partial_namespace (pdi, lowpc, highpc, need_pc, cu);
6459               break;
6460             case DW_TAG_module:
6461               add_partial_module (pdi, lowpc, highpc, need_pc, cu);
6462               break;
6463             case DW_TAG_imported_unit:
6464               {
6465                 struct dwarf2_per_cu_data *per_cu;
6466
6467                 /* For now we don't handle imported units in type units.  */
6468                 if (cu->per_cu->is_debug_types)
6469                   {
6470                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6471                              " supported in type units [in module %s]"),
6472                            objfile_name (cu->objfile));
6473                   }
6474
6475                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.offset,
6476                                                            pdi->is_dwz,
6477                                                            cu->objfile);
6478
6479                 /* Go read the partial unit, if needed.  */
6480                 if (per_cu->v.psymtab == NULL)
6481                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6482
6483                 VEC_safe_push (dwarf2_per_cu_ptr,
6484                                cu->per_cu->imported_symtabs, per_cu);
6485               }
6486               break;
6487             default:
6488               break;
6489             }
6490         }
6491
6492       /* If the die has a sibling, skip to the sibling.  */
6493
6494       pdi = pdi->die_sibling;
6495     }
6496 }
6497
6498 /* Functions used to compute the fully scoped name of a partial DIE.
6499
6500    Normally, this is simple.  For C++, the parent DIE's fully scoped
6501    name is concatenated with "::" and the partial DIE's name.  For
6502    Java, the same thing occurs except that "." is used instead of "::".
6503    Enumerators are an exception; they use the scope of their parent
6504    enumeration type, i.e. the name of the enumeration type is not
6505    prepended to the enumerator.
6506
6507    There are two complexities.  One is DW_AT_specification; in this
6508    case "parent" means the parent of the target of the specification,
6509    instead of the direct parent of the DIE.  The other is compilers
6510    which do not emit DW_TAG_namespace; in this case we try to guess
6511    the fully qualified name of structure types from their members'
6512    linkage names.  This must be done using the DIE's children rather
6513    than the children of any DW_AT_specification target.  We only need
6514    to do this for structures at the top level, i.e. if the target of
6515    any DW_AT_specification (if any; otherwise the DIE itself) does not
6516    have a parent.  */
6517
6518 /* Compute the scope prefix associated with PDI's parent, in
6519    compilation unit CU.  The result will be allocated on CU's
6520    comp_unit_obstack, or a copy of the already allocated PDI->NAME
6521    field.  NULL is returned if no prefix is necessary.  */
6522 static const char *
6523 partial_die_parent_scope (struct partial_die_info *pdi,
6524                           struct dwarf2_cu *cu)
6525 {
6526   const char *grandparent_scope;
6527   struct partial_die_info *parent, *real_pdi;
6528
6529   /* We need to look at our parent DIE; if we have a DW_AT_specification,
6530      then this means the parent of the specification DIE.  */
6531
6532   real_pdi = pdi;
6533   while (real_pdi->has_specification)
6534     real_pdi = find_partial_die (real_pdi->spec_offset,
6535                                  real_pdi->spec_is_dwz, cu);
6536
6537   parent = real_pdi->die_parent;
6538   if (parent == NULL)
6539     return NULL;
6540
6541   if (parent->scope_set)
6542     return parent->scope;
6543
6544   fixup_partial_die (parent, cu);
6545
6546   grandparent_scope = partial_die_parent_scope (parent, cu);
6547
6548   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
6549      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
6550      Work around this problem here.  */
6551   if (cu->language == language_cplus
6552       && parent->tag == DW_TAG_namespace
6553       && strcmp (parent->name, "::") == 0
6554       && grandparent_scope == NULL)
6555     {
6556       parent->scope = NULL;
6557       parent->scope_set = 1;
6558       return NULL;
6559     }
6560
6561   if (pdi->tag == DW_TAG_enumerator)
6562     /* Enumerators should not get the name of the enumeration as a prefix.  */
6563     parent->scope = grandparent_scope;
6564   else if (parent->tag == DW_TAG_namespace
6565       || parent->tag == DW_TAG_module
6566       || parent->tag == DW_TAG_structure_type
6567       || parent->tag == DW_TAG_class_type
6568       || parent->tag == DW_TAG_interface_type
6569       || parent->tag == DW_TAG_union_type
6570       || parent->tag == DW_TAG_enumeration_type)
6571     {
6572       if (grandparent_scope == NULL)
6573         parent->scope = parent->name;
6574       else
6575         parent->scope = typename_concat (&cu->comp_unit_obstack,
6576                                          grandparent_scope,
6577                                          parent->name, 0, cu);
6578     }
6579   else
6580     {
6581       /* FIXME drow/2004-04-01: What should we be doing with
6582          function-local names?  For partial symbols, we should probably be
6583          ignoring them.  */
6584       complaint (&symfile_complaints,
6585                  _("unhandled containing DIE tag %d for DIE at %d"),
6586                  parent->tag, pdi->offset.sect_off);
6587       parent->scope = grandparent_scope;
6588     }
6589
6590   parent->scope_set = 1;
6591   return parent->scope;
6592 }
6593
6594 /* Return the fully scoped name associated with PDI, from compilation unit
6595    CU.  The result will be allocated with malloc.  */
6596
6597 static char *
6598 partial_die_full_name (struct partial_die_info *pdi,
6599                        struct dwarf2_cu *cu)
6600 {
6601   const char *parent_scope;
6602
6603   /* If this is a template instantiation, we can not work out the
6604      template arguments from partial DIEs.  So, unfortunately, we have
6605      to go through the full DIEs.  At least any work we do building
6606      types here will be reused if full symbols are loaded later.  */
6607   if (pdi->has_template_arguments)
6608     {
6609       fixup_partial_die (pdi, cu);
6610
6611       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
6612         {
6613           struct die_info *die;
6614           struct attribute attr;
6615           struct dwarf2_cu *ref_cu = cu;
6616
6617           /* DW_FORM_ref_addr is using section offset.  */
6618           attr.name = 0;
6619           attr.form = DW_FORM_ref_addr;
6620           attr.u.unsnd = pdi->offset.sect_off;
6621           die = follow_die_ref (NULL, &attr, &ref_cu);
6622
6623           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
6624         }
6625     }
6626
6627   parent_scope = partial_die_parent_scope (pdi, cu);
6628   if (parent_scope == NULL)
6629     return NULL;
6630   else
6631     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
6632 }
6633
6634 static void
6635 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
6636 {
6637   struct objfile *objfile = cu->objfile;
6638   CORE_ADDR addr = 0;
6639   const char *actual_name = NULL;
6640   CORE_ADDR baseaddr;
6641   char *built_actual_name;
6642
6643   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6644
6645   built_actual_name = partial_die_full_name (pdi, cu);
6646   if (built_actual_name != NULL)
6647     actual_name = built_actual_name;
6648
6649   if (actual_name == NULL)
6650     actual_name = pdi->name;
6651
6652   switch (pdi->tag)
6653     {
6654     case DW_TAG_subprogram:
6655       if (pdi->is_external || cu->language == language_ada)
6656         {
6657           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
6658              of the global scope.  But in Ada, we want to be able to access
6659              nested procedures globally.  So all Ada subprograms are stored
6660              in the global scope.  */
6661           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6662              mst_text, objfile); */
6663           add_psymbol_to_list (actual_name, strlen (actual_name),
6664                                built_actual_name != NULL,
6665                                VAR_DOMAIN, LOC_BLOCK,
6666                                &objfile->global_psymbols,
6667                                0, pdi->lowpc + baseaddr,
6668                                cu->language, objfile);
6669         }
6670       else
6671         {
6672           /* prim_record_minimal_symbol (actual_name, pdi->lowpc + baseaddr,
6673              mst_file_text, objfile); */
6674           add_psymbol_to_list (actual_name, strlen (actual_name),
6675                                built_actual_name != NULL,
6676                                VAR_DOMAIN, LOC_BLOCK,
6677                                &objfile->static_psymbols,
6678                                0, pdi->lowpc + baseaddr,
6679                                cu->language, objfile);
6680         }
6681       break;
6682     case DW_TAG_constant:
6683       {
6684         struct psymbol_allocation_list *list;
6685
6686         if (pdi->is_external)
6687           list = &objfile->global_psymbols;
6688         else
6689           list = &objfile->static_psymbols;
6690         add_psymbol_to_list (actual_name, strlen (actual_name),
6691                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
6692                              list, 0, 0, cu->language, objfile);
6693       }
6694       break;
6695     case DW_TAG_variable:
6696       if (pdi->d.locdesc)
6697         addr = decode_locdesc (pdi->d.locdesc, cu);
6698
6699       if (pdi->d.locdesc
6700           && addr == 0
6701           && !dwarf2_per_objfile->has_section_at_zero)
6702         {
6703           /* A global or static variable may also have been stripped
6704              out by the linker if unused, in which case its address
6705              will be nullified; do not add such variables into partial
6706              symbol table then.  */
6707         }
6708       else if (pdi->is_external)
6709         {
6710           /* Global Variable.
6711              Don't enter into the minimal symbol tables as there is
6712              a minimal symbol table entry from the ELF symbols already.
6713              Enter into partial symbol table if it has a location
6714              descriptor or a type.
6715              If the location descriptor is missing, new_symbol will create
6716              a LOC_UNRESOLVED symbol, the address of the variable will then
6717              be determined from the minimal symbol table whenever the variable
6718              is referenced.
6719              The address for the partial symbol table entry is not
6720              used by GDB, but it comes in handy for debugging partial symbol
6721              table building.  */
6722
6723           if (pdi->d.locdesc || pdi->has_type)
6724             add_psymbol_to_list (actual_name, strlen (actual_name),
6725                                  built_actual_name != NULL,
6726                                  VAR_DOMAIN, LOC_STATIC,
6727                                  &objfile->global_psymbols,
6728                                  0, addr + baseaddr,
6729                                  cu->language, objfile);
6730         }
6731       else
6732         {
6733           /* Static Variable.  Skip symbols without location descriptors.  */
6734           if (pdi->d.locdesc == NULL)
6735             {
6736               xfree (built_actual_name);
6737               return;
6738             }
6739           /* prim_record_minimal_symbol (actual_name, addr + baseaddr,
6740              mst_file_data, objfile); */
6741           add_psymbol_to_list (actual_name, strlen (actual_name),
6742                                built_actual_name != NULL,
6743                                VAR_DOMAIN, LOC_STATIC,
6744                                &objfile->static_psymbols,
6745                                0, addr + baseaddr,
6746                                cu->language, objfile);
6747         }
6748       break;
6749     case DW_TAG_typedef:
6750     case DW_TAG_base_type:
6751     case DW_TAG_subrange_type:
6752       add_psymbol_to_list (actual_name, strlen (actual_name),
6753                            built_actual_name != NULL,
6754                            VAR_DOMAIN, LOC_TYPEDEF,
6755                            &objfile->static_psymbols,
6756                            0, (CORE_ADDR) 0, cu->language, objfile);
6757       break;
6758     case DW_TAG_namespace:
6759       add_psymbol_to_list (actual_name, strlen (actual_name),
6760                            built_actual_name != NULL,
6761                            VAR_DOMAIN, LOC_TYPEDEF,
6762                            &objfile->global_psymbols,
6763                            0, (CORE_ADDR) 0, cu->language, objfile);
6764       break;
6765     case DW_TAG_class_type:
6766     case DW_TAG_interface_type:
6767     case DW_TAG_structure_type:
6768     case DW_TAG_union_type:
6769     case DW_TAG_enumeration_type:
6770       /* Skip external references.  The DWARF standard says in the section
6771          about "Structure, Union, and Class Type Entries": "An incomplete
6772          structure, union or class type is represented by a structure,
6773          union or class entry that does not have a byte size attribute
6774          and that has a DW_AT_declaration attribute."  */
6775       if (!pdi->has_byte_size && pdi->is_declaration)
6776         {
6777           xfree (built_actual_name);
6778           return;
6779         }
6780
6781       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
6782          static vs. global.  */
6783       add_psymbol_to_list (actual_name, strlen (actual_name),
6784                            built_actual_name != NULL,
6785                            STRUCT_DOMAIN, LOC_TYPEDEF,
6786                            (cu->language == language_cplus
6787                             || cu->language == language_java)
6788                            ? &objfile->global_psymbols
6789                            : &objfile->static_psymbols,
6790                            0, (CORE_ADDR) 0, cu->language, objfile);
6791
6792       break;
6793     case DW_TAG_enumerator:
6794       add_psymbol_to_list (actual_name, strlen (actual_name),
6795                            built_actual_name != NULL,
6796                            VAR_DOMAIN, LOC_CONST,
6797                            (cu->language == language_cplus
6798                             || cu->language == language_java)
6799                            ? &objfile->global_psymbols
6800                            : &objfile->static_psymbols,
6801                            0, (CORE_ADDR) 0, cu->language, objfile);
6802       break;
6803     default:
6804       break;
6805     }
6806
6807   xfree (built_actual_name);
6808 }
6809
6810 /* Read a partial die corresponding to a namespace; also, add a symbol
6811    corresponding to that namespace to the symbol table.  NAMESPACE is
6812    the name of the enclosing namespace.  */
6813
6814 static void
6815 add_partial_namespace (struct partial_die_info *pdi,
6816                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
6817                        int need_pc, struct dwarf2_cu *cu)
6818 {
6819   /* Add a symbol for the namespace.  */
6820
6821   add_partial_symbol (pdi, cu);
6822
6823   /* Now scan partial symbols in that namespace.  */
6824
6825   if (pdi->has_children)
6826     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6827 }
6828
6829 /* Read a partial die corresponding to a Fortran module.  */
6830
6831 static void
6832 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
6833                     CORE_ADDR *highpc, int need_pc, struct dwarf2_cu *cu)
6834 {
6835   /* Now scan partial symbols in that module.  */
6836
6837   if (pdi->has_children)
6838     scan_partial_symbols (pdi->die_child, lowpc, highpc, need_pc, cu);
6839 }
6840
6841 /* Read a partial die corresponding to a subprogram and create a partial
6842    symbol for that subprogram.  When the CU language allows it, this
6843    routine also defines a partial symbol for each nested subprogram
6844    that this subprogram contains.
6845
6846    DIE my also be a lexical block, in which case we simply search
6847    recursively for suprograms defined inside that lexical block.
6848    Again, this is only performed when the CU language allows this
6849    type of definitions.  */
6850
6851 static void
6852 add_partial_subprogram (struct partial_die_info *pdi,
6853                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
6854                         int need_pc, struct dwarf2_cu *cu)
6855 {
6856   if (pdi->tag == DW_TAG_subprogram)
6857     {
6858       if (pdi->has_pc_info)
6859         {
6860           if (pdi->lowpc < *lowpc)
6861             *lowpc = pdi->lowpc;
6862           if (pdi->highpc > *highpc)
6863             *highpc = pdi->highpc;
6864           if (need_pc)
6865             {
6866               CORE_ADDR baseaddr;
6867               struct objfile *objfile = cu->objfile;
6868
6869               baseaddr = ANOFFSET (objfile->section_offsets,
6870                                    SECT_OFF_TEXT (objfile));
6871               addrmap_set_empty (objfile->psymtabs_addrmap,
6872                                  pdi->lowpc + baseaddr,
6873                                  pdi->highpc - 1 + baseaddr,
6874                                  cu->per_cu->v.psymtab);
6875             }
6876         }
6877
6878       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
6879         {
6880           if (!pdi->is_declaration)
6881             /* Ignore subprogram DIEs that do not have a name, they are
6882                illegal.  Do not emit a complaint at this point, we will
6883                do so when we convert this psymtab into a symtab.  */
6884             if (pdi->name)
6885               add_partial_symbol (pdi, cu);
6886         }
6887     }
6888
6889   if (! pdi->has_children)
6890     return;
6891
6892   if (cu->language == language_ada)
6893     {
6894       pdi = pdi->die_child;
6895       while (pdi != NULL)
6896         {
6897           fixup_partial_die (pdi, cu);
6898           if (pdi->tag == DW_TAG_subprogram
6899               || pdi->tag == DW_TAG_lexical_block)
6900             add_partial_subprogram (pdi, lowpc, highpc, need_pc, cu);
6901           pdi = pdi->die_sibling;
6902         }
6903     }
6904 }
6905
6906 /* Read a partial die corresponding to an enumeration type.  */
6907
6908 static void
6909 add_partial_enumeration (struct partial_die_info *enum_pdi,
6910                          struct dwarf2_cu *cu)
6911 {
6912   struct partial_die_info *pdi;
6913
6914   if (enum_pdi->name != NULL)
6915     add_partial_symbol (enum_pdi, cu);
6916
6917   pdi = enum_pdi->die_child;
6918   while (pdi)
6919     {
6920       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
6921         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
6922       else
6923         add_partial_symbol (pdi, cu);
6924       pdi = pdi->die_sibling;
6925     }
6926 }
6927
6928 /* Return the initial uleb128 in the die at INFO_PTR.  */
6929
6930 static unsigned int
6931 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
6932 {
6933   unsigned int bytes_read;
6934
6935   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
6936 }
6937
6938 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
6939    Return the corresponding abbrev, or NULL if the number is zero (indicating
6940    an empty DIE).  In either case *BYTES_READ will be set to the length of
6941    the initial number.  */
6942
6943 static struct abbrev_info *
6944 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
6945                  struct dwarf2_cu *cu)
6946 {
6947   bfd *abfd = cu->objfile->obfd;
6948   unsigned int abbrev_number;
6949   struct abbrev_info *abbrev;
6950
6951   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
6952
6953   if (abbrev_number == 0)
6954     return NULL;
6955
6956   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
6957   if (!abbrev)
6958     {
6959       error (_("Dwarf Error: Could not find abbrev number %d [in module %s]"),
6960              abbrev_number, bfd_get_filename (abfd));
6961     }
6962
6963   return abbrev;
6964 }
6965
6966 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6967    Returns a pointer to the end of a series of DIEs, terminated by an empty
6968    DIE.  Any children of the skipped DIEs will also be skipped.  */
6969
6970 static const gdb_byte *
6971 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
6972 {
6973   struct dwarf2_cu *cu = reader->cu;
6974   struct abbrev_info *abbrev;
6975   unsigned int bytes_read;
6976
6977   while (1)
6978     {
6979       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
6980       if (abbrev == NULL)
6981         return info_ptr + bytes_read;
6982       else
6983         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
6984     }
6985 }
6986
6987 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
6988    INFO_PTR should point just after the initial uleb128 of a DIE, and the
6989    abbrev corresponding to that skipped uleb128 should be passed in
6990    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
6991    children.  */
6992
6993 static const gdb_byte *
6994 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
6995               struct abbrev_info *abbrev)
6996 {
6997   unsigned int bytes_read;
6998   struct attribute attr;
6999   bfd *abfd = reader->abfd;
7000   struct dwarf2_cu *cu = reader->cu;
7001   const gdb_byte *buffer = reader->buffer;
7002   const gdb_byte *buffer_end = reader->buffer_end;
7003   const gdb_byte *start_info_ptr = info_ptr;
7004   unsigned int form, i;
7005
7006   for (i = 0; i < abbrev->num_attrs; i++)
7007     {
7008       /* The only abbrev we care about is DW_AT_sibling.  */
7009       if (abbrev->attrs[i].name == DW_AT_sibling)
7010         {
7011           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7012           if (attr.form == DW_FORM_ref_addr)
7013             complaint (&symfile_complaints,
7014                        _("ignoring absolute DW_AT_sibling"));
7015           else
7016             return buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
7017         }
7018
7019       /* If it isn't DW_AT_sibling, skip this attribute.  */
7020       form = abbrev->attrs[i].form;
7021     skip_attribute:
7022       switch (form)
7023         {
7024         case DW_FORM_ref_addr:
7025           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7026              and later it is offset sized.  */
7027           if (cu->header.version == 2)
7028             info_ptr += cu->header.addr_size;
7029           else
7030             info_ptr += cu->header.offset_size;
7031           break;
7032         case DW_FORM_GNU_ref_alt:
7033           info_ptr += cu->header.offset_size;
7034           break;
7035         case DW_FORM_addr:
7036           info_ptr += cu->header.addr_size;
7037           break;
7038         case DW_FORM_data1:
7039         case DW_FORM_ref1:
7040         case DW_FORM_flag:
7041           info_ptr += 1;
7042           break;
7043         case DW_FORM_flag_present:
7044           break;
7045         case DW_FORM_data2:
7046         case DW_FORM_ref2:
7047           info_ptr += 2;
7048           break;
7049         case DW_FORM_data4:
7050         case DW_FORM_ref4:
7051           info_ptr += 4;
7052           break;
7053         case DW_FORM_data8:
7054         case DW_FORM_ref8:
7055         case DW_FORM_ref_sig8:
7056           info_ptr += 8;
7057           break;
7058         case DW_FORM_string:
7059           read_direct_string (abfd, info_ptr, &bytes_read);
7060           info_ptr += bytes_read;
7061           break;
7062         case DW_FORM_sec_offset:
7063         case DW_FORM_strp:
7064         case DW_FORM_GNU_strp_alt:
7065           info_ptr += cu->header.offset_size;
7066           break;
7067         case DW_FORM_exprloc:
7068         case DW_FORM_block:
7069           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7070           info_ptr += bytes_read;
7071           break;
7072         case DW_FORM_block1:
7073           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7074           break;
7075         case DW_FORM_block2:
7076           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7077           break;
7078         case DW_FORM_block4:
7079           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7080           break;
7081         case DW_FORM_sdata:
7082         case DW_FORM_udata:
7083         case DW_FORM_ref_udata:
7084         case DW_FORM_GNU_addr_index:
7085         case DW_FORM_GNU_str_index:
7086           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7087           break;
7088         case DW_FORM_indirect:
7089           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7090           info_ptr += bytes_read;
7091           /* We need to continue parsing from here, so just go back to
7092              the top.  */
7093           goto skip_attribute;
7094
7095         default:
7096           error (_("Dwarf Error: Cannot handle %s "
7097                    "in DWARF reader [in module %s]"),
7098                  dwarf_form_name (form),
7099                  bfd_get_filename (abfd));
7100         }
7101     }
7102
7103   if (abbrev->has_children)
7104     return skip_children (reader, info_ptr);
7105   else
7106     return info_ptr;
7107 }
7108
7109 /* Locate ORIG_PDI's sibling.
7110    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7111
7112 static const gdb_byte *
7113 locate_pdi_sibling (const struct die_reader_specs *reader,
7114                     struct partial_die_info *orig_pdi,
7115                     const gdb_byte *info_ptr)
7116 {
7117   /* Do we know the sibling already?  */
7118
7119   if (orig_pdi->sibling)
7120     return orig_pdi->sibling;
7121
7122   /* Are there any children to deal with?  */
7123
7124   if (!orig_pdi->has_children)
7125     return info_ptr;
7126
7127   /* Skip the children the long way.  */
7128
7129   return skip_children (reader, info_ptr);
7130 }
7131
7132 /* Expand this partial symbol table into a full symbol table.  SELF is
7133    not NULL.  */
7134
7135 static void
7136 dwarf2_read_symtab (struct partial_symtab *self,
7137                     struct objfile *objfile)
7138 {
7139   if (self->readin)
7140     {
7141       warning (_("bug: psymtab for %s is already read in."),
7142                self->filename);
7143     }
7144   else
7145     {
7146       if (info_verbose)
7147         {
7148           printf_filtered (_("Reading in symbols for %s..."),
7149                            self->filename);
7150           gdb_flush (gdb_stdout);
7151         }
7152
7153       /* Restore our global data.  */
7154       dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
7155
7156       /* If this psymtab is constructed from a debug-only objfile, the
7157          has_section_at_zero flag will not necessarily be correct.  We
7158          can get the correct value for this flag by looking at the data
7159          associated with the (presumably stripped) associated objfile.  */
7160       if (objfile->separate_debug_objfile_backlink)
7161         {
7162           struct dwarf2_per_objfile *dpo_backlink
7163             = objfile_data (objfile->separate_debug_objfile_backlink,
7164                             dwarf2_objfile_data_key);
7165
7166           dwarf2_per_objfile->has_section_at_zero
7167             = dpo_backlink->has_section_at_zero;
7168         }
7169
7170       dwarf2_per_objfile->reading_partial_symbols = 0;
7171
7172       psymtab_to_symtab_1 (self);
7173
7174       /* Finish up the debug error message.  */
7175       if (info_verbose)
7176         printf_filtered (_("done.\n"));
7177     }
7178
7179   process_cu_includes ();
7180 }
7181 \f
7182 /* Reading in full CUs.  */
7183
7184 /* Add PER_CU to the queue.  */
7185
7186 static void
7187 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7188                  enum language pretend_language)
7189 {
7190   struct dwarf2_queue_item *item;
7191
7192   per_cu->queued = 1;
7193   item = xmalloc (sizeof (*item));
7194   item->per_cu = per_cu;
7195   item->pretend_language = pretend_language;
7196   item->next = NULL;
7197
7198   if (dwarf2_queue == NULL)
7199     dwarf2_queue = item;
7200   else
7201     dwarf2_queue_tail->next = item;
7202
7203   dwarf2_queue_tail = item;
7204 }
7205
7206 /* If PER_CU is not yet queued, add it to the queue.
7207    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7208    dependency.
7209    The result is non-zero if PER_CU was queued, otherwise the result is zero
7210    meaning either PER_CU is already queued or it is already loaded.
7211
7212    N.B. There is an invariant here that if a CU is queued then it is loaded.
7213    The caller is required to load PER_CU if we return non-zero.  */
7214
7215 static int
7216 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7217                        struct dwarf2_per_cu_data *per_cu,
7218                        enum language pretend_language)
7219 {
7220   /* We may arrive here during partial symbol reading, if we need full
7221      DIEs to process an unusual case (e.g. template arguments).  Do
7222      not queue PER_CU, just tell our caller to load its DIEs.  */
7223   if (dwarf2_per_objfile->reading_partial_symbols)
7224     {
7225       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7226         return 1;
7227       return 0;
7228     }
7229
7230   /* Mark the dependence relation so that we don't flush PER_CU
7231      too early.  */
7232   if (dependent_cu != NULL)
7233     dwarf2_add_dependence (dependent_cu, per_cu);
7234
7235   /* If it's already on the queue, we have nothing to do.  */
7236   if (per_cu->queued)
7237     return 0;
7238
7239   /* If the compilation unit is already loaded, just mark it as
7240      used.  */
7241   if (per_cu->cu != NULL)
7242     {
7243       per_cu->cu->last_used = 0;
7244       return 0;
7245     }
7246
7247   /* Add it to the queue.  */
7248   queue_comp_unit (per_cu, pretend_language);
7249
7250   return 1;
7251 }
7252
7253 /* Process the queue.  */
7254
7255 static void
7256 process_queue (void)
7257 {
7258   struct dwarf2_queue_item *item, *next_item;
7259
7260   if (dwarf2_read_debug)
7261     {
7262       fprintf_unfiltered (gdb_stdlog,
7263                           "Expanding one or more symtabs of objfile %s ...\n",
7264                           objfile_name (dwarf2_per_objfile->objfile));
7265     }
7266
7267   /* The queue starts out with one item, but following a DIE reference
7268      may load a new CU, adding it to the end of the queue.  */
7269   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7270     {
7271       if (dwarf2_per_objfile->using_index
7272           ? !item->per_cu->v.quick->symtab
7273           : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7274         {
7275           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7276           char buf[100];
7277
7278           if (per_cu->is_debug_types)
7279             {
7280               struct signatured_type *sig_type =
7281                 (struct signatured_type *) per_cu;
7282
7283               sprintf (buf, "TU %s at offset 0x%x",
7284                        hex_string (sig_type->signature), per_cu->offset.sect_off);
7285             }
7286           else
7287             sprintf (buf, "CU at offset 0x%x", per_cu->offset.sect_off);
7288
7289           if (dwarf2_read_debug)
7290             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7291
7292           if (per_cu->is_debug_types)
7293             process_full_type_unit (per_cu, item->pretend_language);
7294           else
7295             process_full_comp_unit (per_cu, item->pretend_language);
7296
7297           if (dwarf2_read_debug)
7298             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7299         }
7300
7301       item->per_cu->queued = 0;
7302       next_item = item->next;
7303       xfree (item);
7304     }
7305
7306   dwarf2_queue_tail = NULL;
7307
7308   if (dwarf2_read_debug)
7309     {
7310       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7311                           objfile_name (dwarf2_per_objfile->objfile));
7312     }
7313 }
7314
7315 /* Free all allocated queue entries.  This function only releases anything if
7316    an error was thrown; if the queue was processed then it would have been
7317    freed as we went along.  */
7318
7319 static void
7320 dwarf2_release_queue (void *dummy)
7321 {
7322   struct dwarf2_queue_item *item, *last;
7323
7324   item = dwarf2_queue;
7325   while (item)
7326     {
7327       /* Anything still marked queued is likely to be in an
7328          inconsistent state, so discard it.  */
7329       if (item->per_cu->queued)
7330         {
7331           if (item->per_cu->cu != NULL)
7332             free_one_cached_comp_unit (item->per_cu);
7333           item->per_cu->queued = 0;
7334         }
7335
7336       last = item;
7337       item = item->next;
7338       xfree (last);
7339     }
7340
7341   dwarf2_queue = dwarf2_queue_tail = NULL;
7342 }
7343
7344 /* Read in full symbols for PST, and anything it depends on.  */
7345
7346 static void
7347 psymtab_to_symtab_1 (struct partial_symtab *pst)
7348 {
7349   struct dwarf2_per_cu_data *per_cu;
7350   int i;
7351
7352   if (pst->readin)
7353     return;
7354
7355   for (i = 0; i < pst->number_of_dependencies; i++)
7356     if (!pst->dependencies[i]->readin
7357         && pst->dependencies[i]->user == NULL)
7358       {
7359         /* Inform about additional files that need to be read in.  */
7360         if (info_verbose)
7361           {
7362             /* FIXME: i18n: Need to make this a single string.  */
7363             fputs_filtered (" ", gdb_stdout);
7364             wrap_here ("");
7365             fputs_filtered ("and ", gdb_stdout);
7366             wrap_here ("");
7367             printf_filtered ("%s...", pst->dependencies[i]->filename);
7368             wrap_here ("");     /* Flush output.  */
7369             gdb_flush (gdb_stdout);
7370           }
7371         psymtab_to_symtab_1 (pst->dependencies[i]);
7372       }
7373
7374   per_cu = pst->read_symtab_private;
7375
7376   if (per_cu == NULL)
7377     {
7378       /* It's an include file, no symbols to read for it.
7379          Everything is in the parent symtab.  */
7380       pst->readin = 1;
7381       return;
7382     }
7383
7384   dw2_do_instantiate_symtab (per_cu);
7385 }
7386
7387 /* Trivial hash function for die_info: the hash value of a DIE
7388    is its offset in .debug_info for this objfile.  */
7389
7390 static hashval_t
7391 die_hash (const void *item)
7392 {
7393   const struct die_info *die = item;
7394
7395   return die->offset.sect_off;
7396 }
7397
7398 /* Trivial comparison function for die_info structures: two DIEs
7399    are equal if they have the same offset.  */
7400
7401 static int
7402 die_eq (const void *item_lhs, const void *item_rhs)
7403 {
7404   const struct die_info *die_lhs = item_lhs;
7405   const struct die_info *die_rhs = item_rhs;
7406
7407   return die_lhs->offset.sect_off == die_rhs->offset.sect_off;
7408 }
7409
7410 /* die_reader_func for load_full_comp_unit.
7411    This is identical to read_signatured_type_reader,
7412    but is kept separate for now.  */
7413
7414 static void
7415 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7416                             const gdb_byte *info_ptr,
7417                             struct die_info *comp_unit_die,
7418                             int has_children,
7419                             void *data)
7420 {
7421   struct dwarf2_cu *cu = reader->cu;
7422   enum language *language_ptr = data;
7423
7424   gdb_assert (cu->die_hash == NULL);
7425   cu->die_hash =
7426     htab_create_alloc_ex (cu->header.length / 12,
7427                           die_hash,
7428                           die_eq,
7429                           NULL,
7430                           &cu->comp_unit_obstack,
7431                           hashtab_obstack_allocate,
7432                           dummy_obstack_deallocate);
7433
7434   if (has_children)
7435     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7436                                                   &info_ptr, comp_unit_die);
7437   cu->dies = comp_unit_die;
7438   /* comp_unit_die is not stored in die_hash, no need.  */
7439
7440   /* We try not to read any attributes in this function, because not
7441      all CUs needed for references have been loaded yet, and symbol
7442      table processing isn't initialized.  But we have to set the CU language,
7443      or we won't be able to build types correctly.
7444      Similarly, if we do not read the producer, we can not apply
7445      producer-specific interpretation.  */
7446   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7447 }
7448
7449 /* Load the DIEs associated with PER_CU into memory.  */
7450
7451 static void
7452 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7453                      enum language pretend_language)
7454 {
7455   gdb_assert (! this_cu->is_debug_types);
7456
7457   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7458                            load_full_comp_unit_reader, &pretend_language);
7459 }
7460
7461 /* Add a DIE to the delayed physname list.  */
7462
7463 static void
7464 add_to_method_list (struct type *type, int fnfield_index, int index,
7465                     const char *name, struct die_info *die,
7466                     struct dwarf2_cu *cu)
7467 {
7468   struct delayed_method_info mi;
7469   mi.type = type;
7470   mi.fnfield_index = fnfield_index;
7471   mi.index = index;
7472   mi.name = name;
7473   mi.die = die;
7474   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
7475 }
7476
7477 /* A cleanup for freeing the delayed method list.  */
7478
7479 static void
7480 free_delayed_list (void *ptr)
7481 {
7482   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
7483   if (cu->method_list != NULL)
7484     {
7485       VEC_free (delayed_method_info, cu->method_list);
7486       cu->method_list = NULL;
7487     }
7488 }
7489
7490 /* Compute the physnames of any methods on the CU's method list.
7491
7492    The computation of method physnames is delayed in order to avoid the
7493    (bad) condition that one of the method's formal parameters is of an as yet
7494    incomplete type.  */
7495
7496 static void
7497 compute_delayed_physnames (struct dwarf2_cu *cu)
7498 {
7499   int i;
7500   struct delayed_method_info *mi;
7501   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
7502     {
7503       const char *physname;
7504       struct fn_fieldlist *fn_flp
7505         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
7506       physname = dwarf2_physname (mi->name, mi->die, cu);
7507       fn_flp->fn_fields[mi->index].physname = physname ? physname : "";
7508     }
7509 }
7510
7511 /* Go objects should be embedded in a DW_TAG_module DIE,
7512    and it's not clear if/how imported objects will appear.
7513    To keep Go support simple until that's worked out,
7514    go back through what we've read and create something usable.
7515    We could do this while processing each DIE, and feels kinda cleaner,
7516    but that way is more invasive.
7517    This is to, for example, allow the user to type "p var" or "b main"
7518    without having to specify the package name, and allow lookups
7519    of module.object to work in contexts that use the expression
7520    parser.  */
7521
7522 static void
7523 fixup_go_packaging (struct dwarf2_cu *cu)
7524 {
7525   char *package_name = NULL;
7526   struct pending *list;
7527   int i;
7528
7529   for (list = global_symbols; list != NULL; list = list->next)
7530     {
7531       for (i = 0; i < list->nsyms; ++i)
7532         {
7533           struct symbol *sym = list->symbol[i];
7534
7535           if (SYMBOL_LANGUAGE (sym) == language_go
7536               && SYMBOL_CLASS (sym) == LOC_BLOCK)
7537             {
7538               char *this_package_name = go_symbol_package_name (sym);
7539
7540               if (this_package_name == NULL)
7541                 continue;
7542               if (package_name == NULL)
7543                 package_name = this_package_name;
7544               else
7545                 {
7546                   if (strcmp (package_name, this_package_name) != 0)
7547                     complaint (&symfile_complaints,
7548                                _("Symtab %s has objects from two different Go packages: %s and %s"),
7549                                (SYMBOL_SYMTAB (sym)
7550                           ? symtab_to_filename_for_display (SYMBOL_SYMTAB (sym))
7551                                 : objfile_name (cu->objfile)),
7552                                this_package_name, package_name);
7553                   xfree (this_package_name);
7554                 }
7555             }
7556         }
7557     }
7558
7559   if (package_name != NULL)
7560     {
7561       struct objfile *objfile = cu->objfile;
7562       const char *saved_package_name = obstack_copy0 (&objfile->objfile_obstack,
7563                                                       package_name,
7564                                                       strlen (package_name));
7565       struct type *type = init_type (TYPE_CODE_MODULE, 0, 0,
7566                                      saved_package_name, objfile);
7567       struct symbol *sym;
7568
7569       TYPE_TAG_NAME (type) = TYPE_NAME (type);
7570
7571       sym = allocate_symbol (objfile);
7572       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
7573       SYMBOL_SET_NAMES (sym, saved_package_name,
7574                         strlen (saved_package_name), 0, objfile);
7575       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
7576          e.g., "main" finds the "main" module and not C's main().  */
7577       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
7578       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
7579       SYMBOL_TYPE (sym) = type;
7580
7581       add_symbol_to_list (sym, &global_symbols);
7582
7583       xfree (package_name);
7584     }
7585 }
7586
7587 /* Return the symtab for PER_CU.  This works properly regardless of
7588    whether we're using the index or psymtabs.  */
7589
7590 static struct symtab *
7591 get_symtab (struct dwarf2_per_cu_data *per_cu)
7592 {
7593   return (dwarf2_per_objfile->using_index
7594           ? per_cu->v.quick->symtab
7595           : per_cu->v.psymtab->symtab);
7596 }
7597
7598 /* A helper function for computing the list of all symbol tables
7599    included by PER_CU.  */
7600
7601 static void
7602 recursively_compute_inclusions (VEC (symtab_ptr) **result,
7603                                 htab_t all_children, htab_t all_type_symtabs,
7604                                 struct dwarf2_per_cu_data *per_cu,
7605                                 struct symtab *immediate_parent)
7606 {
7607   void **slot;
7608   int ix;
7609   struct symtab *symtab;
7610   struct dwarf2_per_cu_data *iter;
7611
7612   slot = htab_find_slot (all_children, per_cu, INSERT);
7613   if (*slot != NULL)
7614     {
7615       /* This inclusion and its children have been processed.  */
7616       return;
7617     }
7618
7619   *slot = per_cu;
7620   /* Only add a CU if it has a symbol table.  */
7621   symtab = get_symtab (per_cu);
7622   if (symtab != NULL)
7623     {
7624       /* If this is a type unit only add its symbol table if we haven't
7625          seen it yet (type unit per_cu's can share symtabs).  */
7626       if (per_cu->is_debug_types)
7627         {
7628           slot = htab_find_slot (all_type_symtabs, symtab, INSERT);
7629           if (*slot == NULL)
7630             {
7631               *slot = symtab;
7632               VEC_safe_push (symtab_ptr, *result, symtab);
7633               if (symtab->user == NULL)
7634                 symtab->user = immediate_parent;
7635             }
7636         }
7637       else
7638         {
7639           VEC_safe_push (symtab_ptr, *result, symtab);
7640           if (symtab->user == NULL)
7641             symtab->user = immediate_parent;
7642         }
7643     }
7644
7645   for (ix = 0;
7646        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
7647        ++ix)
7648     {
7649       recursively_compute_inclusions (result, all_children,
7650                                       all_type_symtabs, iter, symtab);
7651     }
7652 }
7653
7654 /* Compute the symtab 'includes' fields for the symtab related to
7655    PER_CU.  */
7656
7657 static void
7658 compute_symtab_includes (struct dwarf2_per_cu_data *per_cu)
7659 {
7660   gdb_assert (! per_cu->is_debug_types);
7661
7662   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
7663     {
7664       int ix, len;
7665       struct dwarf2_per_cu_data *per_cu_iter;
7666       struct symtab *symtab_iter;
7667       VEC (symtab_ptr) *result_symtabs = NULL;
7668       htab_t all_children, all_type_symtabs;
7669       struct symtab *symtab = get_symtab (per_cu);
7670
7671       /* If we don't have a symtab, we can just skip this case.  */
7672       if (symtab == NULL)
7673         return;
7674
7675       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7676                                         NULL, xcalloc, xfree);
7677       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
7678                                             NULL, xcalloc, xfree);
7679
7680       for (ix = 0;
7681            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
7682                         ix, per_cu_iter);
7683            ++ix)
7684         {
7685           recursively_compute_inclusions (&result_symtabs, all_children,
7686                                           all_type_symtabs, per_cu_iter,
7687                                           symtab);
7688         }
7689
7690       /* Now we have a transitive closure of all the included symtabs.  */
7691       len = VEC_length (symtab_ptr, result_symtabs);
7692       symtab->includes
7693         = obstack_alloc (&dwarf2_per_objfile->objfile->objfile_obstack,
7694                          (len + 1) * sizeof (struct symtab *));
7695       for (ix = 0;
7696            VEC_iterate (symtab_ptr, result_symtabs, ix, symtab_iter);
7697            ++ix)
7698         symtab->includes[ix] = symtab_iter;
7699       symtab->includes[len] = NULL;
7700
7701       VEC_free (symtab_ptr, result_symtabs);
7702       htab_delete (all_children);
7703       htab_delete (all_type_symtabs);
7704     }
7705 }
7706
7707 /* Compute the 'includes' field for the symtabs of all the CUs we just
7708    read.  */
7709
7710 static void
7711 process_cu_includes (void)
7712 {
7713   int ix;
7714   struct dwarf2_per_cu_data *iter;
7715
7716   for (ix = 0;
7717        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
7718                     ix, iter);
7719        ++ix)
7720     {
7721       if (! iter->is_debug_types)
7722         compute_symtab_includes (iter);
7723     }
7724
7725   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
7726 }
7727
7728 /* Generate full symbol information for PER_CU, whose DIEs have
7729    already been loaded into memory.  */
7730
7731 static void
7732 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
7733                         enum language pretend_language)
7734 {
7735   struct dwarf2_cu *cu = per_cu->cu;
7736   struct objfile *objfile = per_cu->objfile;
7737   CORE_ADDR lowpc, highpc;
7738   struct symtab *symtab;
7739   struct cleanup *back_to, *delayed_list_cleanup;
7740   CORE_ADDR baseaddr;
7741   struct block *static_block;
7742
7743   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7744
7745   buildsym_init ();
7746   back_to = make_cleanup (really_free_pendings, NULL);
7747   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7748
7749   cu->list_in_scope = &file_symbols;
7750
7751   cu->language = pretend_language;
7752   cu->language_defn = language_def (cu->language);
7753
7754   /* Do line number decoding in read_file_scope () */
7755   process_die (cu->dies, cu);
7756
7757   /* For now fudge the Go package.  */
7758   if (cu->language == language_go)
7759     fixup_go_packaging (cu);
7760
7761   /* Now that we have processed all the DIEs in the CU, all the types 
7762      should be complete, and it should now be safe to compute all of the
7763      physnames.  */
7764   compute_delayed_physnames (cu);
7765   do_cleanups (delayed_list_cleanup);
7766
7767   /* Some compilers don't define a DW_AT_high_pc attribute for the
7768      compilation unit.  If the DW_AT_high_pc is missing, synthesize
7769      it, by scanning the DIE's below the compilation unit.  */
7770   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
7771
7772   static_block
7773     = end_symtab_get_static_block (highpc + baseaddr, objfile, 0, 1);
7774
7775   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
7776      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
7777      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
7778      addrmap to help ensure it has an accurate map of pc values belonging to
7779      this comp unit.  */
7780   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
7781
7782   symtab = end_symtab_from_static_block (static_block, objfile,
7783                                          SECT_OFF_TEXT (objfile), 0);
7784
7785   if (symtab != NULL)
7786     {
7787       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
7788
7789       /* Set symtab language to language from DW_AT_language.  If the
7790          compilation is from a C file generated by language preprocessors, do
7791          not set the language if it was already deduced by start_subfile.  */
7792       if (!(cu->language == language_c && symtab->language != language_c))
7793         symtab->language = cu->language;
7794
7795       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
7796          produce DW_AT_location with location lists but it can be possibly
7797          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
7798          there were bugs in prologue debug info, fixed later in GCC-4.5
7799          by "unwind info for epilogues" patch (which is not directly related).
7800
7801          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
7802          needed, it would be wrong due to missing DW_AT_producer there.
7803
7804          Still one can confuse GDB by using non-standard GCC compilation
7805          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
7806          */ 
7807       if (cu->has_loclist && gcc_4_minor >= 5)
7808         symtab->locations_valid = 1;
7809
7810       if (gcc_4_minor >= 5)
7811         symtab->epilogue_unwind_valid = 1;
7812
7813       symtab->call_site_htab = cu->call_site_htab;
7814     }
7815
7816   if (dwarf2_per_objfile->using_index)
7817     per_cu->v.quick->symtab = symtab;
7818   else
7819     {
7820       struct partial_symtab *pst = per_cu->v.psymtab;
7821       pst->symtab = symtab;
7822       pst->readin = 1;
7823     }
7824
7825   /* Push it for inclusion processing later.  */
7826   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
7827
7828   do_cleanups (back_to);
7829 }
7830
7831 /* Generate full symbol information for type unit PER_CU, whose DIEs have
7832    already been loaded into memory.  */
7833
7834 static void
7835 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
7836                         enum language pretend_language)
7837 {
7838   struct dwarf2_cu *cu = per_cu->cu;
7839   struct objfile *objfile = per_cu->objfile;
7840   struct symtab *symtab;
7841   struct cleanup *back_to, *delayed_list_cleanup;
7842   struct signatured_type *sig_type;
7843
7844   gdb_assert (per_cu->is_debug_types);
7845   sig_type = (struct signatured_type *) per_cu;
7846
7847   buildsym_init ();
7848   back_to = make_cleanup (really_free_pendings, NULL);
7849   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
7850
7851   cu->list_in_scope = &file_symbols;
7852
7853   cu->language = pretend_language;
7854   cu->language_defn = language_def (cu->language);
7855
7856   /* The symbol tables are set up in read_type_unit_scope.  */
7857   process_die (cu->dies, cu);
7858
7859   /* For now fudge the Go package.  */
7860   if (cu->language == language_go)
7861     fixup_go_packaging (cu);
7862
7863   /* Now that we have processed all the DIEs in the CU, all the types 
7864      should be complete, and it should now be safe to compute all of the
7865      physnames.  */
7866   compute_delayed_physnames (cu);
7867   do_cleanups (delayed_list_cleanup);
7868
7869   /* TUs share symbol tables.
7870      If this is the first TU to use this symtab, complete the construction
7871      of it with end_expandable_symtab.  Otherwise, complete the addition of
7872      this TU's symbols to the existing symtab.  */
7873   if (sig_type->type_unit_group->primary_symtab == NULL)
7874     {
7875       symtab = end_expandable_symtab (0, objfile, SECT_OFF_TEXT (objfile));
7876       sig_type->type_unit_group->primary_symtab = symtab;
7877
7878       if (symtab != NULL)
7879         {
7880           /* Set symtab language to language from DW_AT_language.  If the
7881              compilation is from a C file generated by language preprocessors,
7882              do not set the language if it was already deduced by
7883              start_subfile.  */
7884           if (!(cu->language == language_c && symtab->language != language_c))
7885             symtab->language = cu->language;
7886         }
7887     }
7888   else
7889     {
7890       augment_type_symtab (objfile,
7891                            sig_type->type_unit_group->primary_symtab);
7892       symtab = sig_type->type_unit_group->primary_symtab;
7893     }
7894
7895   if (dwarf2_per_objfile->using_index)
7896     per_cu->v.quick->symtab = symtab;
7897   else
7898     {
7899       struct partial_symtab *pst = per_cu->v.psymtab;
7900       pst->symtab = symtab;
7901       pst->readin = 1;
7902     }
7903
7904   do_cleanups (back_to);
7905 }
7906
7907 /* Process an imported unit DIE.  */
7908
7909 static void
7910 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
7911 {
7912   struct attribute *attr;
7913
7914   /* For now we don't handle imported units in type units.  */
7915   if (cu->per_cu->is_debug_types)
7916     {
7917       error (_("Dwarf Error: DW_TAG_imported_unit is not"
7918                " supported in type units [in module %s]"),
7919              objfile_name (cu->objfile));
7920     }
7921
7922   attr = dwarf2_attr (die, DW_AT_import, cu);
7923   if (attr != NULL)
7924     {
7925       struct dwarf2_per_cu_data *per_cu;
7926       struct symtab *imported_symtab;
7927       sect_offset offset;
7928       int is_dwz;
7929
7930       offset = dwarf2_get_ref_die_offset (attr);
7931       is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
7932       per_cu = dwarf2_find_containing_comp_unit (offset, is_dwz, cu->objfile);
7933
7934       /* If necessary, add it to the queue and load its DIEs.  */
7935       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
7936         load_full_comp_unit (per_cu, cu->language);
7937
7938       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7939                      per_cu);
7940     }
7941 }
7942
7943 /* Process a die and its children.  */
7944
7945 static void
7946 process_die (struct die_info *die, struct dwarf2_cu *cu)
7947 {
7948   switch (die->tag)
7949     {
7950     case DW_TAG_padding:
7951       break;
7952     case DW_TAG_compile_unit:
7953     case DW_TAG_partial_unit:
7954       read_file_scope (die, cu);
7955       break;
7956     case DW_TAG_type_unit:
7957       read_type_unit_scope (die, cu);
7958       break;
7959     case DW_TAG_subprogram:
7960     case DW_TAG_inlined_subroutine:
7961       read_func_scope (die, cu);
7962       break;
7963     case DW_TAG_lexical_block:
7964     case DW_TAG_try_block:
7965     case DW_TAG_catch_block:
7966       read_lexical_block_scope (die, cu);
7967       break;
7968     case DW_TAG_GNU_call_site:
7969       read_call_site_scope (die, cu);
7970       break;
7971     case DW_TAG_class_type:
7972     case DW_TAG_interface_type:
7973     case DW_TAG_structure_type:
7974     case DW_TAG_union_type:
7975       process_structure_scope (die, cu);
7976       break;
7977     case DW_TAG_enumeration_type:
7978       process_enumeration_scope (die, cu);
7979       break;
7980
7981     /* These dies have a type, but processing them does not create
7982        a symbol or recurse to process the children.  Therefore we can
7983        read them on-demand through read_type_die.  */
7984     case DW_TAG_subroutine_type:
7985     case DW_TAG_set_type:
7986     case DW_TAG_array_type:
7987     case DW_TAG_pointer_type:
7988     case DW_TAG_ptr_to_member_type:
7989     case DW_TAG_reference_type:
7990     case DW_TAG_string_type:
7991       break;
7992
7993     case DW_TAG_base_type:
7994     case DW_TAG_subrange_type:
7995     case DW_TAG_typedef:
7996       /* Add a typedef symbol for the type definition, if it has a
7997          DW_AT_name.  */
7998       new_symbol (die, read_type_die (die, cu), cu);
7999       break;
8000     case DW_TAG_common_block:
8001       read_common_block (die, cu);
8002       break;
8003     case DW_TAG_common_inclusion:
8004       break;
8005     case DW_TAG_namespace:
8006       cu->processing_has_namespace_info = 1;
8007       read_namespace (die, cu);
8008       break;
8009     case DW_TAG_module:
8010       cu->processing_has_namespace_info = 1;
8011       read_module (die, cu);
8012       break;
8013     case DW_TAG_imported_declaration:
8014     case DW_TAG_imported_module:
8015       cu->processing_has_namespace_info = 1;
8016       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8017                                  || cu->language != language_fortran))
8018         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8019                    dwarf_tag_name (die->tag));
8020       read_import_statement (die, cu);
8021       break;
8022
8023     case DW_TAG_imported_unit:
8024       process_imported_unit_die (die, cu);
8025       break;
8026
8027     default:
8028       new_symbol (die, NULL, cu);
8029       break;
8030     }
8031 }
8032 \f
8033 /* DWARF name computation.  */
8034
8035 /* A helper function for dwarf2_compute_name which determines whether DIE
8036    needs to have the name of the scope prepended to the name listed in the
8037    die.  */
8038
8039 static int
8040 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8041 {
8042   struct attribute *attr;
8043
8044   switch (die->tag)
8045     {
8046     case DW_TAG_namespace:
8047     case DW_TAG_typedef:
8048     case DW_TAG_class_type:
8049     case DW_TAG_interface_type:
8050     case DW_TAG_structure_type:
8051     case DW_TAG_union_type:
8052     case DW_TAG_enumeration_type:
8053     case DW_TAG_enumerator:
8054     case DW_TAG_subprogram:
8055     case DW_TAG_member:
8056       return 1;
8057
8058     case DW_TAG_variable:
8059     case DW_TAG_constant:
8060       /* We only need to prefix "globally" visible variables.  These include
8061          any variable marked with DW_AT_external or any variable that
8062          lives in a namespace.  [Variables in anonymous namespaces
8063          require prefixing, but they are not DW_AT_external.]  */
8064
8065       if (dwarf2_attr (die, DW_AT_specification, cu))
8066         {
8067           struct dwarf2_cu *spec_cu = cu;
8068
8069           return die_needs_namespace (die_specification (die, &spec_cu),
8070                                       spec_cu);
8071         }
8072
8073       attr = dwarf2_attr (die, DW_AT_external, cu);
8074       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8075           && die->parent->tag != DW_TAG_module)
8076         return 0;
8077       /* A variable in a lexical block of some kind does not need a
8078          namespace, even though in C++ such variables may be external
8079          and have a mangled name.  */
8080       if (die->parent->tag ==  DW_TAG_lexical_block
8081           || die->parent->tag ==  DW_TAG_try_block
8082           || die->parent->tag ==  DW_TAG_catch_block
8083           || die->parent->tag == DW_TAG_subprogram)
8084         return 0;
8085       return 1;
8086
8087     default:
8088       return 0;
8089     }
8090 }
8091
8092 /* Retrieve the last character from a mem_file.  */
8093
8094 static void
8095 do_ui_file_peek_last (void *object, const char *buffer, long length)
8096 {
8097   char *last_char_p = (char *) object;
8098
8099   if (length > 0)
8100     *last_char_p = buffer[length - 1];
8101 }
8102
8103 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8104    compute the physname for the object, which include a method's:
8105    - formal parameters (C++/Java),
8106    - receiver type (Go),
8107    - return type (Java).
8108
8109    The term "physname" is a bit confusing.
8110    For C++, for example, it is the demangled name.
8111    For Go, for example, it's the mangled name.
8112
8113    For Ada, return the DIE's linkage name rather than the fully qualified
8114    name.  PHYSNAME is ignored..
8115
8116    The result is allocated on the objfile_obstack and canonicalized.  */
8117
8118 static const char *
8119 dwarf2_compute_name (const char *name,
8120                      struct die_info *die, struct dwarf2_cu *cu,
8121                      int physname)
8122 {
8123   struct objfile *objfile = cu->objfile;
8124
8125   if (name == NULL)
8126     name = dwarf2_name (die, cu);
8127
8128   /* For Fortran GDB prefers DW_AT_*linkage_name if present but otherwise
8129      compute it by typename_concat inside GDB.  */
8130   if (cu->language == language_ada
8131       || (cu->language == language_fortran && physname))
8132     {
8133       /* For Ada unit, we prefer the linkage name over the name, as
8134          the former contains the exported name, which the user expects
8135          to be able to reference.  Ideally, we want the user to be able
8136          to reference this entity using either natural or linkage name,
8137          but we haven't started looking at this enhancement yet.  */
8138       struct attribute *attr;
8139
8140       attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8141       if (attr == NULL)
8142         attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8143       if (attr && DW_STRING (attr))
8144         return DW_STRING (attr);
8145     }
8146
8147   /* These are the only languages we know how to qualify names in.  */
8148   if (name != NULL
8149       && (cu->language == language_cplus || cu->language == language_java
8150           || cu->language == language_fortran))
8151     {
8152       if (die_needs_namespace (die, cu))
8153         {
8154           long length;
8155           const char *prefix;
8156           struct ui_file *buf;
8157
8158           prefix = determine_prefix (die, cu);
8159           buf = mem_fileopen ();
8160           if (*prefix != '\0')
8161             {
8162               char *prefixed_name = typename_concat (NULL, prefix, name,
8163                                                      physname, cu);
8164
8165               fputs_unfiltered (prefixed_name, buf);
8166               xfree (prefixed_name);
8167             }
8168           else
8169             fputs_unfiltered (name, buf);
8170
8171           /* Template parameters may be specified in the DIE's DW_AT_name, or
8172              as children with DW_TAG_template_type_param or
8173              DW_TAG_value_type_param.  If the latter, add them to the name
8174              here.  If the name already has template parameters, then
8175              skip this step; some versions of GCC emit both, and
8176              it is more efficient to use the pre-computed name.
8177
8178              Something to keep in mind about this process: it is very
8179              unlikely, or in some cases downright impossible, to produce
8180              something that will match the mangled name of a function.
8181              If the definition of the function has the same debug info,
8182              we should be able to match up with it anyway.  But fallbacks
8183              using the minimal symbol, for instance to find a method
8184              implemented in a stripped copy of libstdc++, will not work.
8185              If we do not have debug info for the definition, we will have to
8186              match them up some other way.
8187
8188              When we do name matching there is a related problem with function
8189              templates; two instantiated function templates are allowed to
8190              differ only by their return types, which we do not add here.  */
8191
8192           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8193             {
8194               struct attribute *attr;
8195               struct die_info *child;
8196               int first = 1;
8197
8198               die->building_fullname = 1;
8199
8200               for (child = die->child; child != NULL; child = child->sibling)
8201                 {
8202                   struct type *type;
8203                   LONGEST value;
8204                   const gdb_byte *bytes;
8205                   struct dwarf2_locexpr_baton *baton;
8206                   struct value *v;
8207
8208                   if (child->tag != DW_TAG_template_type_param
8209                       && child->tag != DW_TAG_template_value_param)
8210                     continue;
8211
8212                   if (first)
8213                     {
8214                       fputs_unfiltered ("<", buf);
8215                       first = 0;
8216                     }
8217                   else
8218                     fputs_unfiltered (", ", buf);
8219
8220                   attr = dwarf2_attr (child, DW_AT_type, cu);
8221                   if (attr == NULL)
8222                     {
8223                       complaint (&symfile_complaints,
8224                                  _("template parameter missing DW_AT_type"));
8225                       fputs_unfiltered ("UNKNOWN_TYPE", buf);
8226                       continue;
8227                     }
8228                   type = die_type (child, cu);
8229
8230                   if (child->tag == DW_TAG_template_type_param)
8231                     {
8232                       c_print_type (type, "", buf, -1, 0, &type_print_raw_options);
8233                       continue;
8234                     }
8235
8236                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8237                   if (attr == NULL)
8238                     {
8239                       complaint (&symfile_complaints,
8240                                  _("template parameter missing "
8241                                    "DW_AT_const_value"));
8242                       fputs_unfiltered ("UNKNOWN_VALUE", buf);
8243                       continue;
8244                     }
8245
8246                   dwarf2_const_value_attr (attr, type, name,
8247                                            &cu->comp_unit_obstack, cu,
8248                                            &value, &bytes, &baton);
8249
8250                   if (TYPE_NOSIGN (type))
8251                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8252                        changed, this can use value_print instead.  */
8253                     c_printchar (value, type, buf);
8254                   else
8255                     {
8256                       struct value_print_options opts;
8257
8258                       if (baton != NULL)
8259                         v = dwarf2_evaluate_loc_desc (type, NULL,
8260                                                       baton->data,
8261                                                       baton->size,
8262                                                       baton->per_cu);
8263                       else if (bytes != NULL)
8264                         {
8265                           v = allocate_value (type);
8266                           memcpy (value_contents_writeable (v), bytes,
8267                                   TYPE_LENGTH (type));
8268                         }
8269                       else
8270                         v = value_from_longest (type, value);
8271
8272                       /* Specify decimal so that we do not depend on
8273                          the radix.  */
8274                       get_formatted_print_options (&opts, 'd');
8275                       opts.raw = 1;
8276                       value_print (v, buf, &opts);
8277                       release_value (v);
8278                       value_free (v);
8279                     }
8280                 }
8281
8282               die->building_fullname = 0;
8283
8284               if (!first)
8285                 {
8286                   /* Close the argument list, with a space if necessary
8287                      (nested templates).  */
8288                   char last_char = '\0';
8289                   ui_file_put (buf, do_ui_file_peek_last, &last_char);
8290                   if (last_char == '>')
8291                     fputs_unfiltered (" >", buf);
8292                   else
8293                     fputs_unfiltered (">", buf);
8294                 }
8295             }
8296
8297           /* For Java and C++ methods, append formal parameter type
8298              information, if PHYSNAME.  */
8299
8300           if (physname && die->tag == DW_TAG_subprogram
8301               && (cu->language == language_cplus
8302                   || cu->language == language_java))
8303             {
8304               struct type *type = read_type_die (die, cu);
8305
8306               c_type_print_args (type, buf, 1, cu->language,
8307                                  &type_print_raw_options);
8308
8309               if (cu->language == language_java)
8310                 {
8311                   /* For java, we must append the return type to method
8312                      names.  */
8313                   if (die->tag == DW_TAG_subprogram)
8314                     java_print_type (TYPE_TARGET_TYPE (type), "", buf,
8315                                      0, 0, &type_print_raw_options);
8316                 }
8317               else if (cu->language == language_cplus)
8318                 {
8319                   /* Assume that an artificial first parameter is
8320                      "this", but do not crash if it is not.  RealView
8321                      marks unnamed (and thus unused) parameters as
8322                      artificial; there is no way to differentiate
8323                      the two cases.  */
8324                   if (TYPE_NFIELDS (type) > 0
8325                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8326                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8327                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8328                                                                         0))))
8329                     fputs_unfiltered (" const", buf);
8330                 }
8331             }
8332
8333           name = ui_file_obsavestring (buf, &objfile->objfile_obstack,
8334                                        &length);
8335           ui_file_delete (buf);
8336
8337           if (cu->language == language_cplus)
8338             {
8339               const char *cname
8340                 = dwarf2_canonicalize_name (name, cu,
8341                                             &objfile->objfile_obstack);
8342
8343               if (cname != NULL)
8344                 name = cname;
8345             }
8346         }
8347     }
8348
8349   return name;
8350 }
8351
8352 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8353    If scope qualifiers are appropriate they will be added.  The result
8354    will be allocated on the objfile_obstack, or NULL if the DIE does
8355    not have a name.  NAME may either be from a previous call to
8356    dwarf2_name or NULL.
8357
8358    The output string will be canonicalized (if C++/Java).  */
8359
8360 static const char *
8361 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8362 {
8363   return dwarf2_compute_name (name, die, cu, 0);
8364 }
8365
8366 /* Construct a physname for the given DIE in CU.  NAME may either be
8367    from a previous call to dwarf2_name or NULL.  The result will be
8368    allocated on the objfile_objstack or NULL if the DIE does not have a
8369    name.
8370
8371    The output string will be canonicalized (if C++/Java).  */
8372
8373 static const char *
8374 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
8375 {
8376   struct objfile *objfile = cu->objfile;
8377   struct attribute *attr;
8378   const char *retval, *mangled = NULL, *canon = NULL;
8379   struct cleanup *back_to;
8380   int need_copy = 1;
8381
8382   /* In this case dwarf2_compute_name is just a shortcut not building anything
8383      on its own.  */
8384   if (!die_needs_namespace (die, cu))
8385     return dwarf2_compute_name (name, die, cu, 1);
8386
8387   back_to = make_cleanup (null_cleanup, NULL);
8388
8389   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8390   if (!attr)
8391     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8392
8393   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
8394      has computed.  */
8395   if (attr && DW_STRING (attr))
8396     {
8397       char *demangled;
8398
8399       mangled = DW_STRING (attr);
8400
8401       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
8402          type.  It is easier for GDB users to search for such functions as
8403          `name(params)' than `long name(params)'.  In such case the minimal
8404          symbol names do not match the full symbol names but for template
8405          functions there is never a need to look up their definition from their
8406          declaration so the only disadvantage remains the minimal symbol
8407          variant `long name(params)' does not have the proper inferior type.
8408          */
8409
8410       if (cu->language == language_go)
8411         {
8412           /* This is a lie, but we already lie to the caller new_symbol_full.
8413              new_symbol_full assumes we return the mangled name.
8414              This just undoes that lie until things are cleaned up.  */
8415           demangled = NULL;
8416         }
8417       else
8418         {
8419           demangled = gdb_demangle (mangled,
8420                                     (DMGL_PARAMS | DMGL_ANSI
8421                                      | (cu->language == language_java
8422                                         ? DMGL_JAVA | DMGL_RET_POSTFIX
8423                                         : DMGL_RET_DROP)));
8424         }
8425       if (demangled)
8426         {
8427           make_cleanup (xfree, demangled);
8428           canon = demangled;
8429         }
8430       else
8431         {
8432           canon = mangled;
8433           need_copy = 0;
8434         }
8435     }
8436
8437   if (canon == NULL || check_physname)
8438     {
8439       const char *physname = dwarf2_compute_name (name, die, cu, 1);
8440
8441       if (canon != NULL && strcmp (physname, canon) != 0)
8442         {
8443           /* It may not mean a bug in GDB.  The compiler could also
8444              compute DW_AT_linkage_name incorrectly.  But in such case
8445              GDB would need to be bug-to-bug compatible.  */
8446
8447           complaint (&symfile_complaints,
8448                      _("Computed physname <%s> does not match demangled <%s> "
8449                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
8450                      physname, canon, mangled, die->offset.sect_off,
8451                      objfile_name (objfile));
8452
8453           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
8454              is available here - over computed PHYSNAME.  It is safer
8455              against both buggy GDB and buggy compilers.  */
8456
8457           retval = canon;
8458         }
8459       else
8460         {
8461           retval = physname;
8462           need_copy = 0;
8463         }
8464     }
8465   else
8466     retval = canon;
8467
8468   if (need_copy)
8469     retval = obstack_copy0 (&objfile->objfile_obstack, retval, strlen (retval));
8470
8471   do_cleanups (back_to);
8472   return retval;
8473 }
8474
8475 /* Read the import statement specified by the given die and record it.  */
8476
8477 static void
8478 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
8479 {
8480   struct objfile *objfile = cu->objfile;
8481   struct attribute *import_attr;
8482   struct die_info *imported_die, *child_die;
8483   struct dwarf2_cu *imported_cu;
8484   const char *imported_name;
8485   const char *imported_name_prefix;
8486   const char *canonical_name;
8487   const char *import_alias;
8488   const char *imported_declaration = NULL;
8489   const char *import_prefix;
8490   VEC (const_char_ptr) *excludes = NULL;
8491   struct cleanup *cleanups;
8492
8493   import_attr = dwarf2_attr (die, DW_AT_import, cu);
8494   if (import_attr == NULL)
8495     {
8496       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8497                  dwarf_tag_name (die->tag));
8498       return;
8499     }
8500
8501   imported_cu = cu;
8502   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
8503   imported_name = dwarf2_name (imported_die, imported_cu);
8504   if (imported_name == NULL)
8505     {
8506       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
8507
8508         The import in the following code:
8509         namespace A
8510           {
8511             typedef int B;
8512           }
8513
8514         int main ()
8515           {
8516             using A::B;
8517             B b;
8518             return b;
8519           }
8520
8521         ...
8522          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
8523             <52>   DW_AT_decl_file   : 1
8524             <53>   DW_AT_decl_line   : 6
8525             <54>   DW_AT_import      : <0x75>
8526          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
8527             <59>   DW_AT_name        : B
8528             <5b>   DW_AT_decl_file   : 1
8529             <5c>   DW_AT_decl_line   : 2
8530             <5d>   DW_AT_type        : <0x6e>
8531         ...
8532          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
8533             <76>   DW_AT_byte_size   : 4
8534             <77>   DW_AT_encoding    : 5        (signed)
8535
8536         imports the wrong die ( 0x75 instead of 0x58 ).
8537         This case will be ignored until the gcc bug is fixed.  */
8538       return;
8539     }
8540
8541   /* Figure out the local name after import.  */
8542   import_alias = dwarf2_name (die, cu);
8543
8544   /* Figure out where the statement is being imported to.  */
8545   import_prefix = determine_prefix (die, cu);
8546
8547   /* Figure out what the scope of the imported die is and prepend it
8548      to the name of the imported die.  */
8549   imported_name_prefix = determine_prefix (imported_die, imported_cu);
8550
8551   if (imported_die->tag != DW_TAG_namespace
8552       && imported_die->tag != DW_TAG_module)
8553     {
8554       imported_declaration = imported_name;
8555       canonical_name = imported_name_prefix;
8556     }
8557   else if (strlen (imported_name_prefix) > 0)
8558     canonical_name = obconcat (&objfile->objfile_obstack,
8559                                imported_name_prefix, "::", imported_name,
8560                                (char *) NULL);
8561   else
8562     canonical_name = imported_name;
8563
8564   cleanups = make_cleanup (VEC_cleanup (const_char_ptr), &excludes);
8565
8566   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
8567     for (child_die = die->child; child_die && child_die->tag;
8568          child_die = sibling_die (child_die))
8569       {
8570         /* DWARF-4: A Fortran use statement with a “rename list” may be
8571            represented by an imported module entry with an import attribute
8572            referring to the module and owned entries corresponding to those
8573            entities that are renamed as part of being imported.  */
8574
8575         if (child_die->tag != DW_TAG_imported_declaration)
8576           {
8577             complaint (&symfile_complaints,
8578                        _("child DW_TAG_imported_declaration expected "
8579                          "- DIE at 0x%x [in module %s]"),
8580                        child_die->offset.sect_off, objfile_name (objfile));
8581             continue;
8582           }
8583
8584         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
8585         if (import_attr == NULL)
8586           {
8587             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
8588                        dwarf_tag_name (child_die->tag));
8589             continue;
8590           }
8591
8592         imported_cu = cu;
8593         imported_die = follow_die_ref_or_sig (child_die, import_attr,
8594                                               &imported_cu);
8595         imported_name = dwarf2_name (imported_die, imported_cu);
8596         if (imported_name == NULL)
8597           {
8598             complaint (&symfile_complaints,
8599                        _("child DW_TAG_imported_declaration has unknown "
8600                          "imported name - DIE at 0x%x [in module %s]"),
8601                        child_die->offset.sect_off, objfile_name (objfile));
8602             continue;
8603           }
8604
8605         VEC_safe_push (const_char_ptr, excludes, imported_name);
8606
8607         process_die (child_die, cu);
8608       }
8609
8610   cp_add_using_directive (import_prefix,
8611                           canonical_name,
8612                           import_alias,
8613                           imported_declaration,
8614                           excludes,
8615                           0,
8616                           &objfile->objfile_obstack);
8617
8618   do_cleanups (cleanups);
8619 }
8620
8621 /* Cleanup function for handle_DW_AT_stmt_list.  */
8622
8623 static void
8624 free_cu_line_header (void *arg)
8625 {
8626   struct dwarf2_cu *cu = arg;
8627
8628   free_line_header (cu->line_header);
8629   cu->line_header = NULL;
8630 }
8631
8632 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
8633    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
8634    this, it was first present in GCC release 4.3.0.  */
8635
8636 static int
8637 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
8638 {
8639   if (!cu->checked_producer)
8640     check_producer (cu);
8641
8642   return cu->producer_is_gcc_lt_4_3;
8643 }
8644
8645 static void
8646 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu,
8647                          const char **name, const char **comp_dir)
8648 {
8649   struct attribute *attr;
8650
8651   *name = NULL;
8652   *comp_dir = NULL;
8653
8654   /* Find the filename.  Do not use dwarf2_name here, since the filename
8655      is not a source language identifier.  */
8656   attr = dwarf2_attr (die, DW_AT_name, cu);
8657   if (attr)
8658     {
8659       *name = DW_STRING (attr);
8660     }
8661
8662   attr = dwarf2_attr (die, DW_AT_comp_dir, cu);
8663   if (attr)
8664     *comp_dir = DW_STRING (attr);
8665   else if (producer_is_gcc_lt_4_3 (cu) && *name != NULL
8666            && IS_ABSOLUTE_PATH (*name))
8667     {
8668       char *d = ldirname (*name);
8669
8670       *comp_dir = d;
8671       if (d != NULL)
8672         make_cleanup (xfree, d);
8673     }
8674   if (*comp_dir != NULL)
8675     {
8676       /* Irix 6.2 native cc prepends <machine>.: to the compilation
8677          directory, get rid of it.  */
8678       char *cp = strchr (*comp_dir, ':');
8679
8680       if (cp && cp != *comp_dir && cp[-1] == '.' && cp[1] == '/')
8681         *comp_dir = cp + 1;
8682     }
8683
8684   if (*name == NULL)
8685     *name = "<unknown>";
8686 }
8687
8688 /* Handle DW_AT_stmt_list for a compilation unit.
8689    DIE is the DW_TAG_compile_unit die for CU.
8690    COMP_DIR is the compilation directory.
8691    WANT_LINE_INFO is non-zero if the pc/line-number mapping is needed.  */
8692
8693 static void
8694 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
8695                         const char *comp_dir) /* ARI: editCase function */
8696 {
8697   struct attribute *attr;
8698
8699   gdb_assert (! cu->per_cu->is_debug_types);
8700
8701   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8702   if (attr)
8703     {
8704       unsigned int line_offset = DW_UNSND (attr);
8705       struct line_header *line_header
8706         = dwarf_decode_line_header (line_offset, cu);
8707
8708       if (line_header)
8709         {
8710           cu->line_header = line_header;
8711           make_cleanup (free_cu_line_header, cu);
8712           dwarf_decode_lines (line_header, comp_dir, cu, NULL, 1);
8713         }
8714     }
8715 }
8716
8717 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
8718
8719 static void
8720 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
8721 {
8722   struct objfile *objfile = dwarf2_per_objfile->objfile;
8723   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
8724   CORE_ADDR lowpc = ((CORE_ADDR) -1);
8725   CORE_ADDR highpc = ((CORE_ADDR) 0);
8726   struct attribute *attr;
8727   const char *name = NULL;
8728   const char *comp_dir = NULL;
8729   struct die_info *child_die;
8730   bfd *abfd = objfile->obfd;
8731   CORE_ADDR baseaddr;
8732
8733   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8734
8735   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
8736
8737   /* If we didn't find a lowpc, set it to highpc to avoid complaints
8738      from finish_block.  */
8739   if (lowpc == ((CORE_ADDR) -1))
8740     lowpc = highpc;
8741   lowpc += baseaddr;
8742   highpc += baseaddr;
8743
8744   find_file_and_directory (die, cu, &name, &comp_dir);
8745
8746   prepare_one_comp_unit (cu, die, cu->language);
8747
8748   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
8749      standardised yet.  As a workaround for the language detection we fall
8750      back to the DW_AT_producer string.  */
8751   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
8752     cu->language = language_opencl;
8753
8754   /* Similar hack for Go.  */
8755   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
8756     set_cu_language (DW_LANG_Go, cu);
8757
8758   dwarf2_start_symtab (cu, name, comp_dir, lowpc);
8759
8760   /* Decode line number information if present.  We do this before
8761      processing child DIEs, so that the line header table is available
8762      for DW_AT_decl_file.  */
8763   handle_DW_AT_stmt_list (die, cu, comp_dir);
8764
8765   /* Process all dies in compilation unit.  */
8766   if (die->child != NULL)
8767     {
8768       child_die = die->child;
8769       while (child_die && child_die->tag)
8770         {
8771           process_die (child_die, cu);
8772           child_die = sibling_die (child_die);
8773         }
8774     }
8775
8776   /* Decode macro information, if present.  Dwarf 2 macro information
8777      refers to information in the line number info statement program
8778      header, so we can only read it if we've read the header
8779      successfully.  */
8780   attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
8781   if (attr && cu->line_header)
8782     {
8783       if (dwarf2_attr (die, DW_AT_macro_info, cu))
8784         complaint (&symfile_complaints,
8785                    _("CU refers to both DW_AT_GNU_macros and DW_AT_macro_info"));
8786
8787       dwarf_decode_macros (cu, DW_UNSND (attr), comp_dir, 1);
8788     }
8789   else
8790     {
8791       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
8792       if (attr && cu->line_header)
8793         {
8794           unsigned int macro_offset = DW_UNSND (attr);
8795
8796           dwarf_decode_macros (cu, macro_offset, comp_dir, 0);
8797         }
8798     }
8799
8800   do_cleanups (back_to);
8801 }
8802
8803 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
8804    Create the set of symtabs used by this TU, or if this TU is sharing
8805    symtabs with another TU and the symtabs have already been created
8806    then restore those symtabs in the line header.
8807    We don't need the pc/line-number mapping for type units.  */
8808
8809 static void
8810 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
8811 {
8812   struct objfile *objfile = dwarf2_per_objfile->objfile;
8813   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8814   struct type_unit_group *tu_group;
8815   int first_time;
8816   struct line_header *lh;
8817   struct attribute *attr;
8818   unsigned int i, line_offset;
8819   struct signatured_type *sig_type;
8820
8821   gdb_assert (per_cu->is_debug_types);
8822   sig_type = (struct signatured_type *) per_cu;
8823
8824   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
8825
8826   /* If we're using .gdb_index (includes -readnow) then
8827      per_cu->type_unit_group may not have been set up yet.  */
8828   if (sig_type->type_unit_group == NULL)
8829     sig_type->type_unit_group = get_type_unit_group (cu, attr);
8830   tu_group = sig_type->type_unit_group;
8831
8832   /* If we've already processed this stmt_list there's no real need to
8833      do it again, we could fake it and just recreate the part we need
8834      (file name,index -> symtab mapping).  If data shows this optimization
8835      is useful we can do it then.  */
8836   first_time = tu_group->primary_symtab == NULL;
8837
8838   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
8839      debug info.  */
8840   lh = NULL;
8841   if (attr != NULL)
8842     {
8843       line_offset = DW_UNSND (attr);
8844       lh = dwarf_decode_line_header (line_offset, cu);
8845     }
8846   if (lh == NULL)
8847     {
8848       if (first_time)
8849         dwarf2_start_symtab (cu, "", NULL, 0);
8850       else
8851         {
8852           gdb_assert (tu_group->symtabs == NULL);
8853           restart_symtab (0);
8854         }
8855       /* Note: The primary symtab will get allocated at the end.  */
8856       return;
8857     }
8858
8859   cu->line_header = lh;
8860   make_cleanup (free_cu_line_header, cu);
8861
8862   if (first_time)
8863     {
8864       dwarf2_start_symtab (cu, "", NULL, 0);
8865
8866       tu_group->num_symtabs = lh->num_file_names;
8867       tu_group->symtabs = XNEWVEC (struct symtab *, lh->num_file_names);
8868
8869       for (i = 0; i < lh->num_file_names; ++i)
8870         {
8871           const char *dir = NULL;
8872           struct file_entry *fe = &lh->file_names[i];
8873
8874           if (fe->dir_index)
8875             dir = lh->include_dirs[fe->dir_index - 1];
8876           dwarf2_start_subfile (fe->name, dir, NULL);
8877
8878           /* Note: We don't have to watch for the main subfile here, type units
8879              don't have DW_AT_name.  */
8880
8881           if (current_subfile->symtab == NULL)
8882             {
8883               /* NOTE: start_subfile will recognize when it's been passed
8884                  a file it has already seen.  So we can't assume there's a
8885                  simple mapping from lh->file_names to subfiles,
8886                  lh->file_names may contain dups.  */
8887               current_subfile->symtab = allocate_symtab (current_subfile->name,
8888                                                          objfile);
8889             }
8890
8891           fe->symtab = current_subfile->symtab;
8892           tu_group->symtabs[i] = fe->symtab;
8893         }
8894     }
8895   else
8896     {
8897       restart_symtab (0);
8898
8899       for (i = 0; i < lh->num_file_names; ++i)
8900         {
8901           struct file_entry *fe = &lh->file_names[i];
8902
8903           fe->symtab = tu_group->symtabs[i];
8904         }
8905     }
8906
8907   /* The main symtab is allocated last.  Type units don't have DW_AT_name
8908      so they don't have a "real" (so to speak) symtab anyway.
8909      There is later code that will assign the main symtab to all symbols
8910      that don't have one.  We need to handle the case of a symbol with a
8911      missing symtab (DW_AT_decl_file) anyway.  */
8912 }
8913
8914 /* Process DW_TAG_type_unit.
8915    For TUs we want to skip the first top level sibling if it's not the
8916    actual type being defined by this TU.  In this case the first top
8917    level sibling is there to provide context only.  */
8918
8919 static void
8920 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
8921 {
8922   struct die_info *child_die;
8923
8924   prepare_one_comp_unit (cu, die, language_minimal);
8925
8926   /* Initialize (or reinitialize) the machinery for building symtabs.
8927      We do this before processing child DIEs, so that the line header table
8928      is available for DW_AT_decl_file.  */
8929   setup_type_unit_groups (die, cu);
8930
8931   if (die->child != NULL)
8932     {
8933       child_die = die->child;
8934       while (child_die && child_die->tag)
8935         {
8936           process_die (child_die, cu);
8937           child_die = sibling_die (child_die);
8938         }
8939     }
8940 }
8941 \f
8942 /* DWO/DWP files.
8943
8944    http://gcc.gnu.org/wiki/DebugFission
8945    http://gcc.gnu.org/wiki/DebugFissionDWP
8946
8947    To simplify handling of both DWO files ("object" files with the DWARF info)
8948    and DWP files (a file with the DWOs packaged up into one file), we treat
8949    DWP files as having a collection of virtual DWO files.  */
8950
8951 static hashval_t
8952 hash_dwo_file (const void *item)
8953 {
8954   const struct dwo_file *dwo_file = item;
8955   hashval_t hash;
8956
8957   hash = htab_hash_string (dwo_file->dwo_name);
8958   if (dwo_file->comp_dir != NULL)
8959     hash += htab_hash_string (dwo_file->comp_dir);
8960   return hash;
8961 }
8962
8963 static int
8964 eq_dwo_file (const void *item_lhs, const void *item_rhs)
8965 {
8966   const struct dwo_file *lhs = item_lhs;
8967   const struct dwo_file *rhs = item_rhs;
8968
8969   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
8970     return 0;
8971   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
8972     return lhs->comp_dir == rhs->comp_dir;
8973   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
8974 }
8975
8976 /* Allocate a hash table for DWO files.  */
8977
8978 static htab_t
8979 allocate_dwo_file_hash_table (void)
8980 {
8981   struct objfile *objfile = dwarf2_per_objfile->objfile;
8982
8983   return htab_create_alloc_ex (41,
8984                                hash_dwo_file,
8985                                eq_dwo_file,
8986                                NULL,
8987                                &objfile->objfile_obstack,
8988                                hashtab_obstack_allocate,
8989                                dummy_obstack_deallocate);
8990 }
8991
8992 /* Lookup DWO file DWO_NAME.  */
8993
8994 static void **
8995 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
8996 {
8997   struct dwo_file find_entry;
8998   void **slot;
8999
9000   if (dwarf2_per_objfile->dwo_files == NULL)
9001     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9002
9003   memset (&find_entry, 0, sizeof (find_entry));
9004   find_entry.dwo_name = dwo_name;
9005   find_entry.comp_dir = comp_dir;
9006   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9007
9008   return slot;
9009 }
9010
9011 static hashval_t
9012 hash_dwo_unit (const void *item)
9013 {
9014   const struct dwo_unit *dwo_unit = item;
9015
9016   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9017   return dwo_unit->signature;
9018 }
9019
9020 static int
9021 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9022 {
9023   const struct dwo_unit *lhs = item_lhs;
9024   const struct dwo_unit *rhs = item_rhs;
9025
9026   /* The signature is assumed to be unique within the DWO file.
9027      So while object file CU dwo_id's always have the value zero,
9028      that's OK, assuming each object file DWO file has only one CU,
9029      and that's the rule for now.  */
9030   return lhs->signature == rhs->signature;
9031 }
9032
9033 /* Allocate a hash table for DWO CUs,TUs.
9034    There is one of these tables for each of CUs,TUs for each DWO file.  */
9035
9036 static htab_t
9037 allocate_dwo_unit_table (struct objfile *objfile)
9038 {
9039   /* Start out with a pretty small number.
9040      Generally DWO files contain only one CU and maybe some TUs.  */
9041   return htab_create_alloc_ex (3,
9042                                hash_dwo_unit,
9043                                eq_dwo_unit,
9044                                NULL,
9045                                &objfile->objfile_obstack,
9046                                hashtab_obstack_allocate,
9047                                dummy_obstack_deallocate);
9048 }
9049
9050 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9051
9052 struct create_dwo_cu_data
9053 {
9054   struct dwo_file *dwo_file;
9055   struct dwo_unit dwo_unit;
9056 };
9057
9058 /* die_reader_func for create_dwo_cu.  */
9059
9060 static void
9061 create_dwo_cu_reader (const struct die_reader_specs *reader,
9062                       const gdb_byte *info_ptr,
9063                       struct die_info *comp_unit_die,
9064                       int has_children,
9065                       void *datap)
9066 {
9067   struct dwarf2_cu *cu = reader->cu;
9068   struct objfile *objfile = dwarf2_per_objfile->objfile;
9069   sect_offset offset = cu->per_cu->offset;
9070   struct dwarf2_section_info *section = cu->per_cu->section;
9071   struct create_dwo_cu_data *data = datap;
9072   struct dwo_file *dwo_file = data->dwo_file;
9073   struct dwo_unit *dwo_unit = &data->dwo_unit;
9074   struct attribute *attr;
9075
9076   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9077   if (attr == NULL)
9078     {
9079       complaint (&symfile_complaints,
9080                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9081                    " its dwo_id [in module %s]"),
9082                  offset.sect_off, dwo_file->dwo_name);
9083       return;
9084     }
9085
9086   dwo_unit->dwo_file = dwo_file;
9087   dwo_unit->signature = DW_UNSND (attr);
9088   dwo_unit->section = section;
9089   dwo_unit->offset = offset;
9090   dwo_unit->length = cu->per_cu->length;
9091
9092   if (dwarf2_read_debug)
9093     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9094                         offset.sect_off, hex_string (dwo_unit->signature));
9095 }
9096
9097 /* Create the dwo_unit for the lone CU in DWO_FILE.
9098    Note: This function processes DWO files only, not DWP files.  */
9099
9100 static struct dwo_unit *
9101 create_dwo_cu (struct dwo_file *dwo_file)
9102 {
9103   struct objfile *objfile = dwarf2_per_objfile->objfile;
9104   struct dwarf2_section_info *section = &dwo_file->sections.info;
9105   bfd *abfd;
9106   htab_t cu_htab;
9107   const gdb_byte *info_ptr, *end_ptr;
9108   struct create_dwo_cu_data create_dwo_cu_data;
9109   struct dwo_unit *dwo_unit;
9110
9111   dwarf2_read_section (objfile, section);
9112   info_ptr = section->buffer;
9113
9114   if (info_ptr == NULL)
9115     return NULL;
9116
9117   /* We can't set abfd until now because the section may be empty or
9118      not present, in which case section->asection will be NULL.  */
9119   abfd = get_section_bfd_owner (section);
9120
9121   if (dwarf2_read_debug)
9122     {
9123       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9124                           get_section_name (section),
9125                           get_section_file_name (section));
9126     }
9127
9128   create_dwo_cu_data.dwo_file = dwo_file;
9129   dwo_unit = NULL;
9130
9131   end_ptr = info_ptr + section->size;
9132   while (info_ptr < end_ptr)
9133     {
9134       struct dwarf2_per_cu_data per_cu;
9135
9136       memset (&create_dwo_cu_data.dwo_unit, 0,
9137               sizeof (create_dwo_cu_data.dwo_unit));
9138       memset (&per_cu, 0, sizeof (per_cu));
9139       per_cu.objfile = objfile;
9140       per_cu.is_debug_types = 0;
9141       per_cu.offset.sect_off = info_ptr - section->buffer;
9142       per_cu.section = section;
9143
9144       init_cutu_and_read_dies_no_follow (&per_cu,
9145                                          &dwo_file->sections.abbrev,
9146                                          dwo_file,
9147                                          create_dwo_cu_reader,
9148                                          &create_dwo_cu_data);
9149
9150       if (create_dwo_cu_data.dwo_unit.dwo_file != NULL)
9151         {
9152           /* If we've already found one, complain.  We only support one
9153              because having more than one requires hacking the dwo_name of
9154              each to match, which is highly unlikely to happen.  */
9155           if (dwo_unit != NULL)
9156             {
9157               complaint (&symfile_complaints,
9158                          _("Multiple CUs in DWO file %s [in module %s]"),
9159                          dwo_file->dwo_name, objfile_name (objfile));
9160               break;
9161             }
9162
9163           dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9164           *dwo_unit = create_dwo_cu_data.dwo_unit;
9165         }
9166
9167       info_ptr += per_cu.length;
9168     }
9169
9170   return dwo_unit;
9171 }
9172
9173 /* DWP file .debug_{cu,tu}_index section format:
9174    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9175
9176    DWP Version 1:
9177
9178    Both index sections have the same format, and serve to map a 64-bit
9179    signature to a set of section numbers.  Each section begins with a header,
9180    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9181    indexes, and a pool of 32-bit section numbers.  The index sections will be
9182    aligned at 8-byte boundaries in the file.
9183
9184    The index section header consists of:
9185
9186     V, 32 bit version number
9187     -, 32 bits unused
9188     N, 32 bit number of compilation units or type units in the index
9189     M, 32 bit number of slots in the hash table
9190
9191    Numbers are recorded using the byte order of the application binary.
9192
9193    The hash table begins at offset 16 in the section, and consists of an array
9194    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9195    order of the application binary).  Unused slots in the hash table are 0.
9196    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9197
9198    The parallel table begins immediately after the hash table
9199    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9200    array of 32-bit indexes (using the byte order of the application binary),
9201    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9202    table contains a 32-bit index into the pool of section numbers.  For unused
9203    hash table slots, the corresponding entry in the parallel table will be 0.
9204
9205    The pool of section numbers begins immediately following the hash table
9206    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9207    section numbers consists of an array of 32-bit words (using the byte order
9208    of the application binary).  Each item in the array is indexed starting
9209    from 0.  The hash table entry provides the index of the first section
9210    number in the set.  Additional section numbers in the set follow, and the
9211    set is terminated by a 0 entry (section number 0 is not used in ELF).
9212
9213    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9214    section must be the first entry in the set, and the .debug_abbrev.dwo must
9215    be the second entry. Other members of the set may follow in any order.
9216
9217    ---
9218
9219    DWP Version 2:
9220
9221    DWP Version 2 combines all the .debug_info, etc. sections into one,
9222    and the entries in the index tables are now offsets into these sections.
9223    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9224    section.
9225
9226    Index Section Contents:
9227     Header
9228     Hash Table of Signatures   dwp_hash_table.hash_table
9229     Parallel Table of Indices  dwp_hash_table.unit_table
9230     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9231     Table of Section Sizes     dwp_hash_table.v2.sizes
9232
9233    The index section header consists of:
9234
9235     V, 32 bit version number
9236     L, 32 bit number of columns in the table of section offsets
9237     N, 32 bit number of compilation units or type units in the index
9238     M, 32 bit number of slots in the hash table
9239
9240    Numbers are recorded using the byte order of the application binary.
9241
9242    The hash table has the same format as version 1.
9243    The parallel table of indices has the same format as version 1,
9244    except that the entries are origin-1 indices into the table of sections
9245    offsets and the table of section sizes.
9246
9247    The table of offsets begins immediately following the parallel table
9248    (at offset 16 + 12 * M from the beginning of the section).  The table is
9249    a two-dimensional array of 32-bit words (using the byte order of the
9250    application binary), with L columns and N+1 rows, in row-major order.
9251    Each row in the array is indexed starting from 0.  The first row provides
9252    a key to the remaining rows: each column in this row provides an identifier
9253    for a debug section, and the offsets in the same column of subsequent rows
9254    refer to that section.  The section identifiers are:
9255
9256     DW_SECT_INFO         1  .debug_info.dwo
9257     DW_SECT_TYPES        2  .debug_types.dwo
9258     DW_SECT_ABBREV       3  .debug_abbrev.dwo
9259     DW_SECT_LINE         4  .debug_line.dwo
9260     DW_SECT_LOC          5  .debug_loc.dwo
9261     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
9262     DW_SECT_MACINFO      7  .debug_macinfo.dwo
9263     DW_SECT_MACRO        8  .debug_macro.dwo
9264
9265    The offsets provided by the CU and TU index sections are the base offsets
9266    for the contributions made by each CU or TU to the corresponding section
9267    in the package file.  Each CU and TU header contains an abbrev_offset
9268    field, used to find the abbreviations table for that CU or TU within the
9269    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
9270    be interpreted as relative to the base offset given in the index section.
9271    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
9272    should be interpreted as relative to the base offset for .debug_line.dwo,
9273    and offsets into other debug sections obtained from DWARF attributes should
9274    also be interpreted as relative to the corresponding base offset.
9275
9276    The table of sizes begins immediately following the table of offsets.
9277    Like the table of offsets, it is a two-dimensional array of 32-bit words,
9278    with L columns and N rows, in row-major order.  Each row in the array is
9279    indexed starting from 1 (row 0 is shared by the two tables).
9280
9281    ---
9282
9283    Hash table lookup is handled the same in version 1 and 2:
9284
9285    We assume that N and M will not exceed 2^32 - 1.
9286    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
9287
9288    Given a 64-bit compilation unit signature or a type signature S, an entry
9289    in the hash table is located as follows:
9290
9291    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
9292       the low-order k bits all set to 1.
9293
9294    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
9295
9296    3) If the hash table entry at index H matches the signature, use that
9297       entry.  If the hash table entry at index H is unused (all zeroes),
9298       terminate the search: the signature is not present in the table.
9299
9300    4) Let H = (H + H') modulo M. Repeat at Step 3.
9301
9302    Because M > N and H' and M are relatively prime, the search is guaranteed
9303    to stop at an unused slot or find the match.  */
9304
9305 /* Create a hash table to map DWO IDs to their CU/TU entry in
9306    .debug_{info,types}.dwo in DWP_FILE.
9307    Returns NULL if there isn't one.
9308    Note: This function processes DWP files only, not DWO files.  */
9309
9310 static struct dwp_hash_table *
9311 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
9312 {
9313   struct objfile *objfile = dwarf2_per_objfile->objfile;
9314   bfd *dbfd = dwp_file->dbfd;
9315   const gdb_byte *index_ptr, *index_end;
9316   struct dwarf2_section_info *index;
9317   uint32_t version, nr_columns, nr_units, nr_slots;
9318   struct dwp_hash_table *htab;
9319
9320   if (is_debug_types)
9321     index = &dwp_file->sections.tu_index;
9322   else
9323     index = &dwp_file->sections.cu_index;
9324
9325   if (dwarf2_section_empty_p (index))
9326     return NULL;
9327   dwarf2_read_section (objfile, index);
9328
9329   index_ptr = index->buffer;
9330   index_end = index_ptr + index->size;
9331
9332   version = read_4_bytes (dbfd, index_ptr);
9333   index_ptr += 4;
9334   if (version == 2)
9335     nr_columns = read_4_bytes (dbfd, index_ptr);
9336   else
9337     nr_columns = 0;
9338   index_ptr += 4;
9339   nr_units = read_4_bytes (dbfd, index_ptr);
9340   index_ptr += 4;
9341   nr_slots = read_4_bytes (dbfd, index_ptr);
9342   index_ptr += 4;
9343
9344   if (version != 1 && version != 2)
9345     {
9346       error (_("Dwarf Error: unsupported DWP file version (%s)"
9347                " [in module %s]"),
9348              pulongest (version), dwp_file->name);
9349     }
9350   if (nr_slots != (nr_slots & -nr_slots))
9351     {
9352       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
9353                " is not power of 2 [in module %s]"),
9354              pulongest (nr_slots), dwp_file->name);
9355     }
9356
9357   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
9358   htab->version = version;
9359   htab->nr_columns = nr_columns;
9360   htab->nr_units = nr_units;
9361   htab->nr_slots = nr_slots;
9362   htab->hash_table = index_ptr;
9363   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
9364
9365   /* Exit early if the table is empty.  */
9366   if (nr_slots == 0 || nr_units == 0
9367       || (version == 2 && nr_columns == 0))
9368     {
9369       /* All must be zero.  */
9370       if (nr_slots != 0 || nr_units != 0
9371           || (version == 2 && nr_columns != 0))
9372         {
9373           complaint (&symfile_complaints,
9374                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
9375                        " all zero [in modules %s]"),
9376                      dwp_file->name);
9377         }
9378       return htab;
9379     }
9380
9381   if (version == 1)
9382     {
9383       htab->section_pool.v1.indices =
9384         htab->unit_table + sizeof (uint32_t) * nr_slots;
9385       /* It's harder to decide whether the section is too small in v1.
9386          V1 is deprecated anyway so we punt.  */
9387     }
9388   else
9389     {
9390       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
9391       int *ids = htab->section_pool.v2.section_ids;
9392       /* Reverse map for error checking.  */
9393       int ids_seen[DW_SECT_MAX + 1];
9394       int i;
9395
9396       if (nr_columns < 2)
9397         {
9398           error (_("Dwarf Error: bad DWP hash table, too few columns"
9399                    " in section table [in module %s]"),
9400                  dwp_file->name);
9401         }
9402       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
9403         {
9404           error (_("Dwarf Error: bad DWP hash table, too many columns"
9405                    " in section table [in module %s]"),
9406                  dwp_file->name);
9407         }
9408       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9409       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
9410       for (i = 0; i < nr_columns; ++i)
9411         {
9412           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
9413
9414           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
9415             {
9416               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
9417                        " in section table [in module %s]"),
9418                      id, dwp_file->name);
9419             }
9420           if (ids_seen[id] != -1)
9421             {
9422               error (_("Dwarf Error: bad DWP hash table, duplicate section"
9423                        " id %d in section table [in module %s]"),
9424                      id, dwp_file->name);
9425             }
9426           ids_seen[id] = i;
9427           ids[i] = id;
9428         }
9429       /* Must have exactly one info or types section.  */
9430       if (((ids_seen[DW_SECT_INFO] != -1)
9431            + (ids_seen[DW_SECT_TYPES] != -1))
9432           != 1)
9433         {
9434           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
9435                    " DWO info/types section [in module %s]"),
9436                  dwp_file->name);
9437         }
9438       /* Must have an abbrev section.  */
9439       if (ids_seen[DW_SECT_ABBREV] == -1)
9440         {
9441           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
9442                    " section [in module %s]"),
9443                  dwp_file->name);
9444         }
9445       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
9446       htab->section_pool.v2.sizes =
9447         htab->section_pool.v2.offsets + (sizeof (uint32_t)
9448                                          * nr_units * nr_columns);
9449       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
9450                                           * nr_units * nr_columns))
9451           > index_end)
9452         {
9453           error (_("Dwarf Error: DWP index section is corrupt (too small)"
9454                    " [in module %s]"),
9455                  dwp_file->name);
9456         }
9457     }
9458
9459   return htab;
9460 }
9461
9462 /* Update SECTIONS with the data from SECTP.
9463
9464    This function is like the other "locate" section routines that are
9465    passed to bfd_map_over_sections, but in this context the sections to
9466    read comes from the DWP V1 hash table, not the full ELF section table.
9467
9468    The result is non-zero for success, or zero if an error was found.  */
9469
9470 static int
9471 locate_v1_virtual_dwo_sections (asection *sectp,
9472                                 struct virtual_v1_dwo_sections *sections)
9473 {
9474   const struct dwop_section_names *names = &dwop_section_names;
9475
9476   if (section_is_p (sectp->name, &names->abbrev_dwo))
9477     {
9478       /* There can be only one.  */
9479       if (sections->abbrev.s.asection != NULL)
9480         return 0;
9481       sections->abbrev.s.asection = sectp;
9482       sections->abbrev.size = bfd_get_section_size (sectp);
9483     }
9484   else if (section_is_p (sectp->name, &names->info_dwo)
9485            || section_is_p (sectp->name, &names->types_dwo))
9486     {
9487       /* There can be only one.  */
9488       if (sections->info_or_types.s.asection != NULL)
9489         return 0;
9490       sections->info_or_types.s.asection = sectp;
9491       sections->info_or_types.size = bfd_get_section_size (sectp);
9492     }
9493   else if (section_is_p (sectp->name, &names->line_dwo))
9494     {
9495       /* There can be only one.  */
9496       if (sections->line.s.asection != NULL)
9497         return 0;
9498       sections->line.s.asection = sectp;
9499       sections->line.size = bfd_get_section_size (sectp);
9500     }
9501   else if (section_is_p (sectp->name, &names->loc_dwo))
9502     {
9503       /* There can be only one.  */
9504       if (sections->loc.s.asection != NULL)
9505         return 0;
9506       sections->loc.s.asection = sectp;
9507       sections->loc.size = bfd_get_section_size (sectp);
9508     }
9509   else if (section_is_p (sectp->name, &names->macinfo_dwo))
9510     {
9511       /* There can be only one.  */
9512       if (sections->macinfo.s.asection != NULL)
9513         return 0;
9514       sections->macinfo.s.asection = sectp;
9515       sections->macinfo.size = bfd_get_section_size (sectp);
9516     }
9517   else if (section_is_p (sectp->name, &names->macro_dwo))
9518     {
9519       /* There can be only one.  */
9520       if (sections->macro.s.asection != NULL)
9521         return 0;
9522       sections->macro.s.asection = sectp;
9523       sections->macro.size = bfd_get_section_size (sectp);
9524     }
9525   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
9526     {
9527       /* There can be only one.  */
9528       if (sections->str_offsets.s.asection != NULL)
9529         return 0;
9530       sections->str_offsets.s.asection = sectp;
9531       sections->str_offsets.size = bfd_get_section_size (sectp);
9532     }
9533   else
9534     {
9535       /* No other kind of section is valid.  */
9536       return 0;
9537     }
9538
9539   return 1;
9540 }
9541
9542 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9543    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9544    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9545    This is for DWP version 1 files.  */
9546
9547 static struct dwo_unit *
9548 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
9549                            uint32_t unit_index,
9550                            const char *comp_dir,
9551                            ULONGEST signature, int is_debug_types)
9552 {
9553   struct objfile *objfile = dwarf2_per_objfile->objfile;
9554   const struct dwp_hash_table *dwp_htab =
9555     is_debug_types ? dwp_file->tus : dwp_file->cus;
9556   bfd *dbfd = dwp_file->dbfd;
9557   const char *kind = is_debug_types ? "TU" : "CU";
9558   struct dwo_file *dwo_file;
9559   struct dwo_unit *dwo_unit;
9560   struct virtual_v1_dwo_sections sections;
9561   void **dwo_file_slot;
9562   char *virtual_dwo_name;
9563   struct dwarf2_section_info *cutu;
9564   struct cleanup *cleanups;
9565   int i;
9566
9567   gdb_assert (dwp_file->version == 1);
9568
9569   if (dwarf2_read_debug)
9570     {
9571       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
9572                           kind,
9573                           pulongest (unit_index), hex_string (signature),
9574                           dwp_file->name);
9575     }
9576
9577   /* Fetch the sections of this DWO unit.
9578      Put a limit on the number of sections we look for so that bad data
9579      doesn't cause us to loop forever.  */
9580
9581 #define MAX_NR_V1_DWO_SECTIONS \
9582   (1 /* .debug_info or .debug_types */ \
9583    + 1 /* .debug_abbrev */ \
9584    + 1 /* .debug_line */ \
9585    + 1 /* .debug_loc */ \
9586    + 1 /* .debug_str_offsets */ \
9587    + 1 /* .debug_macro or .debug_macinfo */ \
9588    + 1 /* trailing zero */)
9589
9590   memset (&sections, 0, sizeof (sections));
9591   cleanups = make_cleanup (null_cleanup, 0);
9592
9593   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
9594     {
9595       asection *sectp;
9596       uint32_t section_nr =
9597         read_4_bytes (dbfd,
9598                       dwp_htab->section_pool.v1.indices
9599                       + (unit_index + i) * sizeof (uint32_t));
9600
9601       if (section_nr == 0)
9602         break;
9603       if (section_nr >= dwp_file->num_sections)
9604         {
9605           error (_("Dwarf Error: bad DWP hash table, section number too large"
9606                    " [in module %s]"),
9607                  dwp_file->name);
9608         }
9609
9610       sectp = dwp_file->elf_sections[section_nr];
9611       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
9612         {
9613           error (_("Dwarf Error: bad DWP hash table, invalid section found"
9614                    " [in module %s]"),
9615                  dwp_file->name);
9616         }
9617     }
9618
9619   if (i < 2
9620       || dwarf2_section_empty_p (&sections.info_or_types)
9621       || dwarf2_section_empty_p (&sections.abbrev))
9622     {
9623       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
9624                " [in module %s]"),
9625              dwp_file->name);
9626     }
9627   if (i == MAX_NR_V1_DWO_SECTIONS)
9628     {
9629       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
9630                " [in module %s]"),
9631              dwp_file->name);
9632     }
9633
9634   /* It's easier for the rest of the code if we fake a struct dwo_file and
9635      have dwo_unit "live" in that.  At least for now.
9636
9637      The DWP file can be made up of a random collection of CUs and TUs.
9638      However, for each CU + set of TUs that came from the same original DWO
9639      file, we can combine them back into a virtual DWO file to save space
9640      (fewer struct dwo_file objects to allocate).  Remember that for really
9641      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9642
9643   virtual_dwo_name =
9644     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
9645                 get_section_id (&sections.abbrev),
9646                 get_section_id (&sections.line),
9647                 get_section_id (&sections.loc),
9648                 get_section_id (&sections.str_offsets));
9649   make_cleanup (xfree, virtual_dwo_name);
9650   /* Can we use an existing virtual DWO file?  */
9651   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9652   /* Create one if necessary.  */
9653   if (*dwo_file_slot == NULL)
9654     {
9655       if (dwarf2_read_debug)
9656         {
9657           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9658                               virtual_dwo_name);
9659         }
9660       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9661       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9662                                           virtual_dwo_name,
9663                                           strlen (virtual_dwo_name));
9664       dwo_file->comp_dir = comp_dir;
9665       dwo_file->sections.abbrev = sections.abbrev;
9666       dwo_file->sections.line = sections.line;
9667       dwo_file->sections.loc = sections.loc;
9668       dwo_file->sections.macinfo = sections.macinfo;
9669       dwo_file->sections.macro = sections.macro;
9670       dwo_file->sections.str_offsets = sections.str_offsets;
9671       /* The "str" section is global to the entire DWP file.  */
9672       dwo_file->sections.str = dwp_file->sections.str;
9673       /* The info or types section is assigned below to dwo_unit,
9674          there's no need to record it in dwo_file.
9675          Also, we can't simply record type sections in dwo_file because
9676          we record a pointer into the vector in dwo_unit.  As we collect more
9677          types we'll grow the vector and eventually have to reallocate space
9678          for it, invalidating all copies of pointers into the previous
9679          contents.  */
9680       *dwo_file_slot = dwo_file;
9681     }
9682   else
9683     {
9684       if (dwarf2_read_debug)
9685         {
9686           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9687                               virtual_dwo_name);
9688         }
9689       dwo_file = *dwo_file_slot;
9690     }
9691   do_cleanups (cleanups);
9692
9693   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9694   dwo_unit->dwo_file = dwo_file;
9695   dwo_unit->signature = signature;
9696   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9697                                      sizeof (struct dwarf2_section_info));
9698   *dwo_unit->section = sections.info_or_types;
9699   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9700
9701   return dwo_unit;
9702 }
9703
9704 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
9705    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
9706    piece within that section used by a TU/CU, return a virtual section
9707    of just that piece.  */
9708
9709 static struct dwarf2_section_info
9710 create_dwp_v2_section (struct dwarf2_section_info *section,
9711                        bfd_size_type offset, bfd_size_type size)
9712 {
9713   struct dwarf2_section_info result;
9714   asection *sectp;
9715
9716   gdb_assert (section != NULL);
9717   gdb_assert (!section->is_virtual);
9718
9719   memset (&result, 0, sizeof (result));
9720   result.s.containing_section = section;
9721   result.is_virtual = 1;
9722
9723   if (size == 0)
9724     return result;
9725
9726   sectp = get_section_bfd_section (section);
9727
9728   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
9729      bounds of the real section.  This is a pretty-rare event, so just
9730      flag an error (easier) instead of a warning and trying to cope.  */
9731   if (sectp == NULL
9732       || offset + size > bfd_get_section_size (sectp))
9733     {
9734       bfd *abfd = sectp->owner;
9735
9736       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
9737                " in section %s [in module %s]"),
9738              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
9739              objfile_name (dwarf2_per_objfile->objfile));
9740     }
9741
9742   result.virtual_offset = offset;
9743   result.size = size;
9744   return result;
9745 }
9746
9747 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
9748    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
9749    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
9750    This is for DWP version 2 files.  */
9751
9752 static struct dwo_unit *
9753 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
9754                            uint32_t unit_index,
9755                            const char *comp_dir,
9756                            ULONGEST signature, int is_debug_types)
9757 {
9758   struct objfile *objfile = dwarf2_per_objfile->objfile;
9759   const struct dwp_hash_table *dwp_htab =
9760     is_debug_types ? dwp_file->tus : dwp_file->cus;
9761   bfd *dbfd = dwp_file->dbfd;
9762   const char *kind = is_debug_types ? "TU" : "CU";
9763   struct dwo_file *dwo_file;
9764   struct dwo_unit *dwo_unit;
9765   struct virtual_v2_dwo_sections sections;
9766   void **dwo_file_slot;
9767   char *virtual_dwo_name;
9768   struct dwarf2_section_info *cutu;
9769   struct cleanup *cleanups;
9770   int i;
9771
9772   gdb_assert (dwp_file->version == 2);
9773
9774   if (dwarf2_read_debug)
9775     {
9776       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
9777                           kind,
9778                           pulongest (unit_index), hex_string (signature),
9779                           dwp_file->name);
9780     }
9781
9782   /* Fetch the section offsets of this DWO unit.  */
9783
9784   memset (&sections, 0, sizeof (sections));
9785   cleanups = make_cleanup (null_cleanup, 0);
9786
9787   for (i = 0; i < dwp_htab->nr_columns; ++i)
9788     {
9789       uint32_t offset = read_4_bytes (dbfd,
9790                                       dwp_htab->section_pool.v2.offsets
9791                                       + (((unit_index - 1) * dwp_htab->nr_columns
9792                                           + i)
9793                                          * sizeof (uint32_t)));
9794       uint32_t size = read_4_bytes (dbfd,
9795                                     dwp_htab->section_pool.v2.sizes
9796                                     + (((unit_index - 1) * dwp_htab->nr_columns
9797                                         + i)
9798                                        * sizeof (uint32_t)));
9799
9800       switch (dwp_htab->section_pool.v2.section_ids[i])
9801         {
9802         case DW_SECT_INFO:
9803         case DW_SECT_TYPES:
9804           sections.info_or_types_offset = offset;
9805           sections.info_or_types_size = size;
9806           break;
9807         case DW_SECT_ABBREV:
9808           sections.abbrev_offset = offset;
9809           sections.abbrev_size = size;
9810           break;
9811         case DW_SECT_LINE:
9812           sections.line_offset = offset;
9813           sections.line_size = size;
9814           break;
9815         case DW_SECT_LOC:
9816           sections.loc_offset = offset;
9817           sections.loc_size = size;
9818           break;
9819         case DW_SECT_STR_OFFSETS:
9820           sections.str_offsets_offset = offset;
9821           sections.str_offsets_size = size;
9822           break;
9823         case DW_SECT_MACINFO:
9824           sections.macinfo_offset = offset;
9825           sections.macinfo_size = size;
9826           break;
9827         case DW_SECT_MACRO:
9828           sections.macro_offset = offset;
9829           sections.macro_size = size;
9830           break;
9831         }
9832     }
9833
9834   /* It's easier for the rest of the code if we fake a struct dwo_file and
9835      have dwo_unit "live" in that.  At least for now.
9836
9837      The DWP file can be made up of a random collection of CUs and TUs.
9838      However, for each CU + set of TUs that came from the same original DWO
9839      file, we can combine them back into a virtual DWO file to save space
9840      (fewer struct dwo_file objects to allocate).  Remember that for really
9841      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
9842
9843   virtual_dwo_name =
9844     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
9845                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
9846                 (long) (sections.line_size ? sections.line_offset : 0),
9847                 (long) (sections.loc_size ? sections.loc_offset : 0),
9848                 (long) (sections.str_offsets_size
9849                         ? sections.str_offsets_offset : 0));
9850   make_cleanup (xfree, virtual_dwo_name);
9851   /* Can we use an existing virtual DWO file?  */
9852   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
9853   /* Create one if necessary.  */
9854   if (*dwo_file_slot == NULL)
9855     {
9856       if (dwarf2_read_debug)
9857         {
9858           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
9859                               virtual_dwo_name);
9860         }
9861       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
9862       dwo_file->dwo_name = obstack_copy0 (&objfile->objfile_obstack,
9863                                           virtual_dwo_name,
9864                                           strlen (virtual_dwo_name));
9865       dwo_file->comp_dir = comp_dir;
9866       dwo_file->sections.abbrev =
9867         create_dwp_v2_section (&dwp_file->sections.abbrev,
9868                                sections.abbrev_offset, sections.abbrev_size);
9869       dwo_file->sections.line =
9870         create_dwp_v2_section (&dwp_file->sections.line,
9871                                sections.line_offset, sections.line_size);
9872       dwo_file->sections.loc =
9873         create_dwp_v2_section (&dwp_file->sections.loc,
9874                                sections.loc_offset, sections.loc_size);
9875       dwo_file->sections.macinfo =
9876         create_dwp_v2_section (&dwp_file->sections.macinfo,
9877                                sections.macinfo_offset, sections.macinfo_size);
9878       dwo_file->sections.macro =
9879         create_dwp_v2_section (&dwp_file->sections.macro,
9880                                sections.macro_offset, sections.macro_size);
9881       dwo_file->sections.str_offsets =
9882         create_dwp_v2_section (&dwp_file->sections.str_offsets,
9883                                sections.str_offsets_offset,
9884                                sections.str_offsets_size);
9885       /* The "str" section is global to the entire DWP file.  */
9886       dwo_file->sections.str = dwp_file->sections.str;
9887       /* The info or types section is assigned below to dwo_unit,
9888          there's no need to record it in dwo_file.
9889          Also, we can't simply record type sections in dwo_file because
9890          we record a pointer into the vector in dwo_unit.  As we collect more
9891          types we'll grow the vector and eventually have to reallocate space
9892          for it, invalidating all copies of pointers into the previous
9893          contents.  */
9894       *dwo_file_slot = dwo_file;
9895     }
9896   else
9897     {
9898       if (dwarf2_read_debug)
9899         {
9900           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
9901                               virtual_dwo_name);
9902         }
9903       dwo_file = *dwo_file_slot;
9904     }
9905   do_cleanups (cleanups);
9906
9907   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9908   dwo_unit->dwo_file = dwo_file;
9909   dwo_unit->signature = signature;
9910   dwo_unit->section = obstack_alloc (&objfile->objfile_obstack,
9911                                      sizeof (struct dwarf2_section_info));
9912   *dwo_unit->section = create_dwp_v2_section (is_debug_types
9913                                               ? &dwp_file->sections.types
9914                                               : &dwp_file->sections.info,
9915                                               sections.info_or_types_offset,
9916                                               sections.info_or_types_size);
9917   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
9918
9919   return dwo_unit;
9920 }
9921
9922 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
9923    Returns NULL if the signature isn't found.  */
9924
9925 static struct dwo_unit *
9926 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
9927                         ULONGEST signature, int is_debug_types)
9928 {
9929   const struct dwp_hash_table *dwp_htab =
9930     is_debug_types ? dwp_file->tus : dwp_file->cus;
9931   bfd *dbfd = dwp_file->dbfd;
9932   uint32_t mask = dwp_htab->nr_slots - 1;
9933   uint32_t hash = signature & mask;
9934   uint32_t hash2 = ((signature >> 32) & mask) | 1;
9935   unsigned int i;
9936   void **slot;
9937   struct dwo_unit find_dwo_cu, *dwo_cu;
9938
9939   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
9940   find_dwo_cu.signature = signature;
9941   slot = htab_find_slot (is_debug_types
9942                          ? dwp_file->loaded_tus
9943                          : dwp_file->loaded_cus,
9944                          &find_dwo_cu, INSERT);
9945
9946   if (*slot != NULL)
9947     return *slot;
9948
9949   /* Use a for loop so that we don't loop forever on bad debug info.  */
9950   for (i = 0; i < dwp_htab->nr_slots; ++i)
9951     {
9952       ULONGEST signature_in_table;
9953
9954       signature_in_table =
9955         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
9956       if (signature_in_table == signature)
9957         {
9958           uint32_t unit_index =
9959             read_4_bytes (dbfd,
9960                           dwp_htab->unit_table + hash * sizeof (uint32_t));
9961
9962           if (dwp_file->version == 1)
9963             {
9964               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
9965                                                  comp_dir, signature,
9966                                                  is_debug_types);
9967             }
9968           else
9969             {
9970               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
9971                                                  comp_dir, signature,
9972                                                  is_debug_types);
9973             }
9974           return *slot;
9975         }
9976       if (signature_in_table == 0)
9977         return NULL;
9978       hash = (hash + hash2) & mask;
9979     }
9980
9981   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
9982            " [in module %s]"),
9983          dwp_file->name);
9984 }
9985
9986 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
9987    Open the file specified by FILE_NAME and hand it off to BFD for
9988    preliminary analysis.  Return a newly initialized bfd *, which
9989    includes a canonicalized copy of FILE_NAME.
9990    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
9991    SEARCH_CWD is true if the current directory is to be searched.
9992    It will be searched before debug-file-directory.
9993    If unable to find/open the file, return NULL.
9994    NOTE: This function is derived from symfile_bfd_open.  */
9995
9996 static bfd *
9997 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
9998 {
9999   bfd *sym_bfd;
10000   int desc, flags;
10001   char *absolute_name;
10002   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10003      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10004      to debug_file_directory.  */
10005   char *search_path;
10006   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10007
10008   if (search_cwd)
10009     {
10010       if (*debug_file_directory != '\0')
10011         search_path = concat (".", dirname_separator_string,
10012                               debug_file_directory, NULL);
10013       else
10014         search_path = xstrdup (".");
10015     }
10016   else
10017     search_path = xstrdup (debug_file_directory);
10018
10019   flags = OPF_RETURN_REALPATH;
10020   if (is_dwp)
10021     flags |= OPF_SEARCH_IN_PATH;
10022   desc = openp (search_path, flags, file_name,
10023                 O_RDONLY | O_BINARY, &absolute_name);
10024   xfree (search_path);
10025   if (desc < 0)
10026     return NULL;
10027
10028   sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
10029   xfree (absolute_name);
10030   if (sym_bfd == NULL)
10031     return NULL;
10032   bfd_set_cacheable (sym_bfd, 1);
10033
10034   if (!bfd_check_format (sym_bfd, bfd_object))
10035     {
10036       gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
10037       return NULL;
10038     }
10039
10040   return sym_bfd;
10041 }
10042
10043 /* Try to open DWO file FILE_NAME.
10044    COMP_DIR is the DW_AT_comp_dir attribute.
10045    The result is the bfd handle of the file.
10046    If there is a problem finding or opening the file, return NULL.
10047    Upon success, the canonicalized path of the file is stored in the bfd,
10048    same as symfile_bfd_open.  */
10049
10050 static bfd *
10051 open_dwo_file (const char *file_name, const char *comp_dir)
10052 {
10053   bfd *abfd;
10054
10055   if (IS_ABSOLUTE_PATH (file_name))
10056     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10057
10058   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10059
10060   if (comp_dir != NULL)
10061     {
10062       char *path_to_try = concat (comp_dir, SLASH_STRING, file_name, NULL);
10063
10064       /* NOTE: If comp_dir is a relative path, this will also try the
10065          search path, which seems useful.  */
10066       abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
10067       xfree (path_to_try);
10068       if (abfd != NULL)
10069         return abfd;
10070     }
10071
10072   /* That didn't work, try debug-file-directory, which, despite its name,
10073      is a list of paths.  */
10074
10075   if (*debug_file_directory == '\0')
10076     return NULL;
10077
10078   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10079 }
10080
10081 /* This function is mapped across the sections and remembers the offset and
10082    size of each of the DWO debugging sections we are interested in.  */
10083
10084 static void
10085 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10086 {
10087   struct dwo_sections *dwo_sections = dwo_sections_ptr;
10088   const struct dwop_section_names *names = &dwop_section_names;
10089
10090   if (section_is_p (sectp->name, &names->abbrev_dwo))
10091     {
10092       dwo_sections->abbrev.s.asection = sectp;
10093       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10094     }
10095   else if (section_is_p (sectp->name, &names->info_dwo))
10096     {
10097       dwo_sections->info.s.asection = sectp;
10098       dwo_sections->info.size = bfd_get_section_size (sectp);
10099     }
10100   else if (section_is_p (sectp->name, &names->line_dwo))
10101     {
10102       dwo_sections->line.s.asection = sectp;
10103       dwo_sections->line.size = bfd_get_section_size (sectp);
10104     }
10105   else if (section_is_p (sectp->name, &names->loc_dwo))
10106     {
10107       dwo_sections->loc.s.asection = sectp;
10108       dwo_sections->loc.size = bfd_get_section_size (sectp);
10109     }
10110   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10111     {
10112       dwo_sections->macinfo.s.asection = sectp;
10113       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10114     }
10115   else if (section_is_p (sectp->name, &names->macro_dwo))
10116     {
10117       dwo_sections->macro.s.asection = sectp;
10118       dwo_sections->macro.size = bfd_get_section_size (sectp);
10119     }
10120   else if (section_is_p (sectp->name, &names->str_dwo))
10121     {
10122       dwo_sections->str.s.asection = sectp;
10123       dwo_sections->str.size = bfd_get_section_size (sectp);
10124     }
10125   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10126     {
10127       dwo_sections->str_offsets.s.asection = sectp;
10128       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10129     }
10130   else if (section_is_p (sectp->name, &names->types_dwo))
10131     {
10132       struct dwarf2_section_info type_section;
10133
10134       memset (&type_section, 0, sizeof (type_section));
10135       type_section.s.asection = sectp;
10136       type_section.size = bfd_get_section_size (sectp);
10137       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10138                      &type_section);
10139     }
10140 }
10141
10142 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10143    by PER_CU.  This is for the non-DWP case.
10144    The result is NULL if DWO_NAME can't be found.  */
10145
10146 static struct dwo_file *
10147 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10148                         const char *dwo_name, const char *comp_dir)
10149 {
10150   struct objfile *objfile = dwarf2_per_objfile->objfile;
10151   struct dwo_file *dwo_file;
10152   bfd *dbfd;
10153   struct cleanup *cleanups;
10154
10155   dbfd = open_dwo_file (dwo_name, comp_dir);
10156   if (dbfd == NULL)
10157     {
10158       if (dwarf2_read_debug)
10159         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10160       return NULL;
10161     }
10162   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10163   dwo_file->dwo_name = dwo_name;
10164   dwo_file->comp_dir = comp_dir;
10165   dwo_file->dbfd = dbfd;
10166
10167   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10168
10169   bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
10170
10171   dwo_file->cu = create_dwo_cu (dwo_file);
10172
10173   dwo_file->tus = create_debug_types_hash_table (dwo_file,
10174                                                  dwo_file->sections.types);
10175
10176   discard_cleanups (cleanups);
10177
10178   if (dwarf2_read_debug)
10179     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10180
10181   return dwo_file;
10182 }
10183
10184 /* This function is mapped across the sections and remembers the offset and
10185    size of each of the DWP debugging sections common to version 1 and 2 that
10186    we are interested in.  */
10187
10188 static void
10189 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10190                                    void *dwp_file_ptr)
10191 {
10192   struct dwp_file *dwp_file = dwp_file_ptr;
10193   const struct dwop_section_names *names = &dwop_section_names;
10194   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10195
10196   /* Record the ELF section number for later lookup: this is what the
10197      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10198   gdb_assert (elf_section_nr < dwp_file->num_sections);
10199   dwp_file->elf_sections[elf_section_nr] = sectp;
10200
10201   /* Look for specific sections that we need.  */
10202   if (section_is_p (sectp->name, &names->str_dwo))
10203     {
10204       dwp_file->sections.str.s.asection = sectp;
10205       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10206     }
10207   else if (section_is_p (sectp->name, &names->cu_index))
10208     {
10209       dwp_file->sections.cu_index.s.asection = sectp;
10210       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10211     }
10212   else if (section_is_p (sectp->name, &names->tu_index))
10213     {
10214       dwp_file->sections.tu_index.s.asection = sectp;
10215       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10216     }
10217 }
10218
10219 /* This function is mapped across the sections and remembers the offset and
10220    size of each of the DWP version 2 debugging sections that we are interested
10221    in.  This is split into a separate function because we don't know if we
10222    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10223
10224 static void
10225 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10226 {
10227   struct dwp_file *dwp_file = dwp_file_ptr;
10228   const struct dwop_section_names *names = &dwop_section_names;
10229   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10230
10231   /* Record the ELF section number for later lookup: this is what the
10232      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10233   gdb_assert (elf_section_nr < dwp_file->num_sections);
10234   dwp_file->elf_sections[elf_section_nr] = sectp;
10235
10236   /* Look for specific sections that we need.  */
10237   if (section_is_p (sectp->name, &names->abbrev_dwo))
10238     {
10239       dwp_file->sections.abbrev.s.asection = sectp;
10240       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10241     }
10242   else if (section_is_p (sectp->name, &names->info_dwo))
10243     {
10244       dwp_file->sections.info.s.asection = sectp;
10245       dwp_file->sections.info.size = bfd_get_section_size (sectp);
10246     }
10247   else if (section_is_p (sectp->name, &names->line_dwo))
10248     {
10249       dwp_file->sections.line.s.asection = sectp;
10250       dwp_file->sections.line.size = bfd_get_section_size (sectp);
10251     }
10252   else if (section_is_p (sectp->name, &names->loc_dwo))
10253     {
10254       dwp_file->sections.loc.s.asection = sectp;
10255       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
10256     }
10257   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10258     {
10259       dwp_file->sections.macinfo.s.asection = sectp;
10260       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
10261     }
10262   else if (section_is_p (sectp->name, &names->macro_dwo))
10263     {
10264       dwp_file->sections.macro.s.asection = sectp;
10265       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
10266     }
10267   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10268     {
10269       dwp_file->sections.str_offsets.s.asection = sectp;
10270       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
10271     }
10272   else if (section_is_p (sectp->name, &names->types_dwo))
10273     {
10274       dwp_file->sections.types.s.asection = sectp;
10275       dwp_file->sections.types.size = bfd_get_section_size (sectp);
10276     }
10277 }
10278
10279 /* Hash function for dwp_file loaded CUs/TUs.  */
10280
10281 static hashval_t
10282 hash_dwp_loaded_cutus (const void *item)
10283 {
10284   const struct dwo_unit *dwo_unit = item;
10285
10286   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
10287   return dwo_unit->signature;
10288 }
10289
10290 /* Equality function for dwp_file loaded CUs/TUs.  */
10291
10292 static int
10293 eq_dwp_loaded_cutus (const void *a, const void *b)
10294 {
10295   const struct dwo_unit *dua = a;
10296   const struct dwo_unit *dub = b;
10297
10298   return dua->signature == dub->signature;
10299 }
10300
10301 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
10302
10303 static htab_t
10304 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
10305 {
10306   return htab_create_alloc_ex (3,
10307                                hash_dwp_loaded_cutus,
10308                                eq_dwp_loaded_cutus,
10309                                NULL,
10310                                &objfile->objfile_obstack,
10311                                hashtab_obstack_allocate,
10312                                dummy_obstack_deallocate);
10313 }
10314
10315 /* Try to open DWP file FILE_NAME.
10316    The result is the bfd handle of the file.
10317    If there is a problem finding or opening the file, return NULL.
10318    Upon success, the canonicalized path of the file is stored in the bfd,
10319    same as symfile_bfd_open.  */
10320
10321 static bfd *
10322 open_dwp_file (const char *file_name)
10323 {
10324   bfd *abfd;
10325
10326   abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
10327   if (abfd != NULL)
10328     return abfd;
10329
10330   /* Work around upstream bug 15652.
10331      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
10332      [Whether that's a "bug" is debatable, but it is getting in our way.]
10333      We have no real idea where the dwp file is, because gdb's realpath-ing
10334      of the executable's path may have discarded the needed info.
10335      [IWBN if the dwp file name was recorded in the executable, akin to
10336      .gnu_debuglink, but that doesn't exist yet.]
10337      Strip the directory from FILE_NAME and search again.  */
10338   if (*debug_file_directory != '\0')
10339     {
10340       /* Don't implicitly search the current directory here.
10341          If the user wants to search "." to handle this case,
10342          it must be added to debug-file-directory.  */
10343       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
10344                                  0 /*search_cwd*/);
10345     }
10346
10347   return NULL;
10348 }
10349
10350 /* Initialize the use of the DWP file for the current objfile.
10351    By convention the name of the DWP file is ${objfile}.dwp.
10352    The result is NULL if it can't be found.  */
10353
10354 static struct dwp_file *
10355 open_and_init_dwp_file (void)
10356 {
10357   struct objfile *objfile = dwarf2_per_objfile->objfile;
10358   struct dwp_file *dwp_file;
10359   char *dwp_name;
10360   bfd *dbfd;
10361   struct cleanup *cleanups;
10362
10363   /* Try to find first .dwp for the binary file before any symbolic links
10364      resolving.  */
10365   dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
10366   cleanups = make_cleanup (xfree, dwp_name);
10367
10368   dbfd = open_dwp_file (dwp_name);
10369   if (dbfd == NULL
10370       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
10371     {
10372       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
10373       dwp_name = xstrprintf ("%s.dwp", objfile_name (objfile));
10374       make_cleanup (xfree, dwp_name);
10375       dbfd = open_dwp_file (dwp_name);
10376     }
10377
10378   if (dbfd == NULL)
10379     {
10380       if (dwarf2_read_debug)
10381         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name);
10382       do_cleanups (cleanups);
10383       return NULL;
10384     }
10385   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
10386   dwp_file->name = bfd_get_filename (dbfd);
10387   dwp_file->dbfd = dbfd;
10388   do_cleanups (cleanups);
10389
10390   /* +1: section 0 is unused */
10391   dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
10392   dwp_file->elf_sections =
10393     OBSTACK_CALLOC (&objfile->objfile_obstack,
10394                     dwp_file->num_sections, asection *);
10395
10396   bfd_map_over_sections (dbfd, dwarf2_locate_common_dwp_sections, dwp_file);
10397
10398   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
10399
10400   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
10401
10402   /* The DWP file version is stored in the hash table.  Oh well.  */
10403   if (dwp_file->cus->version != dwp_file->tus->version)
10404     {
10405       /* Technically speaking, we should try to limp along, but this is
10406          pretty bizarre.  */
10407       error (_("Dwarf Error: DWP file CU version %d doesn't match"
10408                " TU version %d [in DWP file %s]"),
10409              dwp_file->cus->version, dwp_file->tus->version, dwp_name);
10410     }
10411   dwp_file->version = dwp_file->cus->version;
10412
10413   if (dwp_file->version == 2)
10414     bfd_map_over_sections (dbfd, dwarf2_locate_v2_dwp_sections, dwp_file);
10415
10416   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
10417   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
10418
10419   if (dwarf2_read_debug)
10420     {
10421       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
10422       fprintf_unfiltered (gdb_stdlog,
10423                           "    %s CUs, %s TUs\n",
10424                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
10425                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
10426     }
10427
10428   return dwp_file;
10429 }
10430
10431 /* Wrapper around open_and_init_dwp_file, only open it once.  */
10432
10433 static struct dwp_file *
10434 get_dwp_file (void)
10435 {
10436   if (! dwarf2_per_objfile->dwp_checked)
10437     {
10438       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
10439       dwarf2_per_objfile->dwp_checked = 1;
10440     }
10441   return dwarf2_per_objfile->dwp_file;
10442 }
10443
10444 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
10445    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
10446    or in the DWP file for the objfile, referenced by THIS_UNIT.
10447    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
10448    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
10449
10450    This is called, for example, when wanting to read a variable with a
10451    complex location.  Therefore we don't want to do file i/o for every call.
10452    Therefore we don't want to look for a DWO file on every call.
10453    Therefore we first see if we've already seen SIGNATURE in a DWP file,
10454    then we check if we've already seen DWO_NAME, and only THEN do we check
10455    for a DWO file.
10456
10457    The result is a pointer to the dwo_unit object or NULL if we didn't find it
10458    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
10459
10460 static struct dwo_unit *
10461 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
10462                  const char *dwo_name, const char *comp_dir,
10463                  ULONGEST signature, int is_debug_types)
10464 {
10465   struct objfile *objfile = dwarf2_per_objfile->objfile;
10466   const char *kind = is_debug_types ? "TU" : "CU";
10467   void **dwo_file_slot;
10468   struct dwo_file *dwo_file;
10469   struct dwp_file *dwp_file;
10470
10471   /* First see if there's a DWP file.
10472      If we have a DWP file but didn't find the DWO inside it, don't
10473      look for the original DWO file.  It makes gdb behave differently
10474      depending on whether one is debugging in the build tree.  */
10475
10476   dwp_file = get_dwp_file ();
10477   if (dwp_file != NULL)
10478     {
10479       const struct dwp_hash_table *dwp_htab =
10480         is_debug_types ? dwp_file->tus : dwp_file->cus;
10481
10482       if (dwp_htab != NULL)
10483         {
10484           struct dwo_unit *dwo_cutu =
10485             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
10486                                     signature, is_debug_types);
10487
10488           if (dwo_cutu != NULL)
10489             {
10490               if (dwarf2_read_debug)
10491                 {
10492                   fprintf_unfiltered (gdb_stdlog,
10493                                       "Virtual DWO %s %s found: @%s\n",
10494                                       kind, hex_string (signature),
10495                                       host_address_to_string (dwo_cutu));
10496                 }
10497               return dwo_cutu;
10498             }
10499         }
10500     }
10501   else
10502     {
10503       /* No DWP file, look for the DWO file.  */
10504
10505       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
10506       if (*dwo_file_slot == NULL)
10507         {
10508           /* Read in the file and build a table of the CUs/TUs it contains.  */
10509           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
10510         }
10511       /* NOTE: This will be NULL if unable to open the file.  */
10512       dwo_file = *dwo_file_slot;
10513
10514       if (dwo_file != NULL)
10515         {
10516           struct dwo_unit *dwo_cutu = NULL;
10517
10518           if (is_debug_types && dwo_file->tus)
10519             {
10520               struct dwo_unit find_dwo_cutu;
10521
10522               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
10523               find_dwo_cutu.signature = signature;
10524               dwo_cutu = htab_find (dwo_file->tus, &find_dwo_cutu);
10525             }
10526           else if (!is_debug_types && dwo_file->cu)
10527             {
10528               if (signature == dwo_file->cu->signature)
10529                 dwo_cutu = dwo_file->cu;
10530             }
10531
10532           if (dwo_cutu != NULL)
10533             {
10534               if (dwarf2_read_debug)
10535                 {
10536                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
10537                                       kind, dwo_name, hex_string (signature),
10538                                       host_address_to_string (dwo_cutu));
10539                 }
10540               return dwo_cutu;
10541             }
10542         }
10543     }
10544
10545   /* We didn't find it.  This could mean a dwo_id mismatch, or
10546      someone deleted the DWO/DWP file, or the search path isn't set up
10547      correctly to find the file.  */
10548
10549   if (dwarf2_read_debug)
10550     {
10551       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
10552                           kind, dwo_name, hex_string (signature));
10553     }
10554
10555   /* This is a warning and not a complaint because it can be caused by
10556      pilot error (e.g., user accidentally deleting the DWO).  */
10557   warning (_("Could not find DWO %s %s(%s) referenced by %s at offset 0x%x"
10558              " [in module %s]"),
10559            kind, dwo_name, hex_string (signature),
10560            this_unit->is_debug_types ? "TU" : "CU",
10561            this_unit->offset.sect_off, objfile_name (objfile));
10562   return NULL;
10563 }
10564
10565 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
10566    See lookup_dwo_cutu_unit for details.  */
10567
10568 static struct dwo_unit *
10569 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
10570                       const char *dwo_name, const char *comp_dir,
10571                       ULONGEST signature)
10572 {
10573   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
10574 }
10575
10576 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
10577    See lookup_dwo_cutu_unit for details.  */
10578
10579 static struct dwo_unit *
10580 lookup_dwo_type_unit (struct signatured_type *this_tu,
10581                       const char *dwo_name, const char *comp_dir)
10582 {
10583   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
10584 }
10585
10586 /* Traversal function for queue_and_load_all_dwo_tus.  */
10587
10588 static int
10589 queue_and_load_dwo_tu (void **slot, void *info)
10590 {
10591   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
10592   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
10593   ULONGEST signature = dwo_unit->signature;
10594   struct signatured_type *sig_type =
10595     lookup_dwo_signatured_type (per_cu->cu, signature);
10596
10597   if (sig_type != NULL)
10598     {
10599       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
10600
10601       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
10602          a real dependency of PER_CU on SIG_TYPE.  That is detected later
10603          while processing PER_CU.  */
10604       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
10605         load_full_type_unit (sig_cu);
10606       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
10607     }
10608
10609   return 1;
10610 }
10611
10612 /* Queue all TUs contained in the DWO of PER_CU to be read in.
10613    The DWO may have the only definition of the type, though it may not be
10614    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
10615    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
10616
10617 static void
10618 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
10619 {
10620   struct dwo_unit *dwo_unit;
10621   struct dwo_file *dwo_file;
10622
10623   gdb_assert (!per_cu->is_debug_types);
10624   gdb_assert (get_dwp_file () == NULL);
10625   gdb_assert (per_cu->cu != NULL);
10626
10627   dwo_unit = per_cu->cu->dwo_unit;
10628   gdb_assert (dwo_unit != NULL);
10629
10630   dwo_file = dwo_unit->dwo_file;
10631   if (dwo_file->tus != NULL)
10632     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
10633 }
10634
10635 /* Free all resources associated with DWO_FILE.
10636    Close the DWO file and munmap the sections.
10637    All memory should be on the objfile obstack.  */
10638
10639 static void
10640 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
10641 {
10642   int ix;
10643   struct dwarf2_section_info *section;
10644
10645   /* Note: dbfd is NULL for virtual DWO files.  */
10646   gdb_bfd_unref (dwo_file->dbfd);
10647
10648   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
10649 }
10650
10651 /* Wrapper for free_dwo_file for use in cleanups.  */
10652
10653 static void
10654 free_dwo_file_cleanup (void *arg)
10655 {
10656   struct dwo_file *dwo_file = (struct dwo_file *) arg;
10657   struct objfile *objfile = dwarf2_per_objfile->objfile;
10658
10659   free_dwo_file (dwo_file, objfile);
10660 }
10661
10662 /* Traversal function for free_dwo_files.  */
10663
10664 static int
10665 free_dwo_file_from_slot (void **slot, void *info)
10666 {
10667   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
10668   struct objfile *objfile = (struct objfile *) info;
10669
10670   free_dwo_file (dwo_file, objfile);
10671
10672   return 1;
10673 }
10674
10675 /* Free all resources associated with DWO_FILES.  */
10676
10677 static void
10678 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
10679 {
10680   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
10681 }
10682 \f
10683 /* Read in various DIEs.  */
10684
10685 /* qsort helper for inherit_abstract_dies.  */
10686
10687 static int
10688 unsigned_int_compar (const void *ap, const void *bp)
10689 {
10690   unsigned int a = *(unsigned int *) ap;
10691   unsigned int b = *(unsigned int *) bp;
10692
10693   return (a > b) - (b > a);
10694 }
10695
10696 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
10697    Inherit only the children of the DW_AT_abstract_origin DIE not being
10698    already referenced by DW_AT_abstract_origin from the children of the
10699    current DIE.  */
10700
10701 static void
10702 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
10703 {
10704   struct die_info *child_die;
10705   unsigned die_children_count;
10706   /* CU offsets which were referenced by children of the current DIE.  */
10707   sect_offset *offsets;
10708   sect_offset *offsets_end, *offsetp;
10709   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
10710   struct die_info *origin_die;
10711   /* Iterator of the ORIGIN_DIE children.  */
10712   struct die_info *origin_child_die;
10713   struct cleanup *cleanups;
10714   struct attribute *attr;
10715   struct dwarf2_cu *origin_cu;
10716   struct pending **origin_previous_list_in_scope;
10717
10718   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
10719   if (!attr)
10720     return;
10721
10722   /* Note that following die references may follow to a die in a
10723      different cu.  */
10724
10725   origin_cu = cu;
10726   origin_die = follow_die_ref (die, attr, &origin_cu);
10727
10728   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
10729      symbols in.  */
10730   origin_previous_list_in_scope = origin_cu->list_in_scope;
10731   origin_cu->list_in_scope = cu->list_in_scope;
10732
10733   if (die->tag != origin_die->tag
10734       && !(die->tag == DW_TAG_inlined_subroutine
10735            && origin_die->tag == DW_TAG_subprogram))
10736     complaint (&symfile_complaints,
10737                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
10738                die->offset.sect_off, origin_die->offset.sect_off);
10739
10740   child_die = die->child;
10741   die_children_count = 0;
10742   while (child_die && child_die->tag)
10743     {
10744       child_die = sibling_die (child_die);
10745       die_children_count++;
10746     }
10747   offsets = xmalloc (sizeof (*offsets) * die_children_count);
10748   cleanups = make_cleanup (xfree, offsets);
10749
10750   offsets_end = offsets;
10751   child_die = die->child;
10752   while (child_die && child_die->tag)
10753     {
10754       /* For each CHILD_DIE, find the corresponding child of
10755          ORIGIN_DIE.  If there is more than one layer of
10756          DW_AT_abstract_origin, follow them all; there shouldn't be,
10757          but GCC versions at least through 4.4 generate this (GCC PR
10758          40573).  */
10759       struct die_info *child_origin_die = child_die;
10760       struct dwarf2_cu *child_origin_cu = cu;
10761
10762       while (1)
10763         {
10764           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
10765                               child_origin_cu);
10766           if (attr == NULL)
10767             break;
10768           child_origin_die = follow_die_ref (child_origin_die, attr,
10769                                              &child_origin_cu);
10770         }
10771
10772       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
10773          counterpart may exist.  */
10774       if (child_origin_die != child_die)
10775         {
10776           if (child_die->tag != child_origin_die->tag
10777               && !(child_die->tag == DW_TAG_inlined_subroutine
10778                    && child_origin_die->tag == DW_TAG_subprogram))
10779             complaint (&symfile_complaints,
10780                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10781                          "different tags"), child_die->offset.sect_off,
10782                        child_origin_die->offset.sect_off);
10783           if (child_origin_die->parent != origin_die)
10784             complaint (&symfile_complaints,
10785                        _("Child DIE 0x%x and its abstract origin 0x%x have "
10786                          "different parents"), child_die->offset.sect_off,
10787                        child_origin_die->offset.sect_off);
10788           else
10789             *offsets_end++ = child_origin_die->offset;
10790         }
10791       child_die = sibling_die (child_die);
10792     }
10793   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
10794          unsigned_int_compar);
10795   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
10796     if (offsetp[-1].sect_off == offsetp->sect_off)
10797       complaint (&symfile_complaints,
10798                  _("Multiple children of DIE 0x%x refer "
10799                    "to DIE 0x%x as their abstract origin"),
10800                  die->offset.sect_off, offsetp->sect_off);
10801
10802   offsetp = offsets;
10803   origin_child_die = origin_die->child;
10804   while (origin_child_die && origin_child_die->tag)
10805     {
10806       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
10807       while (offsetp < offsets_end
10808              && offsetp->sect_off < origin_child_die->offset.sect_off)
10809         offsetp++;
10810       if (offsetp >= offsets_end
10811           || offsetp->sect_off > origin_child_die->offset.sect_off)
10812         {
10813           /* Found that ORIGIN_CHILD_DIE is really not referenced.  */
10814           process_die (origin_child_die, origin_cu);
10815         }
10816       origin_child_die = sibling_die (origin_child_die);
10817     }
10818   origin_cu->list_in_scope = origin_previous_list_in_scope;
10819
10820   do_cleanups (cleanups);
10821 }
10822
10823 static void
10824 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
10825 {
10826   struct objfile *objfile = cu->objfile;
10827   struct context_stack *new;
10828   CORE_ADDR lowpc;
10829   CORE_ADDR highpc;
10830   struct die_info *child_die;
10831   struct attribute *attr, *call_line, *call_file;
10832   const char *name;
10833   CORE_ADDR baseaddr;
10834   struct block *block;
10835   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
10836   VEC (symbolp) *template_args = NULL;
10837   struct template_symbol *templ_func = NULL;
10838
10839   if (inlined_func)
10840     {
10841       /* If we do not have call site information, we can't show the
10842          caller of this inlined function.  That's too confusing, so
10843          only use the scope for local variables.  */
10844       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
10845       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
10846       if (call_line == NULL || call_file == NULL)
10847         {
10848           read_lexical_block_scope (die, cu);
10849           return;
10850         }
10851     }
10852
10853   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10854
10855   name = dwarf2_name (die, cu);
10856
10857   /* Ignore functions with missing or empty names.  These are actually
10858      illegal according to the DWARF standard.  */
10859   if (name == NULL)
10860     {
10861       complaint (&symfile_complaints,
10862                  _("missing name for subprogram DIE at %d"),
10863                  die->offset.sect_off);
10864       return;
10865     }
10866
10867   /* Ignore functions with missing or invalid low and high pc attributes.  */
10868   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
10869     {
10870       attr = dwarf2_attr (die, DW_AT_external, cu);
10871       if (!attr || !DW_UNSND (attr))
10872         complaint (&symfile_complaints,
10873                    _("cannot get low and high bounds "
10874                      "for subprogram DIE at %d"),
10875                    die->offset.sect_off);
10876       return;
10877     }
10878
10879   lowpc += baseaddr;
10880   highpc += baseaddr;
10881
10882   /* If we have any template arguments, then we must allocate a
10883      different sort of symbol.  */
10884   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
10885     {
10886       if (child_die->tag == DW_TAG_template_type_param
10887           || child_die->tag == DW_TAG_template_value_param)
10888         {
10889           templ_func = allocate_template_symbol (objfile);
10890           templ_func->base.is_cplus_template_function = 1;
10891           break;
10892         }
10893     }
10894
10895   new = push_context (0, lowpc);
10896   new->name = new_symbol_full (die, read_type_die (die, cu), cu,
10897                                (struct symbol *) templ_func);
10898
10899   /* If there is a location expression for DW_AT_frame_base, record
10900      it.  */
10901   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
10902   if (attr)
10903     dwarf2_symbol_mark_computed (attr, new->name, cu, 1);
10904
10905   cu->list_in_scope = &local_symbols;
10906
10907   if (die->child != NULL)
10908     {
10909       child_die = die->child;
10910       while (child_die && child_die->tag)
10911         {
10912           if (child_die->tag == DW_TAG_template_type_param
10913               || child_die->tag == DW_TAG_template_value_param)
10914             {
10915               struct symbol *arg = new_symbol (child_die, NULL, cu);
10916
10917               if (arg != NULL)
10918                 VEC_safe_push (symbolp, template_args, arg);
10919             }
10920           else
10921             process_die (child_die, cu);
10922           child_die = sibling_die (child_die);
10923         }
10924     }
10925
10926   inherit_abstract_dies (die, cu);
10927
10928   /* If we have a DW_AT_specification, we might need to import using
10929      directives from the context of the specification DIE.  See the
10930      comment in determine_prefix.  */
10931   if (cu->language == language_cplus
10932       && dwarf2_attr (die, DW_AT_specification, cu))
10933     {
10934       struct dwarf2_cu *spec_cu = cu;
10935       struct die_info *spec_die = die_specification (die, &spec_cu);
10936
10937       while (spec_die)
10938         {
10939           child_die = spec_die->child;
10940           while (child_die && child_die->tag)
10941             {
10942               if (child_die->tag == DW_TAG_imported_module)
10943                 process_die (child_die, spec_cu);
10944               child_die = sibling_die (child_die);
10945             }
10946
10947           /* In some cases, GCC generates specification DIEs that
10948              themselves contain DW_AT_specification attributes.  */
10949           spec_die = die_specification (spec_die, &spec_cu);
10950         }
10951     }
10952
10953   new = pop_context ();
10954   /* Make a block for the local symbols within.  */
10955   block = finish_block (new->name, &local_symbols, new->old_blocks,
10956                         lowpc, highpc, objfile);
10957
10958   /* For C++, set the block's scope.  */
10959   if ((cu->language == language_cplus || cu->language == language_fortran)
10960       && cu->processing_has_namespace_info)
10961     block_set_scope (block, determine_prefix (die, cu),
10962                      &objfile->objfile_obstack);
10963
10964   /* If we have address ranges, record them.  */
10965   dwarf2_record_block_ranges (die, block, baseaddr, cu);
10966
10967   /* Attach template arguments to function.  */
10968   if (! VEC_empty (symbolp, template_args))
10969     {
10970       gdb_assert (templ_func != NULL);
10971
10972       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
10973       templ_func->template_arguments
10974         = obstack_alloc (&objfile->objfile_obstack,
10975                          (templ_func->n_template_arguments
10976                           * sizeof (struct symbol *)));
10977       memcpy (templ_func->template_arguments,
10978               VEC_address (symbolp, template_args),
10979               (templ_func->n_template_arguments * sizeof (struct symbol *)));
10980       VEC_free (symbolp, template_args);
10981     }
10982
10983   /* In C++, we can have functions nested inside functions (e.g., when
10984      a function declares a class that has methods).  This means that
10985      when we finish processing a function scope, we may need to go
10986      back to building a containing block's symbol lists.  */
10987   local_symbols = new->locals;
10988   using_directives = new->using_directives;
10989
10990   /* If we've finished processing a top-level function, subsequent
10991      symbols go in the file symbol list.  */
10992   if (outermost_context_p ())
10993     cu->list_in_scope = &file_symbols;
10994 }
10995
10996 /* Process all the DIES contained within a lexical block scope.  Start
10997    a new scope, process the dies, and then close the scope.  */
10998
10999 static void
11000 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11001 {
11002   struct objfile *objfile = cu->objfile;
11003   struct context_stack *new;
11004   CORE_ADDR lowpc, highpc;
11005   struct die_info *child_die;
11006   CORE_ADDR baseaddr;
11007
11008   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11009
11010   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11011   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11012      as multiple lexical blocks?  Handling children in a sane way would
11013      be nasty.  Might be easier to properly extend generic blocks to
11014      describe ranges.  */
11015   if (!dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11016     return;
11017   lowpc += baseaddr;
11018   highpc += baseaddr;
11019
11020   push_context (0, lowpc);
11021   if (die->child != NULL)
11022     {
11023       child_die = die->child;
11024       while (child_die && child_die->tag)
11025         {
11026           process_die (child_die, cu);
11027           child_die = sibling_die (child_die);
11028         }
11029     }
11030   new = pop_context ();
11031
11032   if (local_symbols != NULL || using_directives != NULL)
11033     {
11034       struct block *block
11035         = finish_block (0, &local_symbols, new->old_blocks, new->start_addr,
11036                         highpc, objfile);
11037
11038       /* Note that recording ranges after traversing children, as we
11039          do here, means that recording a parent's ranges entails
11040          walking across all its children's ranges as they appear in
11041          the address map, which is quadratic behavior.
11042
11043          It would be nicer to record the parent's ranges before
11044          traversing its children, simply overriding whatever you find
11045          there.  But since we don't even decide whether to create a
11046          block until after we've traversed its children, that's hard
11047          to do.  */
11048       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11049     }
11050   local_symbols = new->locals;
11051   using_directives = new->using_directives;
11052 }
11053
11054 /* Read in DW_TAG_GNU_call_site and insert it to CU->call_site_htab.  */
11055
11056 static void
11057 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11058 {
11059   struct objfile *objfile = cu->objfile;
11060   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11061   CORE_ADDR pc, baseaddr;
11062   struct attribute *attr;
11063   struct call_site *call_site, call_site_local;
11064   void **slot;
11065   int nparams;
11066   struct die_info *child_die;
11067
11068   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11069
11070   attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11071   if (!attr)
11072     {
11073       complaint (&symfile_complaints,
11074                  _("missing DW_AT_low_pc for DW_TAG_GNU_call_site "
11075                    "DIE 0x%x [in module %s]"),
11076                  die->offset.sect_off, objfile_name (objfile));
11077       return;
11078     }
11079   pc = DW_ADDR (attr) + baseaddr;
11080
11081   if (cu->call_site_htab == NULL)
11082     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11083                                                NULL, &objfile->objfile_obstack,
11084                                                hashtab_obstack_allocate, NULL);
11085   call_site_local.pc = pc;
11086   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11087   if (*slot != NULL)
11088     {
11089       complaint (&symfile_complaints,
11090                  _("Duplicate PC %s for DW_TAG_GNU_call_site "
11091                    "DIE 0x%x [in module %s]"),
11092                  paddress (gdbarch, pc), die->offset.sect_off,
11093                  objfile_name (objfile));
11094       return;
11095     }
11096
11097   /* Count parameters at the caller.  */
11098
11099   nparams = 0;
11100   for (child_die = die->child; child_die && child_die->tag;
11101        child_die = sibling_die (child_die))
11102     {
11103       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11104         {
11105           complaint (&symfile_complaints,
11106                      _("Tag %d is not DW_TAG_GNU_call_site_parameter in "
11107                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11108                      child_die->tag, child_die->offset.sect_off,
11109                      objfile_name (objfile));
11110           continue;
11111         }
11112
11113       nparams++;
11114     }
11115
11116   call_site = obstack_alloc (&objfile->objfile_obstack,
11117                              (sizeof (*call_site)
11118                               + (sizeof (*call_site->parameter)
11119                                  * (nparams - 1))));
11120   *slot = call_site;
11121   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11122   call_site->pc = pc;
11123
11124   if (dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11125     {
11126       struct die_info *func_die;
11127
11128       /* Skip also over DW_TAG_inlined_subroutine.  */
11129       for (func_die = die->parent;
11130            func_die && func_die->tag != DW_TAG_subprogram
11131            && func_die->tag != DW_TAG_subroutine_type;
11132            func_die = func_die->parent);
11133
11134       /* DW_AT_GNU_all_call_sites is a superset
11135          of DW_AT_GNU_all_tail_call_sites.  */
11136       if (func_die
11137           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11138           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11139         {
11140           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11141              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11142              both the initial caller containing the real return address PC and
11143              the final callee containing the current PC of a chain of tail
11144              calls do not need to have the tail call list complete.  But any
11145              function candidate for a virtual tail call frame searched via
11146              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11147              determined unambiguously.  */
11148         }
11149       else
11150         {
11151           struct type *func_type = NULL;
11152
11153           if (func_die)
11154             func_type = get_die_type (func_die, cu);
11155           if (func_type != NULL)
11156             {
11157               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11158
11159               /* Enlist this call site to the function.  */
11160               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11161               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11162             }
11163           else
11164             complaint (&symfile_complaints,
11165                        _("Cannot find function owning DW_TAG_GNU_call_site "
11166                          "DIE 0x%x [in module %s]"),
11167                        die->offset.sect_off, objfile_name (objfile));
11168         }
11169     }
11170
11171   attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11172   if (attr == NULL)
11173     attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11174   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
11175   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
11176     /* Keep NULL DWARF_BLOCK.  */;
11177   else if (attr_form_is_block (attr))
11178     {
11179       struct dwarf2_locexpr_baton *dlbaton;
11180
11181       dlbaton = obstack_alloc (&objfile->objfile_obstack, sizeof (*dlbaton));
11182       dlbaton->data = DW_BLOCK (attr)->data;
11183       dlbaton->size = DW_BLOCK (attr)->size;
11184       dlbaton->per_cu = cu->per_cu;
11185
11186       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
11187     }
11188   else if (attr_form_is_ref (attr))
11189     {
11190       struct dwarf2_cu *target_cu = cu;
11191       struct die_info *target_die;
11192
11193       target_die = follow_die_ref (die, attr, &target_cu);
11194       gdb_assert (target_cu->objfile == objfile);
11195       if (die_is_declaration (target_die, target_cu))
11196         {
11197           const char *target_physname = NULL;
11198           struct attribute *target_attr;
11199
11200           /* Prefer the mangled name; otherwise compute the demangled one.  */
11201           target_attr = dwarf2_attr (target_die, DW_AT_linkage_name, target_cu);
11202           if (target_attr == NULL)
11203             target_attr = dwarf2_attr (target_die, DW_AT_MIPS_linkage_name,
11204                                        target_cu);
11205           if (target_attr != NULL && DW_STRING (target_attr) != NULL)
11206             target_physname = DW_STRING (target_attr);
11207           else
11208             target_physname = dwarf2_physname (NULL, target_die, target_cu);
11209           if (target_physname == NULL)
11210             complaint (&symfile_complaints,
11211                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11212                          "physname, for referencing DIE 0x%x [in module %s]"),
11213                        die->offset.sect_off, objfile_name (objfile));
11214           else
11215             SET_FIELD_PHYSNAME (call_site->target, target_physname);
11216         }
11217       else
11218         {
11219           CORE_ADDR lowpc;
11220
11221           /* DW_AT_entry_pc should be preferred.  */
11222           if (!dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL))
11223             complaint (&symfile_complaints,
11224                        _("DW_AT_GNU_call_site_target target DIE has invalid "
11225                          "low pc, for referencing DIE 0x%x [in module %s]"),
11226                        die->offset.sect_off, objfile_name (objfile));
11227           else
11228             SET_FIELD_PHYSADDR (call_site->target, lowpc + baseaddr);
11229         }
11230     }
11231   else
11232     complaint (&symfile_complaints,
11233                _("DW_TAG_GNU_call_site DW_AT_GNU_call_site_target is neither "
11234                  "block nor reference, for DIE 0x%x [in module %s]"),
11235                die->offset.sect_off, objfile_name (objfile));
11236
11237   call_site->per_cu = cu->per_cu;
11238
11239   for (child_die = die->child;
11240        child_die && child_die->tag;
11241        child_die = sibling_die (child_die))
11242     {
11243       struct call_site_parameter *parameter;
11244       struct attribute *loc, *origin;
11245
11246       if (child_die->tag != DW_TAG_GNU_call_site_parameter)
11247         {
11248           /* Already printed the complaint above.  */
11249           continue;
11250         }
11251
11252       gdb_assert (call_site->parameter_count < nparams);
11253       parameter = &call_site->parameter[call_site->parameter_count];
11254
11255       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
11256          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
11257          register is contained in DW_AT_GNU_call_site_value.  */
11258
11259       loc = dwarf2_attr (child_die, DW_AT_location, cu);
11260       origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
11261       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
11262         {
11263           sect_offset offset;
11264
11265           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
11266           offset = dwarf2_get_ref_die_offset (origin);
11267           if (!offset_in_cu_p (&cu->header, offset))
11268             {
11269               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
11270                  binding can be done only inside one CU.  Such referenced DIE
11271                  therefore cannot be even moved to DW_TAG_partial_unit.  */
11272               complaint (&symfile_complaints,
11273                          _("DW_AT_abstract_origin offset is not in CU for "
11274                            "DW_TAG_GNU_call_site child DIE 0x%x "
11275                            "[in module %s]"),
11276                          child_die->offset.sect_off, objfile_name (objfile));
11277               continue;
11278             }
11279           parameter->u.param_offset.cu_off = (offset.sect_off
11280                                               - cu->header.offset.sect_off);
11281         }
11282       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
11283         {
11284           complaint (&symfile_complaints,
11285                      _("No DW_FORM_block* DW_AT_location for "
11286                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11287                      child_die->offset.sect_off, objfile_name (objfile));
11288           continue;
11289         }
11290       else
11291         {
11292           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
11293             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
11294           if (parameter->u.dwarf_reg != -1)
11295             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
11296           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
11297                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
11298                                              &parameter->u.fb_offset))
11299             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
11300           else
11301             {
11302               complaint (&symfile_complaints,
11303                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
11304                            "for DW_FORM_block* DW_AT_location is supported for "
11305                            "DW_TAG_GNU_call_site child DIE 0x%x "
11306                            "[in module %s]"),
11307                          child_die->offset.sect_off, objfile_name (objfile));
11308               continue;
11309             }
11310         }
11311
11312       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
11313       if (!attr_form_is_block (attr))
11314         {
11315           complaint (&symfile_complaints,
11316                      _("No DW_FORM_block* DW_AT_GNU_call_site_value for "
11317                        "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11318                      child_die->offset.sect_off, objfile_name (objfile));
11319           continue;
11320         }
11321       parameter->value = DW_BLOCK (attr)->data;
11322       parameter->value_size = DW_BLOCK (attr)->size;
11323
11324       /* Parameters are not pre-cleared by memset above.  */
11325       parameter->data_value = NULL;
11326       parameter->data_value_size = 0;
11327       call_site->parameter_count++;
11328
11329       attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
11330       if (attr)
11331         {
11332           if (!attr_form_is_block (attr))
11333             complaint (&symfile_complaints,
11334                        _("No DW_FORM_block* DW_AT_GNU_call_site_data_value for "
11335                          "DW_TAG_GNU_call_site child DIE 0x%x [in module %s]"),
11336                        child_die->offset.sect_off, objfile_name (objfile));
11337           else
11338             {
11339               parameter->data_value = DW_BLOCK (attr)->data;
11340               parameter->data_value_size = DW_BLOCK (attr)->size;
11341             }
11342         }
11343     }
11344 }
11345
11346 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
11347    Return 1 if the attributes are present and valid, otherwise, return 0.
11348    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
11349
11350 static int
11351 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
11352                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
11353                     struct partial_symtab *ranges_pst)
11354 {
11355   struct objfile *objfile = cu->objfile;
11356   struct comp_unit_head *cu_header = &cu->header;
11357   bfd *obfd = objfile->obfd;
11358   unsigned int addr_size = cu_header->addr_size;
11359   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11360   /* Base address selection entry.  */
11361   CORE_ADDR base;
11362   int found_base;
11363   unsigned int dummy;
11364   const gdb_byte *buffer;
11365   CORE_ADDR marker;
11366   int low_set;
11367   CORE_ADDR low = 0;
11368   CORE_ADDR high = 0;
11369   CORE_ADDR baseaddr;
11370
11371   found_base = cu->base_known;
11372   base = cu->base_address;
11373
11374   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11375   if (offset >= dwarf2_per_objfile->ranges.size)
11376     {
11377       complaint (&symfile_complaints,
11378                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
11379                  offset);
11380       return 0;
11381     }
11382   buffer = dwarf2_per_objfile->ranges.buffer + offset;
11383
11384   /* Read in the largest possible address.  */
11385   marker = read_address (obfd, buffer, cu, &dummy);
11386   if ((marker & mask) == mask)
11387     {
11388       /* If we found the largest possible address, then
11389          read the base address.  */
11390       base = read_address (obfd, buffer + addr_size, cu, &dummy);
11391       buffer += 2 * addr_size;
11392       offset += 2 * addr_size;
11393       found_base = 1;
11394     }
11395
11396   low_set = 0;
11397
11398   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11399
11400   while (1)
11401     {
11402       CORE_ADDR range_beginning, range_end;
11403
11404       range_beginning = read_address (obfd, buffer, cu, &dummy);
11405       buffer += addr_size;
11406       range_end = read_address (obfd, buffer, cu, &dummy);
11407       buffer += addr_size;
11408       offset += 2 * addr_size;
11409
11410       /* An end of list marker is a pair of zero addresses.  */
11411       if (range_beginning == 0 && range_end == 0)
11412         /* Found the end of list entry.  */
11413         break;
11414
11415       /* Each base address selection entry is a pair of 2 values.
11416          The first is the largest possible address, the second is
11417          the base address.  Check for a base address here.  */
11418       if ((range_beginning & mask) == mask)
11419         {
11420           /* If we found the largest possible address, then
11421              read the base address.  */
11422           base = read_address (obfd, buffer + addr_size, cu, &dummy);
11423           found_base = 1;
11424           continue;
11425         }
11426
11427       if (!found_base)
11428         {
11429           /* We have no valid base address for the ranges
11430              data.  */
11431           complaint (&symfile_complaints,
11432                      _("Invalid .debug_ranges data (no base address)"));
11433           return 0;
11434         }
11435
11436       if (range_beginning > range_end)
11437         {
11438           /* Inverted range entries are invalid.  */
11439           complaint (&symfile_complaints,
11440                      _("Invalid .debug_ranges data (inverted range)"));
11441           return 0;
11442         }
11443
11444       /* Empty range entries have no effect.  */
11445       if (range_beginning == range_end)
11446         continue;
11447
11448       range_beginning += base;
11449       range_end += base;
11450
11451       /* A not-uncommon case of bad debug info.
11452          Don't pollute the addrmap with bad data.  */
11453       if (range_beginning + baseaddr == 0
11454           && !dwarf2_per_objfile->has_section_at_zero)
11455         {
11456           complaint (&symfile_complaints,
11457                      _(".debug_ranges entry has start address of zero"
11458                        " [in module %s]"), objfile_name (objfile));
11459           continue;
11460         }
11461
11462       if (ranges_pst != NULL)
11463         addrmap_set_empty (objfile->psymtabs_addrmap,
11464                            range_beginning + baseaddr,
11465                            range_end - 1 + baseaddr,
11466                            ranges_pst);
11467
11468       /* FIXME: This is recording everything as a low-high
11469          segment of consecutive addresses.  We should have a
11470          data structure for discontiguous block ranges
11471          instead.  */
11472       if (! low_set)
11473         {
11474           low = range_beginning;
11475           high = range_end;
11476           low_set = 1;
11477         }
11478       else
11479         {
11480           if (range_beginning < low)
11481             low = range_beginning;
11482           if (range_end > high)
11483             high = range_end;
11484         }
11485     }
11486
11487   if (! low_set)
11488     /* If the first entry is an end-of-list marker, the range
11489        describes an empty scope, i.e. no instructions.  */
11490     return 0;
11491
11492   if (low_return)
11493     *low_return = low;
11494   if (high_return)
11495     *high_return = high;
11496   return 1;
11497 }
11498
11499 /* Get low and high pc attributes from a die.  Return 1 if the attributes
11500    are present and valid, otherwise, return 0.  Return -1 if the range is
11501    discontinuous, i.e. derived from DW_AT_ranges information.  */
11502
11503 static int
11504 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
11505                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
11506                       struct partial_symtab *pst)
11507 {
11508   struct attribute *attr;
11509   struct attribute *attr_high;
11510   CORE_ADDR low = 0;
11511   CORE_ADDR high = 0;
11512   int ret = 0;
11513
11514   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11515   if (attr_high)
11516     {
11517       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11518       if (attr)
11519         {
11520           low = DW_ADDR (attr);
11521           if (attr_high->form == DW_FORM_addr
11522               || attr_high->form == DW_FORM_GNU_addr_index)
11523             high = DW_ADDR (attr_high);
11524           else
11525             high = low + DW_UNSND (attr_high);
11526         }
11527       else
11528         /* Found high w/o low attribute.  */
11529         return 0;
11530
11531       /* Found consecutive range of addresses.  */
11532       ret = 1;
11533     }
11534   else
11535     {
11536       attr = dwarf2_attr (die, DW_AT_ranges, cu);
11537       if (attr != NULL)
11538         {
11539           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11540              We take advantage of the fact that DW_AT_ranges does not appear
11541              in DW_TAG_compile_unit of DWO files.  */
11542           int need_ranges_base = die->tag != DW_TAG_compile_unit;
11543           unsigned int ranges_offset = (DW_UNSND (attr)
11544                                         + (need_ranges_base
11545                                            ? cu->ranges_base
11546                                            : 0));
11547
11548           /* Value of the DW_AT_ranges attribute is the offset in the
11549              .debug_ranges section.  */
11550           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
11551             return 0;
11552           /* Found discontinuous range of addresses.  */
11553           ret = -1;
11554         }
11555     }
11556
11557   /* read_partial_die has also the strict LOW < HIGH requirement.  */
11558   if (high <= low)
11559     return 0;
11560
11561   /* When using the GNU linker, .gnu.linkonce. sections are used to
11562      eliminate duplicate copies of functions and vtables and such.
11563      The linker will arbitrarily choose one and discard the others.
11564      The AT_*_pc values for such functions refer to local labels in
11565      these sections.  If the section from that file was discarded, the
11566      labels are not in the output, so the relocs get a value of 0.
11567      If this is a discarded function, mark the pc bounds as invalid,
11568      so that GDB will ignore it.  */
11569   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
11570     return 0;
11571
11572   *lowpc = low;
11573   if (highpc)
11574     *highpc = high;
11575   return ret;
11576 }
11577
11578 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
11579    its low and high PC addresses.  Do nothing if these addresses could not
11580    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
11581    and HIGHPC to the high address if greater than HIGHPC.  */
11582
11583 static void
11584 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
11585                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
11586                                  struct dwarf2_cu *cu)
11587 {
11588   CORE_ADDR low, high;
11589   struct die_info *child = die->child;
11590
11591   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL))
11592     {
11593       *lowpc = min (*lowpc, low);
11594       *highpc = max (*highpc, high);
11595     }
11596
11597   /* If the language does not allow nested subprograms (either inside
11598      subprograms or lexical blocks), we're done.  */
11599   if (cu->language != language_ada)
11600     return;
11601
11602   /* Check all the children of the given DIE.  If it contains nested
11603      subprograms, then check their pc bounds.  Likewise, we need to
11604      check lexical blocks as well, as they may also contain subprogram
11605      definitions.  */
11606   while (child && child->tag)
11607     {
11608       if (child->tag == DW_TAG_subprogram
11609           || child->tag == DW_TAG_lexical_block)
11610         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
11611       child = sibling_die (child);
11612     }
11613 }
11614
11615 /* Get the low and high pc's represented by the scope DIE, and store
11616    them in *LOWPC and *HIGHPC.  If the correct values can't be
11617    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
11618
11619 static void
11620 get_scope_pc_bounds (struct die_info *die,
11621                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
11622                      struct dwarf2_cu *cu)
11623 {
11624   CORE_ADDR best_low = (CORE_ADDR) -1;
11625   CORE_ADDR best_high = (CORE_ADDR) 0;
11626   CORE_ADDR current_low, current_high;
11627
11628   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL))
11629     {
11630       best_low = current_low;
11631       best_high = current_high;
11632     }
11633   else
11634     {
11635       struct die_info *child = die->child;
11636
11637       while (child && child->tag)
11638         {
11639           switch (child->tag) {
11640           case DW_TAG_subprogram:
11641             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
11642             break;
11643           case DW_TAG_namespace:
11644           case DW_TAG_module:
11645             /* FIXME: carlton/2004-01-16: Should we do this for
11646                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
11647                that current GCC's always emit the DIEs corresponding
11648                to definitions of methods of classes as children of a
11649                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
11650                the DIEs giving the declarations, which could be
11651                anywhere).  But I don't see any reason why the
11652                standards says that they have to be there.  */
11653             get_scope_pc_bounds (child, &current_low, &current_high, cu);
11654
11655             if (current_low != ((CORE_ADDR) -1))
11656               {
11657                 best_low = min (best_low, current_low);
11658                 best_high = max (best_high, current_high);
11659               }
11660             break;
11661           default:
11662             /* Ignore.  */
11663             break;
11664           }
11665
11666           child = sibling_die (child);
11667         }
11668     }
11669
11670   *lowpc = best_low;
11671   *highpc = best_high;
11672 }
11673
11674 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
11675    in DIE.  */
11676
11677 static void
11678 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
11679                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
11680 {
11681   struct objfile *objfile = cu->objfile;
11682   struct attribute *attr;
11683   struct attribute *attr_high;
11684
11685   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
11686   if (attr_high)
11687     {
11688       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11689       if (attr)
11690         {
11691           CORE_ADDR low = DW_ADDR (attr);
11692           CORE_ADDR high;
11693           if (attr_high->form == DW_FORM_addr
11694               || attr_high->form == DW_FORM_GNU_addr_index)
11695             high = DW_ADDR (attr_high);
11696           else
11697             high = low + DW_UNSND (attr_high);
11698
11699           record_block_range (block, baseaddr + low, baseaddr + high - 1);
11700         }
11701     }
11702
11703   attr = dwarf2_attr (die, DW_AT_ranges, cu);
11704   if (attr)
11705     {
11706       bfd *obfd = objfile->obfd;
11707       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
11708          We take advantage of the fact that DW_AT_ranges does not appear
11709          in DW_TAG_compile_unit of DWO files.  */
11710       int need_ranges_base = die->tag != DW_TAG_compile_unit;
11711
11712       /* The value of the DW_AT_ranges attribute is the offset of the
11713          address range list in the .debug_ranges section.  */
11714       unsigned long offset = (DW_UNSND (attr)
11715                               + (need_ranges_base ? cu->ranges_base : 0));
11716       const gdb_byte *buffer;
11717
11718       /* For some target architectures, but not others, the
11719          read_address function sign-extends the addresses it returns.
11720          To recognize base address selection entries, we need a
11721          mask.  */
11722       unsigned int addr_size = cu->header.addr_size;
11723       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
11724
11725       /* The base address, to which the next pair is relative.  Note
11726          that this 'base' is a DWARF concept: most entries in a range
11727          list are relative, to reduce the number of relocs against the
11728          debugging information.  This is separate from this function's
11729          'baseaddr' argument, which GDB uses to relocate debugging
11730          information from a shared library based on the address at
11731          which the library was loaded.  */
11732       CORE_ADDR base = cu->base_address;
11733       int base_known = cu->base_known;
11734
11735       dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
11736       if (offset >= dwarf2_per_objfile->ranges.size)
11737         {
11738           complaint (&symfile_complaints,
11739                      _("Offset %lu out of bounds for DW_AT_ranges attribute"),
11740                      offset);
11741           return;
11742         }
11743       buffer = dwarf2_per_objfile->ranges.buffer + offset;
11744
11745       for (;;)
11746         {
11747           unsigned int bytes_read;
11748           CORE_ADDR start, end;
11749
11750           start = read_address (obfd, buffer, cu, &bytes_read);
11751           buffer += bytes_read;
11752           end = read_address (obfd, buffer, cu, &bytes_read);
11753           buffer += bytes_read;
11754
11755           /* Did we find the end of the range list?  */
11756           if (start == 0 && end == 0)
11757             break;
11758
11759           /* Did we find a base address selection entry?  */
11760           else if ((start & base_select_mask) == base_select_mask)
11761             {
11762               base = end;
11763               base_known = 1;
11764             }
11765
11766           /* We found an ordinary address range.  */
11767           else
11768             {
11769               if (!base_known)
11770                 {
11771                   complaint (&symfile_complaints,
11772                              _("Invalid .debug_ranges data "
11773                                "(no base address)"));
11774                   return;
11775                 }
11776
11777               if (start > end)
11778                 {
11779                   /* Inverted range entries are invalid.  */
11780                   complaint (&symfile_complaints,
11781                              _("Invalid .debug_ranges data "
11782                                "(inverted range)"));
11783                   return;
11784                 }
11785
11786               /* Empty range entries have no effect.  */
11787               if (start == end)
11788                 continue;
11789
11790               start += base + baseaddr;
11791               end += base + baseaddr;
11792
11793               /* A not-uncommon case of bad debug info.
11794                  Don't pollute the addrmap with bad data.  */
11795               if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
11796                 {
11797                   complaint (&symfile_complaints,
11798                              _(".debug_ranges entry has start address of zero"
11799                                " [in module %s]"), objfile_name (objfile));
11800                   continue;
11801                 }
11802
11803               record_block_range (block, start, end - 1);
11804             }
11805         }
11806     }
11807 }
11808
11809 /* Check whether the producer field indicates either of GCC < 4.6, or the
11810    Intel C/C++ compiler, and cache the result in CU.  */
11811
11812 static void
11813 check_producer (struct dwarf2_cu *cu)
11814 {
11815   const char *cs;
11816   int major, minor, release;
11817
11818   if (cu->producer == NULL)
11819     {
11820       /* For unknown compilers expect their behavior is DWARF version
11821          compliant.
11822
11823          GCC started to support .debug_types sections by -gdwarf-4 since
11824          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
11825          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
11826          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
11827          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
11828     }
11829   else if (strncmp (cu->producer, "GNU ", strlen ("GNU ")) == 0)
11830     {
11831       /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
11832
11833       cs = &cu->producer[strlen ("GNU ")];
11834       while (*cs && !isdigit (*cs))
11835         cs++;
11836       if (sscanf (cs, "%d.%d.%d", &major, &minor, &release) != 3)
11837         {
11838           /* Not recognized as GCC.  */
11839         }
11840       else
11841         {
11842           cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
11843           cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
11844         }
11845     }
11846   else if (strncmp (cu->producer, "Intel(R) C", strlen ("Intel(R) C")) == 0)
11847     cu->producer_is_icc = 1;
11848   else
11849     {
11850       /* For other non-GCC compilers, expect their behavior is DWARF version
11851          compliant.  */
11852     }
11853
11854   cu->checked_producer = 1;
11855 }
11856
11857 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
11858    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
11859    during 4.6.0 experimental.  */
11860
11861 static int
11862 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
11863 {
11864   if (!cu->checked_producer)
11865     check_producer (cu);
11866
11867   return cu->producer_is_gxx_lt_4_6;
11868 }
11869
11870 /* Return the default accessibility type if it is not overriden by
11871    DW_AT_accessibility.  */
11872
11873 static enum dwarf_access_attribute
11874 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
11875 {
11876   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
11877     {
11878       /* The default DWARF 2 accessibility for members is public, the default
11879          accessibility for inheritance is private.  */
11880
11881       if (die->tag != DW_TAG_inheritance)
11882         return DW_ACCESS_public;
11883       else
11884         return DW_ACCESS_private;
11885     }
11886   else
11887     {
11888       /* DWARF 3+ defines the default accessibility a different way.  The same
11889          rules apply now for DW_TAG_inheritance as for the members and it only
11890          depends on the container kind.  */
11891
11892       if (die->parent->tag == DW_TAG_class_type)
11893         return DW_ACCESS_private;
11894       else
11895         return DW_ACCESS_public;
11896     }
11897 }
11898
11899 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
11900    offset.  If the attribute was not found return 0, otherwise return
11901    1.  If it was found but could not properly be handled, set *OFFSET
11902    to 0.  */
11903
11904 static int
11905 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
11906                              LONGEST *offset)
11907 {
11908   struct attribute *attr;
11909
11910   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
11911   if (attr != NULL)
11912     {
11913       *offset = 0;
11914
11915       /* Note that we do not check for a section offset first here.
11916          This is because DW_AT_data_member_location is new in DWARF 4,
11917          so if we see it, we can assume that a constant form is really
11918          a constant and not a section offset.  */
11919       if (attr_form_is_constant (attr))
11920         *offset = dwarf2_get_attr_constant_value (attr, 0);
11921       else if (attr_form_is_section_offset (attr))
11922         dwarf2_complex_location_expr_complaint ();
11923       else if (attr_form_is_block (attr))
11924         *offset = decode_locdesc (DW_BLOCK (attr), cu);
11925       else
11926         dwarf2_complex_location_expr_complaint ();
11927
11928       return 1;
11929     }
11930
11931   return 0;
11932 }
11933
11934 /* Add an aggregate field to the field list.  */
11935
11936 static void
11937 dwarf2_add_field (struct field_info *fip, struct die_info *die,
11938                   struct dwarf2_cu *cu)
11939 {
11940   struct objfile *objfile = cu->objfile;
11941   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11942   struct nextfield *new_field;
11943   struct attribute *attr;
11944   struct field *fp;
11945   const char *fieldname = "";
11946
11947   /* Allocate a new field list entry and link it in.  */
11948   new_field = (struct nextfield *) xmalloc (sizeof (struct nextfield));
11949   make_cleanup (xfree, new_field);
11950   memset (new_field, 0, sizeof (struct nextfield));
11951
11952   if (die->tag == DW_TAG_inheritance)
11953     {
11954       new_field->next = fip->baseclasses;
11955       fip->baseclasses = new_field;
11956     }
11957   else
11958     {
11959       new_field->next = fip->fields;
11960       fip->fields = new_field;
11961     }
11962   fip->nfields++;
11963
11964   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
11965   if (attr)
11966     new_field->accessibility = DW_UNSND (attr);
11967   else
11968     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
11969   if (new_field->accessibility != DW_ACCESS_public)
11970     fip->non_public_fields = 1;
11971
11972   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
11973   if (attr)
11974     new_field->virtuality = DW_UNSND (attr);
11975   else
11976     new_field->virtuality = DW_VIRTUALITY_none;
11977
11978   fp = &new_field->field;
11979
11980   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
11981     {
11982       LONGEST offset;
11983
11984       /* Data member other than a C++ static data member.  */
11985
11986       /* Get type of field.  */
11987       fp->type = die_type (die, cu);
11988
11989       SET_FIELD_BITPOS (*fp, 0);
11990
11991       /* Get bit size of field (zero if none).  */
11992       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
11993       if (attr)
11994         {
11995           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
11996         }
11997       else
11998         {
11999           FIELD_BITSIZE (*fp) = 0;
12000         }
12001
12002       /* Get bit offset of field.  */
12003       if (handle_data_member_location (die, cu, &offset))
12004         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12005       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12006       if (attr)
12007         {
12008           if (gdbarch_bits_big_endian (gdbarch))
12009             {
12010               /* For big endian bits, the DW_AT_bit_offset gives the
12011                  additional bit offset from the MSB of the containing
12012                  anonymous object to the MSB of the field.  We don't
12013                  have to do anything special since we don't need to
12014                  know the size of the anonymous object.  */
12015               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12016             }
12017           else
12018             {
12019               /* For little endian bits, compute the bit offset to the
12020                  MSB of the anonymous object, subtract off the number of
12021                  bits from the MSB of the field to the MSB of the
12022                  object, and then subtract off the number of bits of
12023                  the field itself.  The result is the bit offset of
12024                  the LSB of the field.  */
12025               int anonymous_size;
12026               int bit_offset = DW_UNSND (attr);
12027
12028               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12029               if (attr)
12030                 {
12031                   /* The size of the anonymous object containing
12032                      the bit field is explicit, so use the
12033                      indicated size (in bytes).  */
12034                   anonymous_size = DW_UNSND (attr);
12035                 }
12036               else
12037                 {
12038                   /* The size of the anonymous object containing
12039                      the bit field must be inferred from the type
12040                      attribute of the data member containing the
12041                      bit field.  */
12042                   anonymous_size = TYPE_LENGTH (fp->type);
12043                 }
12044               SET_FIELD_BITPOS (*fp,
12045                                 (FIELD_BITPOS (*fp)
12046                                  + anonymous_size * bits_per_byte
12047                                  - bit_offset - FIELD_BITSIZE (*fp)));
12048             }
12049         }
12050
12051       /* Get name of field.  */
12052       fieldname = dwarf2_name (die, cu);
12053       if (fieldname == NULL)
12054         fieldname = "";
12055
12056       /* The name is already allocated along with this objfile, so we don't
12057          need to duplicate it for the type.  */
12058       fp->name = fieldname;
12059
12060       /* Change accessibility for artificial fields (e.g. virtual table
12061          pointer or virtual base class pointer) to private.  */
12062       if (dwarf2_attr (die, DW_AT_artificial, cu))
12063         {
12064           FIELD_ARTIFICIAL (*fp) = 1;
12065           new_field->accessibility = DW_ACCESS_private;
12066           fip->non_public_fields = 1;
12067         }
12068     }
12069   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
12070     {
12071       /* C++ static member.  */
12072
12073       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
12074          is a declaration, but all versions of G++ as of this writing
12075          (so through at least 3.2.1) incorrectly generate
12076          DW_TAG_variable tags.  */
12077
12078       const char *physname;
12079
12080       /* Get name of field.  */
12081       fieldname = dwarf2_name (die, cu);
12082       if (fieldname == NULL)
12083         return;
12084
12085       attr = dwarf2_attr (die, DW_AT_const_value, cu);
12086       if (attr
12087           /* Only create a symbol if this is an external value.
12088              new_symbol checks this and puts the value in the global symbol
12089              table, which we want.  If it is not external, new_symbol
12090              will try to put the value in cu->list_in_scope which is wrong.  */
12091           && dwarf2_flag_true_p (die, DW_AT_external, cu))
12092         {
12093           /* A static const member, not much different than an enum as far as
12094              we're concerned, except that we can support more types.  */
12095           new_symbol (die, NULL, cu);
12096         }
12097
12098       /* Get physical name.  */
12099       physname = dwarf2_physname (fieldname, die, cu);
12100
12101       /* The name is already allocated along with this objfile, so we don't
12102          need to duplicate it for the type.  */
12103       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
12104       FIELD_TYPE (*fp) = die_type (die, cu);
12105       FIELD_NAME (*fp) = fieldname;
12106     }
12107   else if (die->tag == DW_TAG_inheritance)
12108     {
12109       LONGEST offset;
12110
12111       /* C++ base class field.  */
12112       if (handle_data_member_location (die, cu, &offset))
12113         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12114       FIELD_BITSIZE (*fp) = 0;
12115       FIELD_TYPE (*fp) = die_type (die, cu);
12116       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
12117       fip->nbaseclasses++;
12118     }
12119 }
12120
12121 /* Add a typedef defined in the scope of the FIP's class.  */
12122
12123 static void
12124 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
12125                     struct dwarf2_cu *cu)
12126 {
12127   struct objfile *objfile = cu->objfile;
12128   struct typedef_field_list *new_field;
12129   struct attribute *attr;
12130   struct typedef_field *fp;
12131   char *fieldname = "";
12132
12133   /* Allocate a new field list entry and link it in.  */
12134   new_field = xzalloc (sizeof (*new_field));
12135   make_cleanup (xfree, new_field);
12136
12137   gdb_assert (die->tag == DW_TAG_typedef);
12138
12139   fp = &new_field->field;
12140
12141   /* Get name of field.  */
12142   fp->name = dwarf2_name (die, cu);
12143   if (fp->name == NULL)
12144     return;
12145
12146   fp->type = read_type_die (die, cu);
12147
12148   new_field->next = fip->typedef_field_list;
12149   fip->typedef_field_list = new_field;
12150   fip->typedef_field_list_count++;
12151 }
12152
12153 /* Create the vector of fields, and attach it to the type.  */
12154
12155 static void
12156 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
12157                               struct dwarf2_cu *cu)
12158 {
12159   int nfields = fip->nfields;
12160
12161   /* Record the field count, allocate space for the array of fields,
12162      and create blank accessibility bitfields if necessary.  */
12163   TYPE_NFIELDS (type) = nfields;
12164   TYPE_FIELDS (type) = (struct field *)
12165     TYPE_ALLOC (type, sizeof (struct field) * nfields);
12166   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
12167
12168   if (fip->non_public_fields && cu->language != language_ada)
12169     {
12170       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12171
12172       TYPE_FIELD_PRIVATE_BITS (type) =
12173         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12174       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
12175
12176       TYPE_FIELD_PROTECTED_BITS (type) =
12177         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12178       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
12179
12180       TYPE_FIELD_IGNORE_BITS (type) =
12181         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
12182       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
12183     }
12184
12185   /* If the type has baseclasses, allocate and clear a bit vector for
12186      TYPE_FIELD_VIRTUAL_BITS.  */
12187   if (fip->nbaseclasses && cu->language != language_ada)
12188     {
12189       int num_bytes = B_BYTES (fip->nbaseclasses);
12190       unsigned char *pointer;
12191
12192       ALLOCATE_CPLUS_STRUCT_TYPE (type);
12193       pointer = TYPE_ALLOC (type, num_bytes);
12194       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
12195       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
12196       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
12197     }
12198
12199   /* Copy the saved-up fields into the field vector.  Start from the head of
12200      the list, adding to the tail of the field array, so that they end up in
12201      the same order in the array in which they were added to the list.  */
12202   while (nfields-- > 0)
12203     {
12204       struct nextfield *fieldp;
12205
12206       if (fip->fields)
12207         {
12208           fieldp = fip->fields;
12209           fip->fields = fieldp->next;
12210         }
12211       else
12212         {
12213           fieldp = fip->baseclasses;
12214           fip->baseclasses = fieldp->next;
12215         }
12216
12217       TYPE_FIELD (type, nfields) = fieldp->field;
12218       switch (fieldp->accessibility)
12219         {
12220         case DW_ACCESS_private:
12221           if (cu->language != language_ada)
12222             SET_TYPE_FIELD_PRIVATE (type, nfields);
12223           break;
12224
12225         case DW_ACCESS_protected:
12226           if (cu->language != language_ada)
12227             SET_TYPE_FIELD_PROTECTED (type, nfields);
12228           break;
12229
12230         case DW_ACCESS_public:
12231           break;
12232
12233         default:
12234           /* Unknown accessibility.  Complain and treat it as public.  */
12235           {
12236             complaint (&symfile_complaints, _("unsupported accessibility %d"),
12237                        fieldp->accessibility);
12238           }
12239           break;
12240         }
12241       if (nfields < fip->nbaseclasses)
12242         {
12243           switch (fieldp->virtuality)
12244             {
12245             case DW_VIRTUALITY_virtual:
12246             case DW_VIRTUALITY_pure_virtual:
12247               if (cu->language == language_ada)
12248                 error (_("unexpected virtuality in component of Ada type"));
12249               SET_TYPE_FIELD_VIRTUAL (type, nfields);
12250               break;
12251             }
12252         }
12253     }
12254 }
12255
12256 /* Return true if this member function is a constructor, false
12257    otherwise.  */
12258
12259 static int
12260 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
12261 {
12262   const char *fieldname;
12263   const char *typename;
12264   int len;
12265
12266   if (die->parent == NULL)
12267     return 0;
12268
12269   if (die->parent->tag != DW_TAG_structure_type
12270       && die->parent->tag != DW_TAG_union_type
12271       && die->parent->tag != DW_TAG_class_type)
12272     return 0;
12273
12274   fieldname = dwarf2_name (die, cu);
12275   typename = dwarf2_name (die->parent, cu);
12276   if (fieldname == NULL || typename == NULL)
12277     return 0;
12278
12279   len = strlen (fieldname);
12280   return (strncmp (fieldname, typename, len) == 0
12281           && (typename[len] == '\0' || typename[len] == '<'));
12282 }
12283
12284 /* Add a member function to the proper fieldlist.  */
12285
12286 static void
12287 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
12288                       struct type *type, struct dwarf2_cu *cu)
12289 {
12290   struct objfile *objfile = cu->objfile;
12291   struct attribute *attr;
12292   struct fnfieldlist *flp;
12293   int i;
12294   struct fn_field *fnp;
12295   const char *fieldname;
12296   struct nextfnfield *new_fnfield;
12297   struct type *this_type;
12298   enum dwarf_access_attribute accessibility;
12299
12300   if (cu->language == language_ada)
12301     error (_("unexpected member function in Ada type"));
12302
12303   /* Get name of member function.  */
12304   fieldname = dwarf2_name (die, cu);
12305   if (fieldname == NULL)
12306     return;
12307
12308   /* Look up member function name in fieldlist.  */
12309   for (i = 0; i < fip->nfnfields; i++)
12310     {
12311       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
12312         break;
12313     }
12314
12315   /* Create new list element if necessary.  */
12316   if (i < fip->nfnfields)
12317     flp = &fip->fnfieldlists[i];
12318   else
12319     {
12320       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
12321         {
12322           fip->fnfieldlists = (struct fnfieldlist *)
12323             xrealloc (fip->fnfieldlists,
12324                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
12325                       * sizeof (struct fnfieldlist));
12326           if (fip->nfnfields == 0)
12327             make_cleanup (free_current_contents, &fip->fnfieldlists);
12328         }
12329       flp = &fip->fnfieldlists[fip->nfnfields];
12330       flp->name = fieldname;
12331       flp->length = 0;
12332       flp->head = NULL;
12333       i = fip->nfnfields++;
12334     }
12335
12336   /* Create a new member function field and chain it to the field list
12337      entry.  */
12338   new_fnfield = (struct nextfnfield *) xmalloc (sizeof (struct nextfnfield));
12339   make_cleanup (xfree, new_fnfield);
12340   memset (new_fnfield, 0, sizeof (struct nextfnfield));
12341   new_fnfield->next = flp->head;
12342   flp->head = new_fnfield;
12343   flp->length++;
12344
12345   /* Fill in the member function field info.  */
12346   fnp = &new_fnfield->fnfield;
12347
12348   /* Delay processing of the physname until later.  */
12349   if (cu->language == language_cplus || cu->language == language_java)
12350     {
12351       add_to_method_list (type, i, flp->length - 1, fieldname,
12352                           die, cu);
12353     }
12354   else
12355     {
12356       const char *physname = dwarf2_physname (fieldname, die, cu);
12357       fnp->physname = physname ? physname : "";
12358     }
12359
12360   fnp->type = alloc_type (objfile);
12361   this_type = read_type_die (die, cu);
12362   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
12363     {
12364       int nparams = TYPE_NFIELDS (this_type);
12365
12366       /* TYPE is the domain of this method, and THIS_TYPE is the type
12367            of the method itself (TYPE_CODE_METHOD).  */
12368       smash_to_method_type (fnp->type, type,
12369                             TYPE_TARGET_TYPE (this_type),
12370                             TYPE_FIELDS (this_type),
12371                             TYPE_NFIELDS (this_type),
12372                             TYPE_VARARGS (this_type));
12373
12374       /* Handle static member functions.
12375          Dwarf2 has no clean way to discern C++ static and non-static
12376          member functions.  G++ helps GDB by marking the first
12377          parameter for non-static member functions (which is the this
12378          pointer) as artificial.  We obtain this information from
12379          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
12380       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
12381         fnp->voffset = VOFFSET_STATIC;
12382     }
12383   else
12384     complaint (&symfile_complaints, _("member function type missing for '%s'"),
12385                dwarf2_full_name (fieldname, die, cu));
12386
12387   /* Get fcontext from DW_AT_containing_type if present.  */
12388   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12389     fnp->fcontext = die_containing_type (die, cu);
12390
12391   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
12392      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
12393
12394   /* Get accessibility.  */
12395   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12396   if (attr)
12397     accessibility = DW_UNSND (attr);
12398   else
12399     accessibility = dwarf2_default_access_attribute (die, cu);
12400   switch (accessibility)
12401     {
12402     case DW_ACCESS_private:
12403       fnp->is_private = 1;
12404       break;
12405     case DW_ACCESS_protected:
12406       fnp->is_protected = 1;
12407       break;
12408     }
12409
12410   /* Check for artificial methods.  */
12411   attr = dwarf2_attr (die, DW_AT_artificial, cu);
12412   if (attr && DW_UNSND (attr) != 0)
12413     fnp->is_artificial = 1;
12414
12415   fnp->is_constructor = dwarf2_is_constructor (die, cu);
12416
12417   /* Get index in virtual function table if it is a virtual member
12418      function.  For older versions of GCC, this is an offset in the
12419      appropriate virtual table, as specified by DW_AT_containing_type.
12420      For everyone else, it is an expression to be evaluated relative
12421      to the object address.  */
12422
12423   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
12424   if (attr)
12425     {
12426       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
12427         {
12428           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
12429             {
12430               /* Old-style GCC.  */
12431               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
12432             }
12433           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
12434                    || (DW_BLOCK (attr)->size > 1
12435                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
12436                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
12437             {
12438               struct dwarf_block blk;
12439               int offset;
12440
12441               offset = (DW_BLOCK (attr)->data[0] == DW_OP_deref
12442                         ? 1 : 2);
12443               blk.size = DW_BLOCK (attr)->size - offset;
12444               blk.data = DW_BLOCK (attr)->data + offset;
12445               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
12446               if ((fnp->voffset % cu->header.addr_size) != 0)
12447                 dwarf2_complex_location_expr_complaint ();
12448               else
12449                 fnp->voffset /= cu->header.addr_size;
12450               fnp->voffset += 2;
12451             }
12452           else
12453             dwarf2_complex_location_expr_complaint ();
12454
12455           if (!fnp->fcontext)
12456             fnp->fcontext = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
12457         }
12458       else if (attr_form_is_section_offset (attr))
12459         {
12460           dwarf2_complex_location_expr_complaint ();
12461         }
12462       else
12463         {
12464           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
12465                                                  fieldname);
12466         }
12467     }
12468   else
12469     {
12470       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12471       if (attr && DW_UNSND (attr))
12472         {
12473           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
12474           complaint (&symfile_complaints,
12475                      _("Member function \"%s\" (offset %d) is virtual "
12476                        "but the vtable offset is not specified"),
12477                      fieldname, die->offset.sect_off);
12478           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12479           TYPE_CPLUS_DYNAMIC (type) = 1;
12480         }
12481     }
12482 }
12483
12484 /* Create the vector of member function fields, and attach it to the type.  */
12485
12486 static void
12487 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
12488                                  struct dwarf2_cu *cu)
12489 {
12490   struct fnfieldlist *flp;
12491   int i;
12492
12493   if (cu->language == language_ada)
12494     error (_("unexpected member functions in Ada type"));
12495
12496   ALLOCATE_CPLUS_STRUCT_TYPE (type);
12497   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
12498     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
12499
12500   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
12501     {
12502       struct nextfnfield *nfp = flp->head;
12503       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
12504       int k;
12505
12506       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
12507       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
12508       fn_flp->fn_fields = (struct fn_field *)
12509         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
12510       for (k = flp->length; (k--, nfp); nfp = nfp->next)
12511         fn_flp->fn_fields[k] = nfp->fnfield;
12512     }
12513
12514   TYPE_NFN_FIELDS (type) = fip->nfnfields;
12515 }
12516
12517 /* Returns non-zero if NAME is the name of a vtable member in CU's
12518    language, zero otherwise.  */
12519 static int
12520 is_vtable_name (const char *name, struct dwarf2_cu *cu)
12521 {
12522   static const char vptr[] = "_vptr";
12523   static const char vtable[] = "vtable";
12524
12525   /* Look for the C++ and Java forms of the vtable.  */
12526   if ((cu->language == language_java
12527        && strncmp (name, vtable, sizeof (vtable) - 1) == 0)
12528        || (strncmp (name, vptr, sizeof (vptr) - 1) == 0
12529        && is_cplus_marker (name[sizeof (vptr) - 1])))
12530     return 1;
12531
12532   return 0;
12533 }
12534
12535 /* GCC outputs unnamed structures that are really pointers to member
12536    functions, with the ABI-specified layout.  If TYPE describes
12537    such a structure, smash it into a member function type.
12538
12539    GCC shouldn't do this; it should just output pointer to member DIEs.
12540    This is GCC PR debug/28767.  */
12541
12542 static void
12543 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
12544 {
12545   struct type *pfn_type, *domain_type, *new_type;
12546
12547   /* Check for a structure with no name and two children.  */
12548   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
12549     return;
12550
12551   /* Check for __pfn and __delta members.  */
12552   if (TYPE_FIELD_NAME (type, 0) == NULL
12553       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
12554       || TYPE_FIELD_NAME (type, 1) == NULL
12555       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
12556     return;
12557
12558   /* Find the type of the method.  */
12559   pfn_type = TYPE_FIELD_TYPE (type, 0);
12560   if (pfn_type == NULL
12561       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
12562       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
12563     return;
12564
12565   /* Look for the "this" argument.  */
12566   pfn_type = TYPE_TARGET_TYPE (pfn_type);
12567   if (TYPE_NFIELDS (pfn_type) == 0
12568       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
12569       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
12570     return;
12571
12572   domain_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
12573   new_type = alloc_type (objfile);
12574   smash_to_method_type (new_type, domain_type, TYPE_TARGET_TYPE (pfn_type),
12575                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
12576                         TYPE_VARARGS (pfn_type));
12577   smash_to_methodptr_type (type, new_type);
12578 }
12579
12580 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
12581    (icc).  */
12582
12583 static int
12584 producer_is_icc (struct dwarf2_cu *cu)
12585 {
12586   if (!cu->checked_producer)
12587     check_producer (cu);
12588
12589   return cu->producer_is_icc;
12590 }
12591
12592 /* Called when we find the DIE that starts a structure or union scope
12593    (definition) to create a type for the structure or union.  Fill in
12594    the type's name and general properties; the members will not be
12595    processed until process_structure_scope.
12596
12597    NOTE: we need to call these functions regardless of whether or not the
12598    DIE has a DW_AT_name attribute, since it might be an anonymous
12599    structure or union.  This gets the type entered into our set of
12600    user defined types.
12601
12602    However, if the structure is incomplete (an opaque struct/union)
12603    then suppress creating a symbol table entry for it since gdb only
12604    wants to find the one with the complete definition.  Note that if
12605    it is complete, we just call new_symbol, which does it's own
12606    checking about whether the struct/union is anonymous or not (and
12607    suppresses creating a symbol table entry itself).  */
12608
12609 static struct type *
12610 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
12611 {
12612   struct objfile *objfile = cu->objfile;
12613   struct type *type;
12614   struct attribute *attr;
12615   const char *name;
12616
12617   /* If the definition of this type lives in .debug_types, read that type.
12618      Don't follow DW_AT_specification though, that will take us back up
12619      the chain and we want to go down.  */
12620   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12621   if (attr)
12622     {
12623       type = get_DW_AT_signature_type (die, attr, cu);
12624
12625       /* The type's CU may not be the same as CU.
12626          Ensure TYPE is recorded with CU in die_type_hash.  */
12627       return set_die_type (die, type, cu);
12628     }
12629
12630   type = alloc_type (objfile);
12631   INIT_CPLUS_SPECIFIC (type);
12632
12633   name = dwarf2_name (die, cu);
12634   if (name != NULL)
12635     {
12636       if (cu->language == language_cplus
12637           || cu->language == language_java)
12638         {
12639           const char *full_name = dwarf2_full_name (name, die, cu);
12640
12641           /* dwarf2_full_name might have already finished building the DIE's
12642              type.  If so, there is no need to continue.  */
12643           if (get_die_type (die, cu) != NULL)
12644             return get_die_type (die, cu);
12645
12646           TYPE_TAG_NAME (type) = full_name;
12647           if (die->tag == DW_TAG_structure_type
12648               || die->tag == DW_TAG_class_type)
12649             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12650         }
12651       else
12652         {
12653           /* The name is already allocated along with this objfile, so
12654              we don't need to duplicate it for the type.  */
12655           TYPE_TAG_NAME (type) = name;
12656           if (die->tag == DW_TAG_class_type)
12657             TYPE_NAME (type) = TYPE_TAG_NAME (type);
12658         }
12659     }
12660
12661   if (die->tag == DW_TAG_structure_type)
12662     {
12663       TYPE_CODE (type) = TYPE_CODE_STRUCT;
12664     }
12665   else if (die->tag == DW_TAG_union_type)
12666     {
12667       TYPE_CODE (type) = TYPE_CODE_UNION;
12668     }
12669   else
12670     {
12671       TYPE_CODE (type) = TYPE_CODE_CLASS;
12672     }
12673
12674   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
12675     TYPE_DECLARED_CLASS (type) = 1;
12676
12677   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12678   if (attr)
12679     {
12680       TYPE_LENGTH (type) = DW_UNSND (attr);
12681     }
12682   else
12683     {
12684       TYPE_LENGTH (type) = 0;
12685     }
12686
12687   if (producer_is_icc (cu))
12688     {
12689       /* ICC does not output the required DW_AT_declaration
12690          on incomplete types, but gives them a size of zero.  */
12691     }
12692   else
12693     TYPE_STUB_SUPPORTED (type) = 1;
12694
12695   if (die_is_declaration (die, cu))
12696     TYPE_STUB (type) = 1;
12697   else if (attr == NULL && die->child == NULL
12698            && producer_is_realview (cu->producer))
12699     /* RealView does not output the required DW_AT_declaration
12700        on incomplete types.  */
12701     TYPE_STUB (type) = 1;
12702
12703   /* We need to add the type field to the die immediately so we don't
12704      infinitely recurse when dealing with pointers to the structure
12705      type within the structure itself.  */
12706   set_die_type (die, type, cu);
12707
12708   /* set_die_type should be already done.  */
12709   set_descriptive_type (type, die, cu);
12710
12711   return type;
12712 }
12713
12714 /* Finish creating a structure or union type, including filling in
12715    its members and creating a symbol for it.  */
12716
12717 static void
12718 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
12719 {
12720   struct objfile *objfile = cu->objfile;
12721   struct die_info *child_die = die->child;
12722   struct type *type;
12723
12724   type = get_die_type (die, cu);
12725   if (type == NULL)
12726     type = read_structure_type (die, cu);
12727
12728   if (die->child != NULL && ! die_is_declaration (die, cu))
12729     {
12730       struct field_info fi;
12731       struct die_info *child_die;
12732       VEC (symbolp) *template_args = NULL;
12733       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
12734
12735       memset (&fi, 0, sizeof (struct field_info));
12736
12737       child_die = die->child;
12738
12739       while (child_die && child_die->tag)
12740         {
12741           if (child_die->tag == DW_TAG_member
12742               || child_die->tag == DW_TAG_variable)
12743             {
12744               /* NOTE: carlton/2002-11-05: A C++ static data member
12745                  should be a DW_TAG_member that is a declaration, but
12746                  all versions of G++ as of this writing (so through at
12747                  least 3.2.1) incorrectly generate DW_TAG_variable
12748                  tags for them instead.  */
12749               dwarf2_add_field (&fi, child_die, cu);
12750             }
12751           else if (child_die->tag == DW_TAG_subprogram)
12752             {
12753               /* C++ member function.  */
12754               dwarf2_add_member_fn (&fi, child_die, type, cu);
12755             }
12756           else if (child_die->tag == DW_TAG_inheritance)
12757             {
12758               /* C++ base class field.  */
12759               dwarf2_add_field (&fi, child_die, cu);
12760             }
12761           else if (child_die->tag == DW_TAG_typedef)
12762             dwarf2_add_typedef (&fi, child_die, cu);
12763           else if (child_die->tag == DW_TAG_template_type_param
12764                    || child_die->tag == DW_TAG_template_value_param)
12765             {
12766               struct symbol *arg = new_symbol (child_die, NULL, cu);
12767
12768               if (arg != NULL)
12769                 VEC_safe_push (symbolp, template_args, arg);
12770             }
12771
12772           child_die = sibling_die (child_die);
12773         }
12774
12775       /* Attach template arguments to type.  */
12776       if (! VEC_empty (symbolp, template_args))
12777         {
12778           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12779           TYPE_N_TEMPLATE_ARGUMENTS (type)
12780             = VEC_length (symbolp, template_args);
12781           TYPE_TEMPLATE_ARGUMENTS (type)
12782             = obstack_alloc (&objfile->objfile_obstack,
12783                              (TYPE_N_TEMPLATE_ARGUMENTS (type)
12784                               * sizeof (struct symbol *)));
12785           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
12786                   VEC_address (symbolp, template_args),
12787                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
12788                    * sizeof (struct symbol *)));
12789           VEC_free (symbolp, template_args);
12790         }
12791
12792       /* Attach fields and member functions to the type.  */
12793       if (fi.nfields)
12794         dwarf2_attach_fields_to_type (&fi, type, cu);
12795       if (fi.nfnfields)
12796         {
12797           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
12798
12799           /* Get the type which refers to the base class (possibly this
12800              class itself) which contains the vtable pointer for the current
12801              class from the DW_AT_containing_type attribute.  This use of
12802              DW_AT_containing_type is a GNU extension.  */
12803
12804           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
12805             {
12806               struct type *t = die_containing_type (die, cu);
12807
12808               TYPE_VPTR_BASETYPE (type) = t;
12809               if (type == t)
12810                 {
12811                   int i;
12812
12813                   /* Our own class provides vtbl ptr.  */
12814                   for (i = TYPE_NFIELDS (t) - 1;
12815                        i >= TYPE_N_BASECLASSES (t);
12816                        --i)
12817                     {
12818                       const char *fieldname = TYPE_FIELD_NAME (t, i);
12819
12820                       if (is_vtable_name (fieldname, cu))
12821                         {
12822                           TYPE_VPTR_FIELDNO (type) = i;
12823                           break;
12824                         }
12825                     }
12826
12827                   /* Complain if virtual function table field not found.  */
12828                   if (i < TYPE_N_BASECLASSES (t))
12829                     complaint (&symfile_complaints,
12830                                _("virtual function table pointer "
12831                                  "not found when defining class '%s'"),
12832                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
12833                                "");
12834                 }
12835               else
12836                 {
12837                   TYPE_VPTR_FIELDNO (type) = TYPE_VPTR_FIELDNO (t);
12838                 }
12839             }
12840           else if (cu->producer
12841                    && strncmp (cu->producer,
12842                                "IBM(R) XL C/C++ Advanced Edition", 32) == 0)
12843             {
12844               /* The IBM XLC compiler does not provide direct indication
12845                  of the containing type, but the vtable pointer is
12846                  always named __vfp.  */
12847
12848               int i;
12849
12850               for (i = TYPE_NFIELDS (type) - 1;
12851                    i >= TYPE_N_BASECLASSES (type);
12852                    --i)
12853                 {
12854                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
12855                     {
12856                       TYPE_VPTR_FIELDNO (type) = i;
12857                       TYPE_VPTR_BASETYPE (type) = type;
12858                       break;
12859                     }
12860                 }
12861             }
12862         }
12863
12864       /* Copy fi.typedef_field_list linked list elements content into the
12865          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
12866       if (fi.typedef_field_list)
12867         {
12868           int i = fi.typedef_field_list_count;
12869
12870           ALLOCATE_CPLUS_STRUCT_TYPE (type);
12871           TYPE_TYPEDEF_FIELD_ARRAY (type)
12872             = TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i);
12873           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
12874
12875           /* Reverse the list order to keep the debug info elements order.  */
12876           while (--i >= 0)
12877             {
12878               struct typedef_field *dest, *src;
12879
12880               dest = &TYPE_TYPEDEF_FIELD (type, i);
12881               src = &fi.typedef_field_list->field;
12882               fi.typedef_field_list = fi.typedef_field_list->next;
12883               *dest = *src;
12884             }
12885         }
12886
12887       do_cleanups (back_to);
12888
12889       if (HAVE_CPLUS_STRUCT (type))
12890         TYPE_CPLUS_REALLY_JAVA (type) = cu->language == language_java;
12891     }
12892
12893   quirk_gcc_member_function_pointer (type, objfile);
12894
12895   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
12896      snapshots) has been known to create a die giving a declaration
12897      for a class that has, as a child, a die giving a definition for a
12898      nested class.  So we have to process our children even if the
12899      current die is a declaration.  Normally, of course, a declaration
12900      won't have any children at all.  */
12901
12902   while (child_die != NULL && child_die->tag)
12903     {
12904       if (child_die->tag == DW_TAG_member
12905           || child_die->tag == DW_TAG_variable
12906           || child_die->tag == DW_TAG_inheritance
12907           || child_die->tag == DW_TAG_template_value_param
12908           || child_die->tag == DW_TAG_template_type_param)
12909         {
12910           /* Do nothing.  */
12911         }
12912       else
12913         process_die (child_die, cu);
12914
12915       child_die = sibling_die (child_die);
12916     }
12917
12918   /* Do not consider external references.  According to the DWARF standard,
12919      these DIEs are identified by the fact that they have no byte_size
12920      attribute, and a declaration attribute.  */
12921   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
12922       || !die_is_declaration (die, cu))
12923     new_symbol (die, type, cu);
12924 }
12925
12926 /* Given a DW_AT_enumeration_type die, set its type.  We do not
12927    complete the type's fields yet, or create any symbols.  */
12928
12929 static struct type *
12930 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
12931 {
12932   struct objfile *objfile = cu->objfile;
12933   struct type *type;
12934   struct attribute *attr;
12935   const char *name;
12936
12937   /* If the definition of this type lives in .debug_types, read that type.
12938      Don't follow DW_AT_specification though, that will take us back up
12939      the chain and we want to go down.  */
12940   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
12941   if (attr)
12942     {
12943       type = get_DW_AT_signature_type (die, attr, cu);
12944
12945       /* The type's CU may not be the same as CU.
12946          Ensure TYPE is recorded with CU in die_type_hash.  */
12947       return set_die_type (die, type, cu);
12948     }
12949
12950   type = alloc_type (objfile);
12951
12952   TYPE_CODE (type) = TYPE_CODE_ENUM;
12953   name = dwarf2_full_name (NULL, die, cu);
12954   if (name != NULL)
12955     TYPE_TAG_NAME (type) = name;
12956
12957   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12958   if (attr)
12959     {
12960       TYPE_LENGTH (type) = DW_UNSND (attr);
12961     }
12962   else
12963     {
12964       TYPE_LENGTH (type) = 0;
12965     }
12966
12967   /* The enumeration DIE can be incomplete.  In Ada, any type can be
12968      declared as private in the package spec, and then defined only
12969      inside the package body.  Such types are known as Taft Amendment
12970      Types.  When another package uses such a type, an incomplete DIE
12971      may be generated by the compiler.  */
12972   if (die_is_declaration (die, cu))
12973     TYPE_STUB (type) = 1;
12974
12975   return set_die_type (die, type, cu);
12976 }
12977
12978 /* Given a pointer to a die which begins an enumeration, process all
12979    the dies that define the members of the enumeration, and create the
12980    symbol for the enumeration type.
12981
12982    NOTE: We reverse the order of the element list.  */
12983
12984 static void
12985 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
12986 {
12987   struct type *this_type;
12988
12989   this_type = get_die_type (die, cu);
12990   if (this_type == NULL)
12991     this_type = read_enumeration_type (die, cu);
12992
12993   if (die->child != NULL)
12994     {
12995       struct die_info *child_die;
12996       struct symbol *sym;
12997       struct field *fields = NULL;
12998       int num_fields = 0;
12999       int unsigned_enum = 1;
13000       const char *name;
13001       int flag_enum = 1;
13002       ULONGEST mask = 0;
13003
13004       child_die = die->child;
13005       while (child_die && child_die->tag)
13006         {
13007           if (child_die->tag != DW_TAG_enumerator)
13008             {
13009               process_die (child_die, cu);
13010             }
13011           else
13012             {
13013               name = dwarf2_name (child_die, cu);
13014               if (name)
13015                 {
13016                   sym = new_symbol (child_die, this_type, cu);
13017                   if (SYMBOL_VALUE (sym) < 0)
13018                     {
13019                       unsigned_enum = 0;
13020                       flag_enum = 0;
13021                     }
13022                   else if ((mask & SYMBOL_VALUE (sym)) != 0)
13023                     flag_enum = 0;
13024                   else
13025                     mask |= SYMBOL_VALUE (sym);
13026
13027                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
13028                     {
13029                       fields = (struct field *)
13030                         xrealloc (fields,
13031                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
13032                                   * sizeof (struct field));
13033                     }
13034
13035                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
13036                   FIELD_TYPE (fields[num_fields]) = NULL;
13037                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
13038                   FIELD_BITSIZE (fields[num_fields]) = 0;
13039
13040                   num_fields++;
13041                 }
13042             }
13043
13044           child_die = sibling_die (child_die);
13045         }
13046
13047       if (num_fields)
13048         {
13049           TYPE_NFIELDS (this_type) = num_fields;
13050           TYPE_FIELDS (this_type) = (struct field *)
13051             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
13052           memcpy (TYPE_FIELDS (this_type), fields,
13053                   sizeof (struct field) * num_fields);
13054           xfree (fields);
13055         }
13056       if (unsigned_enum)
13057         TYPE_UNSIGNED (this_type) = 1;
13058       if (flag_enum)
13059         TYPE_FLAG_ENUM (this_type) = 1;
13060     }
13061
13062   /* If we are reading an enum from a .debug_types unit, and the enum
13063      is a declaration, and the enum is not the signatured type in the
13064      unit, then we do not want to add a symbol for it.  Adding a
13065      symbol would in some cases obscure the true definition of the
13066      enum, giving users an incomplete type when the definition is
13067      actually available.  Note that we do not want to do this for all
13068      enums which are just declarations, because C++0x allows forward
13069      enum declarations.  */
13070   if (cu->per_cu->is_debug_types
13071       && die_is_declaration (die, cu))
13072     {
13073       struct signatured_type *sig_type;
13074
13075       sig_type = (struct signatured_type *) cu->per_cu;
13076       gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
13077       if (sig_type->type_offset_in_section.sect_off != die->offset.sect_off)
13078         return;
13079     }
13080
13081   new_symbol (die, this_type, cu);
13082 }
13083
13084 /* Extract all information from a DW_TAG_array_type DIE and put it in
13085    the DIE's type field.  For now, this only handles one dimensional
13086    arrays.  */
13087
13088 static struct type *
13089 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
13090 {
13091   struct objfile *objfile = cu->objfile;
13092   struct die_info *child_die;
13093   struct type *type;
13094   struct type *element_type, *range_type, *index_type;
13095   struct type **range_types = NULL;
13096   struct attribute *attr;
13097   int ndim = 0;
13098   struct cleanup *back_to;
13099   const char *name;
13100
13101   element_type = die_type (die, cu);
13102
13103   /* The die_type call above may have already set the type for this DIE.  */
13104   type = get_die_type (die, cu);
13105   if (type)
13106     return type;
13107
13108   /* Irix 6.2 native cc creates array types without children for
13109      arrays with unspecified length.  */
13110   if (die->child == NULL)
13111     {
13112       index_type = objfile_type (objfile)->builtin_int;
13113       range_type = create_range_type (NULL, index_type, 0, -1);
13114       type = create_array_type (NULL, element_type, range_type);
13115       return set_die_type (die, type, cu);
13116     }
13117
13118   back_to = make_cleanup (null_cleanup, NULL);
13119   child_die = die->child;
13120   while (child_die && child_die->tag)
13121     {
13122       if (child_die->tag == DW_TAG_subrange_type)
13123         {
13124           struct type *child_type = read_type_die (child_die, cu);
13125
13126           if (child_type != NULL)
13127             {
13128               /* The range type was succesfully read.  Save it for the
13129                  array type creation.  */
13130               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
13131                 {
13132                   range_types = (struct type **)
13133                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
13134                               * sizeof (struct type *));
13135                   if (ndim == 0)
13136                     make_cleanup (free_current_contents, &range_types);
13137                 }
13138               range_types[ndim++] = child_type;
13139             }
13140         }
13141       child_die = sibling_die (child_die);
13142     }
13143
13144   /* Dwarf2 dimensions are output from left to right, create the
13145      necessary array types in backwards order.  */
13146
13147   type = element_type;
13148
13149   if (read_array_order (die, cu) == DW_ORD_col_major)
13150     {
13151       int i = 0;
13152
13153       while (i < ndim)
13154         type = create_array_type (NULL, type, range_types[i++]);
13155     }
13156   else
13157     {
13158       while (ndim-- > 0)
13159         type = create_array_type (NULL, type, range_types[ndim]);
13160     }
13161
13162   /* Understand Dwarf2 support for vector types (like they occur on
13163      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
13164      array type.  This is not part of the Dwarf2/3 standard yet, but a
13165      custom vendor extension.  The main difference between a regular
13166      array and the vector variant is that vectors are passed by value
13167      to functions.  */
13168   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
13169   if (attr)
13170     make_vector_type (type);
13171
13172   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
13173      implementation may choose to implement triple vectors using this
13174      attribute.  */
13175   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13176   if (attr)
13177     {
13178       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
13179         TYPE_LENGTH (type) = DW_UNSND (attr);
13180       else
13181         complaint (&symfile_complaints,
13182                    _("DW_AT_byte_size for array type smaller "
13183                      "than the total size of elements"));
13184     }
13185
13186   name = dwarf2_name (die, cu);
13187   if (name)
13188     TYPE_NAME (type) = name;
13189
13190   /* Install the type in the die.  */
13191   set_die_type (die, type, cu);
13192
13193   /* set_die_type should be already done.  */
13194   set_descriptive_type (type, die, cu);
13195
13196   do_cleanups (back_to);
13197
13198   return type;
13199 }
13200
13201 static enum dwarf_array_dim_ordering
13202 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
13203 {
13204   struct attribute *attr;
13205
13206   attr = dwarf2_attr (die, DW_AT_ordering, cu);
13207
13208   if (attr) return DW_SND (attr);
13209
13210   /* GNU F77 is a special case, as at 08/2004 array type info is the
13211      opposite order to the dwarf2 specification, but data is still
13212      laid out as per normal fortran.
13213
13214      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
13215      version checking.  */
13216
13217   if (cu->language == language_fortran
13218       && cu->producer && strstr (cu->producer, "GNU F77"))
13219     {
13220       return DW_ORD_row_major;
13221     }
13222
13223   switch (cu->language_defn->la_array_ordering)
13224     {
13225     case array_column_major:
13226       return DW_ORD_col_major;
13227     case array_row_major:
13228     default:
13229       return DW_ORD_row_major;
13230     };
13231 }
13232
13233 /* Extract all information from a DW_TAG_set_type DIE and put it in
13234    the DIE's type field.  */
13235
13236 static struct type *
13237 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
13238 {
13239   struct type *domain_type, *set_type;
13240   struct attribute *attr;
13241
13242   domain_type = die_type (die, cu);
13243
13244   /* The die_type call above may have already set the type for this DIE.  */
13245   set_type = get_die_type (die, cu);
13246   if (set_type)
13247     return set_type;
13248
13249   set_type = create_set_type (NULL, domain_type);
13250
13251   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13252   if (attr)
13253     TYPE_LENGTH (set_type) = DW_UNSND (attr);
13254
13255   return set_die_type (die, set_type, cu);
13256 }
13257
13258 /* A helper for read_common_block that creates a locexpr baton.
13259    SYM is the symbol which we are marking as computed.
13260    COMMON_DIE is the DIE for the common block.
13261    COMMON_LOC is the location expression attribute for the common
13262    block itself.
13263    MEMBER_LOC is the location expression attribute for the particular
13264    member of the common block that we are processing.
13265    CU is the CU from which the above come.  */
13266
13267 static void
13268 mark_common_block_symbol_computed (struct symbol *sym,
13269                                    struct die_info *common_die,
13270                                    struct attribute *common_loc,
13271                                    struct attribute *member_loc,
13272                                    struct dwarf2_cu *cu)
13273 {
13274   struct objfile *objfile = dwarf2_per_objfile->objfile;
13275   struct dwarf2_locexpr_baton *baton;
13276   gdb_byte *ptr;
13277   unsigned int cu_off;
13278   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
13279   LONGEST offset = 0;
13280
13281   gdb_assert (common_loc && member_loc);
13282   gdb_assert (attr_form_is_block (common_loc));
13283   gdb_assert (attr_form_is_block (member_loc)
13284               || attr_form_is_constant (member_loc));
13285
13286   baton = obstack_alloc (&objfile->objfile_obstack,
13287                          sizeof (struct dwarf2_locexpr_baton));
13288   baton->per_cu = cu->per_cu;
13289   gdb_assert (baton->per_cu);
13290
13291   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
13292
13293   if (attr_form_is_constant (member_loc))
13294     {
13295       offset = dwarf2_get_attr_constant_value (member_loc, 0);
13296       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
13297     }
13298   else
13299     baton->size += DW_BLOCK (member_loc)->size;
13300
13301   ptr = obstack_alloc (&objfile->objfile_obstack, baton->size);
13302   baton->data = ptr;
13303
13304   *ptr++ = DW_OP_call4;
13305   cu_off = common_die->offset.sect_off - cu->per_cu->offset.sect_off;
13306   store_unsigned_integer (ptr, 4, byte_order, cu_off);
13307   ptr += 4;
13308
13309   if (attr_form_is_constant (member_loc))
13310     {
13311       *ptr++ = DW_OP_addr;
13312       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
13313       ptr += cu->header.addr_size;
13314     }
13315   else
13316     {
13317       /* We have to copy the data here, because DW_OP_call4 will only
13318          use a DW_AT_location attribute.  */
13319       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
13320       ptr += DW_BLOCK (member_loc)->size;
13321     }
13322
13323   *ptr++ = DW_OP_plus;
13324   gdb_assert (ptr - baton->data == baton->size);
13325
13326   SYMBOL_LOCATION_BATON (sym) = baton;
13327   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
13328 }
13329
13330 /* Create appropriate locally-scoped variables for all the
13331    DW_TAG_common_block entries.  Also create a struct common_block
13332    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
13333    is used to sepate the common blocks name namespace from regular
13334    variable names.  */
13335
13336 static void
13337 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
13338 {
13339   struct attribute *attr;
13340
13341   attr = dwarf2_attr (die, DW_AT_location, cu);
13342   if (attr)
13343     {
13344       /* Support the .debug_loc offsets.  */
13345       if (attr_form_is_block (attr))
13346         {
13347           /* Ok.  */
13348         }
13349       else if (attr_form_is_section_offset (attr))
13350         {
13351           dwarf2_complex_location_expr_complaint ();
13352           attr = NULL;
13353         }
13354       else
13355         {
13356           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
13357                                                  "common block member");
13358           attr = NULL;
13359         }
13360     }
13361
13362   if (die->child != NULL)
13363     {
13364       struct objfile *objfile = cu->objfile;
13365       struct die_info *child_die;
13366       size_t n_entries = 0, size;
13367       struct common_block *common_block;
13368       struct symbol *sym;
13369
13370       for (child_die = die->child;
13371            child_die && child_die->tag;
13372            child_die = sibling_die (child_die))
13373         ++n_entries;
13374
13375       size = (sizeof (struct common_block)
13376               + (n_entries - 1) * sizeof (struct symbol *));
13377       common_block = obstack_alloc (&objfile->objfile_obstack, size);
13378       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
13379       common_block->n_entries = 0;
13380
13381       for (child_die = die->child;
13382            child_die && child_die->tag;
13383            child_die = sibling_die (child_die))
13384         {
13385           /* Create the symbol in the DW_TAG_common_block block in the current
13386              symbol scope.  */
13387           sym = new_symbol (child_die, NULL, cu);
13388           if (sym != NULL)
13389             {
13390               struct attribute *member_loc;
13391
13392               common_block->contents[common_block->n_entries++] = sym;
13393
13394               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
13395                                         cu);
13396               if (member_loc)
13397                 {
13398                   /* GDB has handled this for a long time, but it is
13399                      not specified by DWARF.  It seems to have been
13400                      emitted by gfortran at least as recently as:
13401                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
13402                   complaint (&symfile_complaints,
13403                              _("Variable in common block has "
13404                                "DW_AT_data_member_location "
13405                                "- DIE at 0x%x [in module %s]"),
13406                              child_die->offset.sect_off,
13407                              objfile_name (cu->objfile));
13408
13409                   if (attr_form_is_section_offset (member_loc))
13410                     dwarf2_complex_location_expr_complaint ();
13411                   else if (attr_form_is_constant (member_loc)
13412                            || attr_form_is_block (member_loc))
13413                     {
13414                       if (attr)
13415                         mark_common_block_symbol_computed (sym, die, attr,
13416                                                            member_loc, cu);
13417                     }
13418                   else
13419                     dwarf2_complex_location_expr_complaint ();
13420                 }
13421             }
13422         }
13423
13424       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
13425       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
13426     }
13427 }
13428
13429 /* Create a type for a C++ namespace.  */
13430
13431 static struct type *
13432 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
13433 {
13434   struct objfile *objfile = cu->objfile;
13435   const char *previous_prefix, *name;
13436   int is_anonymous;
13437   struct type *type;
13438
13439   /* For extensions, reuse the type of the original namespace.  */
13440   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
13441     {
13442       struct die_info *ext_die;
13443       struct dwarf2_cu *ext_cu = cu;
13444
13445       ext_die = dwarf2_extension (die, &ext_cu);
13446       type = read_type_die (ext_die, ext_cu);
13447
13448       /* EXT_CU may not be the same as CU.
13449          Ensure TYPE is recorded with CU in die_type_hash.  */
13450       return set_die_type (die, type, cu);
13451     }
13452
13453   name = namespace_name (die, &is_anonymous, cu);
13454
13455   /* Now build the name of the current namespace.  */
13456
13457   previous_prefix = determine_prefix (die, cu);
13458   if (previous_prefix[0] != '\0')
13459     name = typename_concat (&objfile->objfile_obstack,
13460                             previous_prefix, name, 0, cu);
13461
13462   /* Create the type.  */
13463   type = init_type (TYPE_CODE_NAMESPACE, 0, 0, NULL,
13464                     objfile);
13465   TYPE_NAME (type) = name;
13466   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13467
13468   return set_die_type (die, type, cu);
13469 }
13470
13471 /* Read a C++ namespace.  */
13472
13473 static void
13474 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
13475 {
13476   struct objfile *objfile = cu->objfile;
13477   int is_anonymous;
13478
13479   /* Add a symbol associated to this if we haven't seen the namespace
13480      before.  Also, add a using directive if it's an anonymous
13481      namespace.  */
13482
13483   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
13484     {
13485       struct type *type;
13486
13487       type = read_type_die (die, cu);
13488       new_symbol (die, type, cu);
13489
13490       namespace_name (die, &is_anonymous, cu);
13491       if (is_anonymous)
13492         {
13493           const char *previous_prefix = determine_prefix (die, cu);
13494
13495           cp_add_using_directive (previous_prefix, TYPE_NAME (type), NULL,
13496                                   NULL, NULL, 0, &objfile->objfile_obstack);
13497         }
13498     }
13499
13500   if (die->child != NULL)
13501     {
13502       struct die_info *child_die = die->child;
13503
13504       while (child_die && child_die->tag)
13505         {
13506           process_die (child_die, cu);
13507           child_die = sibling_die (child_die);
13508         }
13509     }
13510 }
13511
13512 /* Read a Fortran module as type.  This DIE can be only a declaration used for
13513    imported module.  Still we need that type as local Fortran "use ... only"
13514    declaration imports depend on the created type in determine_prefix.  */
13515
13516 static struct type *
13517 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
13518 {
13519   struct objfile *objfile = cu->objfile;
13520   const char *module_name;
13521   struct type *type;
13522
13523   module_name = dwarf2_name (die, cu);
13524   if (!module_name)
13525     complaint (&symfile_complaints,
13526                _("DW_TAG_module has no name, offset 0x%x"),
13527                die->offset.sect_off);
13528   type = init_type (TYPE_CODE_MODULE, 0, 0, module_name, objfile);
13529
13530   /* determine_prefix uses TYPE_TAG_NAME.  */
13531   TYPE_TAG_NAME (type) = TYPE_NAME (type);
13532
13533   return set_die_type (die, type, cu);
13534 }
13535
13536 /* Read a Fortran module.  */
13537
13538 static void
13539 read_module (struct die_info *die, struct dwarf2_cu *cu)
13540 {
13541   struct die_info *child_die = die->child;
13542
13543   while (child_die && child_die->tag)
13544     {
13545       process_die (child_die, cu);
13546       child_die = sibling_die (child_die);
13547     }
13548 }
13549
13550 /* Return the name of the namespace represented by DIE.  Set
13551    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
13552    namespace.  */
13553
13554 static const char *
13555 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
13556 {
13557   struct die_info *current_die;
13558   const char *name = NULL;
13559
13560   /* Loop through the extensions until we find a name.  */
13561
13562   for (current_die = die;
13563        current_die != NULL;
13564        current_die = dwarf2_extension (die, &cu))
13565     {
13566       name = dwarf2_name (current_die, cu);
13567       if (name != NULL)
13568         break;
13569     }
13570
13571   /* Is it an anonymous namespace?  */
13572
13573   *is_anonymous = (name == NULL);
13574   if (*is_anonymous)
13575     name = CP_ANONYMOUS_NAMESPACE_STR;
13576
13577   return name;
13578 }
13579
13580 /* Extract all information from a DW_TAG_pointer_type DIE and add to
13581    the user defined type vector.  */
13582
13583 static struct type *
13584 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
13585 {
13586   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
13587   struct comp_unit_head *cu_header = &cu->header;
13588   struct type *type;
13589   struct attribute *attr_byte_size;
13590   struct attribute *attr_address_class;
13591   int byte_size, addr_class;
13592   struct type *target_type;
13593
13594   target_type = die_type (die, cu);
13595
13596   /* The die_type call above may have already set the type for this DIE.  */
13597   type = get_die_type (die, cu);
13598   if (type)
13599     return type;
13600
13601   type = lookup_pointer_type (target_type);
13602
13603   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
13604   if (attr_byte_size)
13605     byte_size = DW_UNSND (attr_byte_size);
13606   else
13607     byte_size = cu_header->addr_size;
13608
13609   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
13610   if (attr_address_class)
13611     addr_class = DW_UNSND (attr_address_class);
13612   else
13613     addr_class = DW_ADDR_none;
13614
13615   /* If the pointer size or address class is different than the
13616      default, create a type variant marked as such and set the
13617      length accordingly.  */
13618   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
13619     {
13620       if (gdbarch_address_class_type_flags_p (gdbarch))
13621         {
13622           int type_flags;
13623
13624           type_flags = gdbarch_address_class_type_flags
13625                          (gdbarch, byte_size, addr_class);
13626           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
13627                       == 0);
13628           type = make_type_with_address_space (type, type_flags);
13629         }
13630       else if (TYPE_LENGTH (type) != byte_size)
13631         {
13632           complaint (&symfile_complaints,
13633                      _("invalid pointer size %d"), byte_size);
13634         }
13635       else
13636         {
13637           /* Should we also complain about unhandled address classes?  */
13638         }
13639     }
13640
13641   TYPE_LENGTH (type) = byte_size;
13642   return set_die_type (die, type, cu);
13643 }
13644
13645 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
13646    the user defined type vector.  */
13647
13648 static struct type *
13649 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
13650 {
13651   struct type *type;
13652   struct type *to_type;
13653   struct type *domain;
13654
13655   to_type = die_type (die, cu);
13656   domain = die_containing_type (die, cu);
13657
13658   /* The calls above may have already set the type for this DIE.  */
13659   type = get_die_type (die, cu);
13660   if (type)
13661     return type;
13662
13663   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
13664     type = lookup_methodptr_type (to_type);
13665   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
13666     {
13667       struct type *new_type = alloc_type (cu->objfile);
13668
13669       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
13670                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
13671                             TYPE_VARARGS (to_type));
13672       type = lookup_methodptr_type (new_type);
13673     }
13674   else
13675     type = lookup_memberptr_type (to_type, domain);
13676
13677   return set_die_type (die, type, cu);
13678 }
13679
13680 /* Extract all information from a DW_TAG_reference_type DIE and add to
13681    the user defined type vector.  */
13682
13683 static struct type *
13684 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu)
13685 {
13686   struct comp_unit_head *cu_header = &cu->header;
13687   struct type *type, *target_type;
13688   struct attribute *attr;
13689
13690   target_type = die_type (die, cu);
13691
13692   /* The die_type call above may have already set the type for this DIE.  */
13693   type = get_die_type (die, cu);
13694   if (type)
13695     return type;
13696
13697   type = lookup_reference_type (target_type);
13698   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13699   if (attr)
13700     {
13701       TYPE_LENGTH (type) = DW_UNSND (attr);
13702     }
13703   else
13704     {
13705       TYPE_LENGTH (type) = cu_header->addr_size;
13706     }
13707   return set_die_type (die, type, cu);
13708 }
13709
13710 static struct type *
13711 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
13712 {
13713   struct type *base_type, *cv_type;
13714
13715   base_type = die_type (die, cu);
13716
13717   /* The die_type call above may have already set the type for this DIE.  */
13718   cv_type = get_die_type (die, cu);
13719   if (cv_type)
13720     return cv_type;
13721
13722   /* In case the const qualifier is applied to an array type, the element type
13723      is so qualified, not the array type (section 6.7.3 of C99).  */
13724   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
13725     {
13726       struct type *el_type, *inner_array;
13727
13728       base_type = copy_type (base_type);
13729       inner_array = base_type;
13730
13731       while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
13732         {
13733           TYPE_TARGET_TYPE (inner_array) =
13734             copy_type (TYPE_TARGET_TYPE (inner_array));
13735           inner_array = TYPE_TARGET_TYPE (inner_array);
13736         }
13737
13738       el_type = TYPE_TARGET_TYPE (inner_array);
13739       TYPE_TARGET_TYPE (inner_array) =
13740         make_cv_type (1, TYPE_VOLATILE (el_type), el_type, NULL);
13741
13742       return set_die_type (die, base_type, cu);
13743     }
13744
13745   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
13746   return set_die_type (die, cv_type, cu);
13747 }
13748
13749 static struct type *
13750 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
13751 {
13752   struct type *base_type, *cv_type;
13753
13754   base_type = die_type (die, cu);
13755
13756   /* The die_type call above may have already set the type for this DIE.  */
13757   cv_type = get_die_type (die, cu);
13758   if (cv_type)
13759     return cv_type;
13760
13761   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
13762   return set_die_type (die, cv_type, cu);
13763 }
13764
13765 /* Handle DW_TAG_restrict_type.  */
13766
13767 static struct type *
13768 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
13769 {
13770   struct type *base_type, *cv_type;
13771
13772   base_type = die_type (die, cu);
13773
13774   /* The die_type call above may have already set the type for this DIE.  */
13775   cv_type = get_die_type (die, cu);
13776   if (cv_type)
13777     return cv_type;
13778
13779   cv_type = make_restrict_type (base_type);
13780   return set_die_type (die, cv_type, cu);
13781 }
13782
13783 /* Extract all information from a DW_TAG_string_type DIE and add to
13784    the user defined type vector.  It isn't really a user defined type,
13785    but it behaves like one, with other DIE's using an AT_user_def_type
13786    attribute to reference it.  */
13787
13788 static struct type *
13789 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
13790 {
13791   struct objfile *objfile = cu->objfile;
13792   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13793   struct type *type, *range_type, *index_type, *char_type;
13794   struct attribute *attr;
13795   unsigned int length;
13796
13797   attr = dwarf2_attr (die, DW_AT_string_length, cu);
13798   if (attr)
13799     {
13800       length = DW_UNSND (attr);
13801     }
13802   else
13803     {
13804       /* Check for the DW_AT_byte_size attribute.  */
13805       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13806       if (attr)
13807         {
13808           length = DW_UNSND (attr);
13809         }
13810       else
13811         {
13812           length = 1;
13813         }
13814     }
13815
13816   index_type = objfile_type (objfile)->builtin_int;
13817   range_type = create_range_type (NULL, index_type, 1, length);
13818   char_type = language_string_char_type (cu->language_defn, gdbarch);
13819   type = create_string_type (NULL, char_type, range_type);
13820
13821   return set_die_type (die, type, cu);
13822 }
13823
13824 /* Assuming that DIE corresponds to a function, returns nonzero
13825    if the function is prototyped.  */
13826
13827 static int
13828 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
13829 {
13830   struct attribute *attr;
13831
13832   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
13833   if (attr && (DW_UNSND (attr) != 0))
13834     return 1;
13835
13836   /* The DWARF standard implies that the DW_AT_prototyped attribute
13837      is only meaninful for C, but the concept also extends to other
13838      languages that allow unprototyped functions (Eg: Objective C).
13839      For all other languages, assume that functions are always
13840      prototyped.  */
13841   if (cu->language != language_c
13842       && cu->language != language_objc
13843       && cu->language != language_opencl)
13844     return 1;
13845
13846   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
13847      prototyped and unprototyped functions; default to prototyped,
13848      since that is more common in modern code (and RealView warns
13849      about unprototyped functions).  */
13850   if (producer_is_realview (cu->producer))
13851     return 1;
13852
13853   return 0;
13854 }
13855
13856 /* Handle DIES due to C code like:
13857
13858    struct foo
13859    {
13860    int (*funcp)(int a, long l);
13861    int b;
13862    };
13863
13864    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
13865
13866 static struct type *
13867 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
13868 {
13869   struct objfile *objfile = cu->objfile;
13870   struct type *type;            /* Type that this function returns.  */
13871   struct type *ftype;           /* Function that returns above type.  */
13872   struct attribute *attr;
13873
13874   type = die_type (die, cu);
13875
13876   /* The die_type call above may have already set the type for this DIE.  */
13877   ftype = get_die_type (die, cu);
13878   if (ftype)
13879     return ftype;
13880
13881   ftype = lookup_function_type (type);
13882
13883   if (prototyped_function_p (die, cu))
13884     TYPE_PROTOTYPED (ftype) = 1;
13885
13886   /* Store the calling convention in the type if it's available in
13887      the subroutine die.  Otherwise set the calling convention to
13888      the default value DW_CC_normal.  */
13889   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
13890   if (attr)
13891     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
13892   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
13893     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
13894   else
13895     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
13896
13897   /* We need to add the subroutine type to the die immediately so
13898      we don't infinitely recurse when dealing with parameters
13899      declared as the same subroutine type.  */
13900   set_die_type (die, ftype, cu);
13901
13902   if (die->child != NULL)
13903     {
13904       struct type *void_type = objfile_type (objfile)->builtin_void;
13905       struct die_info *child_die;
13906       int nparams, iparams;
13907
13908       /* Count the number of parameters.
13909          FIXME: GDB currently ignores vararg functions, but knows about
13910          vararg member functions.  */
13911       nparams = 0;
13912       child_die = die->child;
13913       while (child_die && child_die->tag)
13914         {
13915           if (child_die->tag == DW_TAG_formal_parameter)
13916             nparams++;
13917           else if (child_die->tag == DW_TAG_unspecified_parameters)
13918             TYPE_VARARGS (ftype) = 1;
13919           child_die = sibling_die (child_die);
13920         }
13921
13922       /* Allocate storage for parameters and fill them in.  */
13923       TYPE_NFIELDS (ftype) = nparams;
13924       TYPE_FIELDS (ftype) = (struct field *)
13925         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
13926
13927       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
13928          even if we error out during the parameters reading below.  */
13929       for (iparams = 0; iparams < nparams; iparams++)
13930         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
13931
13932       iparams = 0;
13933       child_die = die->child;
13934       while (child_die && child_die->tag)
13935         {
13936           if (child_die->tag == DW_TAG_formal_parameter)
13937             {
13938               struct type *arg_type;
13939
13940               /* DWARF version 2 has no clean way to discern C++
13941                  static and non-static member functions.  G++ helps
13942                  GDB by marking the first parameter for non-static
13943                  member functions (which is the this pointer) as
13944                  artificial.  We pass this information to
13945                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
13946
13947                  DWARF version 3 added DW_AT_object_pointer, which GCC
13948                  4.5 does not yet generate.  */
13949               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
13950               if (attr)
13951                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
13952               else
13953                 {
13954                   TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
13955
13956                   /* GCC/43521: In java, the formal parameter
13957                      "this" is sometimes not marked with DW_AT_artificial.  */
13958                   if (cu->language == language_java)
13959                     {
13960                       const char *name = dwarf2_name (child_die, cu);
13961
13962                       if (name && !strcmp (name, "this"))
13963                         TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 1;
13964                     }
13965                 }
13966               arg_type = die_type (child_die, cu);
13967
13968               /* RealView does not mark THIS as const, which the testsuite
13969                  expects.  GCC marks THIS as const in method definitions,
13970                  but not in the class specifications (GCC PR 43053).  */
13971               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
13972                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
13973                 {
13974                   int is_this = 0;
13975                   struct dwarf2_cu *arg_cu = cu;
13976                   const char *name = dwarf2_name (child_die, cu);
13977
13978                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
13979                   if (attr)
13980                     {
13981                       /* If the compiler emits this, use it.  */
13982                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
13983                         is_this = 1;
13984                     }
13985                   else if (name && strcmp (name, "this") == 0)
13986                     /* Function definitions will have the argument names.  */
13987                     is_this = 1;
13988                   else if (name == NULL && iparams == 0)
13989                     /* Declarations may not have the names, so like
13990                        elsewhere in GDB, assume an artificial first
13991                        argument is "this".  */
13992                     is_this = 1;
13993
13994                   if (is_this)
13995                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
13996                                              arg_type, 0);
13997                 }
13998
13999               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
14000               iparams++;
14001             }
14002           child_die = sibling_die (child_die);
14003         }
14004     }
14005
14006   return ftype;
14007 }
14008
14009 static struct type *
14010 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
14011 {
14012   struct objfile *objfile = cu->objfile;
14013   const char *name = NULL;
14014   struct type *this_type, *target_type;
14015
14016   name = dwarf2_full_name (NULL, die, cu);
14017   this_type = init_type (TYPE_CODE_TYPEDEF, 0,
14018                          TYPE_FLAG_TARGET_STUB, NULL, objfile);
14019   TYPE_NAME (this_type) = name;
14020   set_die_type (die, this_type, cu);
14021   target_type = die_type (die, cu);
14022   if (target_type != this_type)
14023     TYPE_TARGET_TYPE (this_type) = target_type;
14024   else
14025     {
14026       /* Self-referential typedefs are, it seems, not allowed by the DWARF
14027          spec and cause infinite loops in GDB.  */
14028       complaint (&symfile_complaints,
14029                  _("Self-referential DW_TAG_typedef "
14030                    "- DIE at 0x%x [in module %s]"),
14031                  die->offset.sect_off, objfile_name (objfile));
14032       TYPE_TARGET_TYPE (this_type) = NULL;
14033     }
14034   return this_type;
14035 }
14036
14037 /* Find a representation of a given base type and install
14038    it in the TYPE field of the die.  */
14039
14040 static struct type *
14041 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
14042 {
14043   struct objfile *objfile = cu->objfile;
14044   struct type *type;
14045   struct attribute *attr;
14046   int encoding = 0, size = 0;
14047   const char *name;
14048   enum type_code code = TYPE_CODE_INT;
14049   int type_flags = 0;
14050   struct type *target_type = NULL;
14051
14052   attr = dwarf2_attr (die, DW_AT_encoding, cu);
14053   if (attr)
14054     {
14055       encoding = DW_UNSND (attr);
14056     }
14057   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14058   if (attr)
14059     {
14060       size = DW_UNSND (attr);
14061     }
14062   name = dwarf2_name (die, cu);
14063   if (!name)
14064     {
14065       complaint (&symfile_complaints,
14066                  _("DW_AT_name missing from DW_TAG_base_type"));
14067     }
14068
14069   switch (encoding)
14070     {
14071       case DW_ATE_address:
14072         /* Turn DW_ATE_address into a void * pointer.  */
14073         code = TYPE_CODE_PTR;
14074         type_flags |= TYPE_FLAG_UNSIGNED;
14075         target_type = init_type (TYPE_CODE_VOID, 1, 0, NULL, objfile);
14076         break;
14077       case DW_ATE_boolean:
14078         code = TYPE_CODE_BOOL;
14079         type_flags |= TYPE_FLAG_UNSIGNED;
14080         break;
14081       case DW_ATE_complex_float:
14082         code = TYPE_CODE_COMPLEX;
14083         target_type = init_type (TYPE_CODE_FLT, size / 2, 0, NULL, objfile);
14084         break;
14085       case DW_ATE_decimal_float:
14086         code = TYPE_CODE_DECFLOAT;
14087         break;
14088       case DW_ATE_float:
14089         code = TYPE_CODE_FLT;
14090         break;
14091       case DW_ATE_signed:
14092         break;
14093       case DW_ATE_unsigned:
14094         type_flags |= TYPE_FLAG_UNSIGNED;
14095         if (cu->language == language_fortran
14096             && name
14097             && strncmp (name, "character(", sizeof ("character(") - 1) == 0)
14098           code = TYPE_CODE_CHAR;
14099         break;
14100       case DW_ATE_signed_char:
14101         if (cu->language == language_ada || cu->language == language_m2
14102             || cu->language == language_pascal
14103             || cu->language == language_fortran)
14104           code = TYPE_CODE_CHAR;
14105         break;
14106       case DW_ATE_unsigned_char:
14107         if (cu->language == language_ada || cu->language == language_m2
14108             || cu->language == language_pascal
14109             || cu->language == language_fortran)
14110           code = TYPE_CODE_CHAR;
14111         type_flags |= TYPE_FLAG_UNSIGNED;
14112         break;
14113       case DW_ATE_UTF:
14114         /* We just treat this as an integer and then recognize the
14115            type by name elsewhere.  */
14116         break;
14117
14118       default:
14119         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
14120                    dwarf_type_encoding_name (encoding));
14121         break;
14122     }
14123
14124   type = init_type (code, size, type_flags, NULL, objfile);
14125   TYPE_NAME (type) = name;
14126   TYPE_TARGET_TYPE (type) = target_type;
14127
14128   if (name && strcmp (name, "char") == 0)
14129     TYPE_NOSIGN (type) = 1;
14130
14131   return set_die_type (die, type, cu);
14132 }
14133
14134 /* Read the given DW_AT_subrange DIE.  */
14135
14136 static struct type *
14137 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
14138 {
14139   struct type *base_type, *orig_base_type;
14140   struct type *range_type;
14141   struct attribute *attr;
14142   LONGEST low, high;
14143   int low_default_is_valid;
14144   const char *name;
14145   LONGEST negative_mask;
14146
14147   orig_base_type = die_type (die, cu);
14148   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
14149      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
14150      creating the range type, but we use the result of check_typedef
14151      when examining properties of the type.  */
14152   base_type = check_typedef (orig_base_type);
14153
14154   /* The die_type call above may have already set the type for this DIE.  */
14155   range_type = get_die_type (die, cu);
14156   if (range_type)
14157     return range_type;
14158
14159   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
14160      omitting DW_AT_lower_bound.  */
14161   switch (cu->language)
14162     {
14163     case language_c:
14164     case language_cplus:
14165       low = 0;
14166       low_default_is_valid = 1;
14167       break;
14168     case language_fortran:
14169       low = 1;
14170       low_default_is_valid = 1;
14171       break;
14172     case language_d:
14173     case language_java:
14174     case language_objc:
14175       low = 0;
14176       low_default_is_valid = (cu->header.version >= 4);
14177       break;
14178     case language_ada:
14179     case language_m2:
14180     case language_pascal:
14181       low = 1;
14182       low_default_is_valid = (cu->header.version >= 4);
14183       break;
14184     default:
14185       low = 0;
14186       low_default_is_valid = 0;
14187       break;
14188     }
14189
14190   /* FIXME: For variable sized arrays either of these could be
14191      a variable rather than a constant value.  We'll allow it,
14192      but we don't know how to handle it.  */
14193   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
14194   if (attr)
14195     low = dwarf2_get_attr_constant_value (attr, low);
14196   else if (!low_default_is_valid)
14197     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
14198                                       "- DIE at 0x%x [in module %s]"),
14199                die->offset.sect_off, objfile_name (cu->objfile));
14200
14201   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
14202   if (attr)
14203     {
14204       if (attr_form_is_block (attr) || attr_form_is_ref (attr))
14205         {
14206           /* GCC encodes arrays with unspecified or dynamic length
14207              with a DW_FORM_block1 attribute or a reference attribute.
14208              FIXME: GDB does not yet know how to handle dynamic
14209              arrays properly, treat them as arrays with unspecified
14210              length for now.
14211
14212              FIXME: jimb/2003-09-22: GDB does not really know
14213              how to handle arrays of unspecified length
14214              either; we just represent them as zero-length
14215              arrays.  Choose an appropriate upper bound given
14216              the lower bound we've computed above.  */
14217           high = low - 1;
14218         }
14219       else
14220         high = dwarf2_get_attr_constant_value (attr, 1);
14221     }
14222   else
14223     {
14224       attr = dwarf2_attr (die, DW_AT_count, cu);
14225       if (attr)
14226         {
14227           int count = dwarf2_get_attr_constant_value (attr, 1);
14228           high = low + count - 1;
14229         }
14230       else
14231         {
14232           /* Unspecified array length.  */
14233           high = low - 1;
14234         }
14235     }
14236
14237   /* Dwarf-2 specifications explicitly allows to create subrange types
14238      without specifying a base type.
14239      In that case, the base type must be set to the type of
14240      the lower bound, upper bound or count, in that order, if any of these
14241      three attributes references an object that has a type.
14242      If no base type is found, the Dwarf-2 specifications say that
14243      a signed integer type of size equal to the size of an address should
14244      be used.
14245      For the following C code: `extern char gdb_int [];'
14246      GCC produces an empty range DIE.
14247      FIXME: muller/2010-05-28: Possible references to object for low bound,
14248      high bound or count are not yet handled by this code.  */
14249   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
14250     {
14251       struct objfile *objfile = cu->objfile;
14252       struct gdbarch *gdbarch = get_objfile_arch (objfile);
14253       int addr_size = gdbarch_addr_bit (gdbarch) /8;
14254       struct type *int_type = objfile_type (objfile)->builtin_int;
14255
14256       /* Test "int", "long int", and "long long int" objfile types,
14257          and select the first one having a size above or equal to the
14258          architecture address size.  */
14259       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14260         base_type = int_type;
14261       else
14262         {
14263           int_type = objfile_type (objfile)->builtin_long;
14264           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14265             base_type = int_type;
14266           else
14267             {
14268               int_type = objfile_type (objfile)->builtin_long_long;
14269               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
14270                 base_type = int_type;
14271             }
14272         }
14273     }
14274
14275   negative_mask =
14276     (LONGEST) -1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1);
14277   if (!TYPE_UNSIGNED (base_type) && (low & negative_mask))
14278     low |= negative_mask;
14279   if (!TYPE_UNSIGNED (base_type) && (high & negative_mask))
14280     high |= negative_mask;
14281
14282   range_type = create_range_type (NULL, orig_base_type, low, high);
14283
14284   /* Mark arrays with dynamic length at least as an array of unspecified
14285      length.  GDB could check the boundary but before it gets implemented at
14286      least allow accessing the array elements.  */
14287   if (attr && attr_form_is_block (attr))
14288     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14289
14290   /* Ada expects an empty array on no boundary attributes.  */
14291   if (attr == NULL && cu->language != language_ada)
14292     TYPE_HIGH_BOUND_UNDEFINED (range_type) = 1;
14293
14294   name = dwarf2_name (die, cu);
14295   if (name)
14296     TYPE_NAME (range_type) = name;
14297
14298   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14299   if (attr)
14300     TYPE_LENGTH (range_type) = DW_UNSND (attr);
14301
14302   set_die_type (die, range_type, cu);
14303
14304   /* set_die_type should be already done.  */
14305   set_descriptive_type (range_type, die, cu);
14306
14307   return range_type;
14308 }
14309
14310 static struct type *
14311 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
14312 {
14313   struct type *type;
14314
14315   /* For now, we only support the C meaning of an unspecified type: void.  */
14316
14317   type = init_type (TYPE_CODE_VOID, 0, 0, NULL, cu->objfile);
14318   TYPE_NAME (type) = dwarf2_name (die, cu);
14319
14320   return set_die_type (die, type, cu);
14321 }
14322
14323 /* Read a single die and all its descendents.  Set the die's sibling
14324    field to NULL; set other fields in the die correctly, and set all
14325    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
14326    location of the info_ptr after reading all of those dies.  PARENT
14327    is the parent of the die in question.  */
14328
14329 static struct die_info *
14330 read_die_and_children (const struct die_reader_specs *reader,
14331                        const gdb_byte *info_ptr,
14332                        const gdb_byte **new_info_ptr,
14333                        struct die_info *parent)
14334 {
14335   struct die_info *die;
14336   const gdb_byte *cur_ptr;
14337   int has_children;
14338
14339   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
14340   if (die == NULL)
14341     {
14342       *new_info_ptr = cur_ptr;
14343       return NULL;
14344     }
14345   store_in_ref_table (die, reader->cu);
14346
14347   if (has_children)
14348     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
14349   else
14350     {
14351       die->child = NULL;
14352       *new_info_ptr = cur_ptr;
14353     }
14354
14355   die->sibling = NULL;
14356   die->parent = parent;
14357   return die;
14358 }
14359
14360 /* Read a die, all of its descendents, and all of its siblings; set
14361    all of the fields of all of the dies correctly.  Arguments are as
14362    in read_die_and_children.  */
14363
14364 static struct die_info *
14365 read_die_and_siblings_1 (const struct die_reader_specs *reader,
14366                          const gdb_byte *info_ptr,
14367                          const gdb_byte **new_info_ptr,
14368                          struct die_info *parent)
14369 {
14370   struct die_info *first_die, *last_sibling;
14371   const gdb_byte *cur_ptr;
14372
14373   cur_ptr = info_ptr;
14374   first_die = last_sibling = NULL;
14375
14376   while (1)
14377     {
14378       struct die_info *die
14379         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
14380
14381       if (die == NULL)
14382         {
14383           *new_info_ptr = cur_ptr;
14384           return first_die;
14385         }
14386
14387       if (!first_die)
14388         first_die = die;
14389       else
14390         last_sibling->sibling = die;
14391
14392       last_sibling = die;
14393     }
14394 }
14395
14396 /* Read a die, all of its descendents, and all of its siblings; set
14397    all of the fields of all of the dies correctly.  Arguments are as
14398    in read_die_and_children.
14399    This the main entry point for reading a DIE and all its children.  */
14400
14401 static struct die_info *
14402 read_die_and_siblings (const struct die_reader_specs *reader,
14403                        const gdb_byte *info_ptr,
14404                        const gdb_byte **new_info_ptr,
14405                        struct die_info *parent)
14406 {
14407   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
14408                                                   new_info_ptr, parent);
14409
14410   if (dwarf2_die_debug)
14411     {
14412       fprintf_unfiltered (gdb_stdlog,
14413                           "Read die from %s@0x%x of %s:\n",
14414                           get_section_name (reader->die_section),
14415                           (unsigned) (info_ptr - reader->die_section->buffer),
14416                           bfd_get_filename (reader->abfd));
14417       dump_die (die, dwarf2_die_debug);
14418     }
14419
14420   return die;
14421 }
14422
14423 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
14424    attributes.
14425    The caller is responsible for filling in the extra attributes
14426    and updating (*DIEP)->num_attrs.
14427    Set DIEP to point to a newly allocated die with its information,
14428    except for its child, sibling, and parent fields.
14429    Set HAS_CHILDREN to tell whether the die has children or not.  */
14430
14431 static const gdb_byte *
14432 read_full_die_1 (const struct die_reader_specs *reader,
14433                  struct die_info **diep, const gdb_byte *info_ptr,
14434                  int *has_children, int num_extra_attrs)
14435 {
14436   unsigned int abbrev_number, bytes_read, i;
14437   sect_offset offset;
14438   struct abbrev_info *abbrev;
14439   struct die_info *die;
14440   struct dwarf2_cu *cu = reader->cu;
14441   bfd *abfd = reader->abfd;
14442
14443   offset.sect_off = info_ptr - reader->buffer;
14444   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
14445   info_ptr += bytes_read;
14446   if (!abbrev_number)
14447     {
14448       *diep = NULL;
14449       *has_children = 0;
14450       return info_ptr;
14451     }
14452
14453   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
14454   if (!abbrev)
14455     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
14456            abbrev_number,
14457            bfd_get_filename (abfd));
14458
14459   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
14460   die->offset = offset;
14461   die->tag = abbrev->tag;
14462   die->abbrev = abbrev_number;
14463
14464   /* Make the result usable.
14465      The caller needs to update num_attrs after adding the extra
14466      attributes.  */
14467   die->num_attrs = abbrev->num_attrs;
14468
14469   for (i = 0; i < abbrev->num_attrs; ++i)
14470     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
14471                                info_ptr);
14472
14473   *diep = die;
14474   *has_children = abbrev->has_children;
14475   return info_ptr;
14476 }
14477
14478 /* Read a die and all its attributes.
14479    Set DIEP to point to a newly allocated die with its information,
14480    except for its child, sibling, and parent fields.
14481    Set HAS_CHILDREN to tell whether the die has children or not.  */
14482
14483 static const gdb_byte *
14484 read_full_die (const struct die_reader_specs *reader,
14485                struct die_info **diep, const gdb_byte *info_ptr,
14486                int *has_children)
14487 {
14488   const gdb_byte *result;
14489
14490   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
14491
14492   if (dwarf2_die_debug)
14493     {
14494       fprintf_unfiltered (gdb_stdlog,
14495                           "Read die from %s@0x%x of %s:\n",
14496                           get_section_name (reader->die_section),
14497                           (unsigned) (info_ptr - reader->die_section->buffer),
14498                           bfd_get_filename (reader->abfd));
14499       dump_die (*diep, dwarf2_die_debug);
14500     }
14501
14502   return result;
14503 }
14504 \f
14505 /* Abbreviation tables.
14506
14507    In DWARF version 2, the description of the debugging information is
14508    stored in a separate .debug_abbrev section.  Before we read any
14509    dies from a section we read in all abbreviations and install them
14510    in a hash table.  */
14511
14512 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
14513
14514 static struct abbrev_info *
14515 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
14516 {
14517   struct abbrev_info *abbrev;
14518
14519   abbrev = (struct abbrev_info *)
14520     obstack_alloc (&abbrev_table->abbrev_obstack, sizeof (struct abbrev_info));
14521   memset (abbrev, 0, sizeof (struct abbrev_info));
14522   return abbrev;
14523 }
14524
14525 /* Add an abbreviation to the table.  */
14526
14527 static void
14528 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
14529                          unsigned int abbrev_number,
14530                          struct abbrev_info *abbrev)
14531 {
14532   unsigned int hash_number;
14533
14534   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14535   abbrev->next = abbrev_table->abbrevs[hash_number];
14536   abbrev_table->abbrevs[hash_number] = abbrev;
14537 }
14538
14539 /* Look up an abbrev in the table.
14540    Returns NULL if the abbrev is not found.  */
14541
14542 static struct abbrev_info *
14543 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
14544                             unsigned int abbrev_number)
14545 {
14546   unsigned int hash_number;
14547   struct abbrev_info *abbrev;
14548
14549   hash_number = abbrev_number % ABBREV_HASH_SIZE;
14550   abbrev = abbrev_table->abbrevs[hash_number];
14551
14552   while (abbrev)
14553     {
14554       if (abbrev->number == abbrev_number)
14555         return abbrev;
14556       abbrev = abbrev->next;
14557     }
14558   return NULL;
14559 }
14560
14561 /* Read in an abbrev table.  */
14562
14563 static struct abbrev_table *
14564 abbrev_table_read_table (struct dwarf2_section_info *section,
14565                          sect_offset offset)
14566 {
14567   struct objfile *objfile = dwarf2_per_objfile->objfile;
14568   bfd *abfd = get_section_bfd_owner (section);
14569   struct abbrev_table *abbrev_table;
14570   const gdb_byte *abbrev_ptr;
14571   struct abbrev_info *cur_abbrev;
14572   unsigned int abbrev_number, bytes_read, abbrev_name;
14573   unsigned int abbrev_form;
14574   struct attr_abbrev *cur_attrs;
14575   unsigned int allocated_attrs;
14576
14577   abbrev_table = XMALLOC (struct abbrev_table);
14578   abbrev_table->offset = offset;
14579   obstack_init (&abbrev_table->abbrev_obstack);
14580   abbrev_table->abbrevs = obstack_alloc (&abbrev_table->abbrev_obstack,
14581                                          (ABBREV_HASH_SIZE
14582                                           * sizeof (struct abbrev_info *)));
14583   memset (abbrev_table->abbrevs, 0,
14584           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
14585
14586   dwarf2_read_section (objfile, section);
14587   abbrev_ptr = section->buffer + offset.sect_off;
14588   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14589   abbrev_ptr += bytes_read;
14590
14591   allocated_attrs = ATTR_ALLOC_CHUNK;
14592   cur_attrs = xmalloc (allocated_attrs * sizeof (struct attr_abbrev));
14593
14594   /* Loop until we reach an abbrev number of 0.  */
14595   while (abbrev_number)
14596     {
14597       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
14598
14599       /* read in abbrev header */
14600       cur_abbrev->number = abbrev_number;
14601       cur_abbrev->tag = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14602       abbrev_ptr += bytes_read;
14603       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
14604       abbrev_ptr += 1;
14605
14606       /* now read in declarations */
14607       abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14608       abbrev_ptr += bytes_read;
14609       abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14610       abbrev_ptr += bytes_read;
14611       while (abbrev_name)
14612         {
14613           if (cur_abbrev->num_attrs == allocated_attrs)
14614             {
14615               allocated_attrs += ATTR_ALLOC_CHUNK;
14616               cur_attrs
14617                 = xrealloc (cur_attrs, (allocated_attrs
14618                                         * sizeof (struct attr_abbrev)));
14619             }
14620
14621           cur_attrs[cur_abbrev->num_attrs].name = abbrev_name;
14622           cur_attrs[cur_abbrev->num_attrs++].form = abbrev_form;
14623           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14624           abbrev_ptr += bytes_read;
14625           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14626           abbrev_ptr += bytes_read;
14627         }
14628
14629       cur_abbrev->attrs = obstack_alloc (&abbrev_table->abbrev_obstack,
14630                                          (cur_abbrev->num_attrs
14631                                           * sizeof (struct attr_abbrev)));
14632       memcpy (cur_abbrev->attrs, cur_attrs,
14633               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
14634
14635       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
14636
14637       /* Get next abbreviation.
14638          Under Irix6 the abbreviations for a compilation unit are not
14639          always properly terminated with an abbrev number of 0.
14640          Exit loop if we encounter an abbreviation which we have
14641          already read (which means we are about to read the abbreviations
14642          for the next compile unit) or if the end of the abbreviation
14643          table is reached.  */
14644       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
14645         break;
14646       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
14647       abbrev_ptr += bytes_read;
14648       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
14649         break;
14650     }
14651
14652   xfree (cur_attrs);
14653   return abbrev_table;
14654 }
14655
14656 /* Free the resources held by ABBREV_TABLE.  */
14657
14658 static void
14659 abbrev_table_free (struct abbrev_table *abbrev_table)
14660 {
14661   obstack_free (&abbrev_table->abbrev_obstack, NULL);
14662   xfree (abbrev_table);
14663 }
14664
14665 /* Same as abbrev_table_free but as a cleanup.
14666    We pass in a pointer to the pointer to the table so that we can
14667    set the pointer to NULL when we're done.  It also simplifies
14668    build_type_unit_groups.  */
14669
14670 static void
14671 abbrev_table_free_cleanup (void *table_ptr)
14672 {
14673   struct abbrev_table **abbrev_table_ptr = table_ptr;
14674
14675   if (*abbrev_table_ptr != NULL)
14676     abbrev_table_free (*abbrev_table_ptr);
14677   *abbrev_table_ptr = NULL;
14678 }
14679
14680 /* Read the abbrev table for CU from ABBREV_SECTION.  */
14681
14682 static void
14683 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
14684                      struct dwarf2_section_info *abbrev_section)
14685 {
14686   cu->abbrev_table =
14687     abbrev_table_read_table (abbrev_section, cu->header.abbrev_offset);
14688 }
14689
14690 /* Release the memory used by the abbrev table for a compilation unit.  */
14691
14692 static void
14693 dwarf2_free_abbrev_table (void *ptr_to_cu)
14694 {
14695   struct dwarf2_cu *cu = ptr_to_cu;
14696
14697   if (cu->abbrev_table != NULL)
14698     abbrev_table_free (cu->abbrev_table);
14699   /* Set this to NULL so that we SEGV if we try to read it later,
14700      and also because free_comp_unit verifies this is NULL.  */
14701   cu->abbrev_table = NULL;
14702 }
14703 \f
14704 /* Returns nonzero if TAG represents a type that we might generate a partial
14705    symbol for.  */
14706
14707 static int
14708 is_type_tag_for_partial (int tag)
14709 {
14710   switch (tag)
14711     {
14712 #if 0
14713     /* Some types that would be reasonable to generate partial symbols for,
14714        that we don't at present.  */
14715     case DW_TAG_array_type:
14716     case DW_TAG_file_type:
14717     case DW_TAG_ptr_to_member_type:
14718     case DW_TAG_set_type:
14719     case DW_TAG_string_type:
14720     case DW_TAG_subroutine_type:
14721 #endif
14722     case DW_TAG_base_type:
14723     case DW_TAG_class_type:
14724     case DW_TAG_interface_type:
14725     case DW_TAG_enumeration_type:
14726     case DW_TAG_structure_type:
14727     case DW_TAG_subrange_type:
14728     case DW_TAG_typedef:
14729     case DW_TAG_union_type:
14730       return 1;
14731     default:
14732       return 0;
14733     }
14734 }
14735
14736 /* Load all DIEs that are interesting for partial symbols into memory.  */
14737
14738 static struct partial_die_info *
14739 load_partial_dies (const struct die_reader_specs *reader,
14740                    const gdb_byte *info_ptr, int building_psymtab)
14741 {
14742   struct dwarf2_cu *cu = reader->cu;
14743   struct objfile *objfile = cu->objfile;
14744   struct partial_die_info *part_die;
14745   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
14746   struct abbrev_info *abbrev;
14747   unsigned int bytes_read;
14748   unsigned int load_all = 0;
14749   int nesting_level = 1;
14750
14751   parent_die = NULL;
14752   last_die = NULL;
14753
14754   gdb_assert (cu->per_cu != NULL);
14755   if (cu->per_cu->load_all_dies)
14756     load_all = 1;
14757
14758   cu->partial_dies
14759     = htab_create_alloc_ex (cu->header.length / 12,
14760                             partial_die_hash,
14761                             partial_die_eq,
14762                             NULL,
14763                             &cu->comp_unit_obstack,
14764                             hashtab_obstack_allocate,
14765                             dummy_obstack_deallocate);
14766
14767   part_die = obstack_alloc (&cu->comp_unit_obstack,
14768                             sizeof (struct partial_die_info));
14769
14770   while (1)
14771     {
14772       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
14773
14774       /* A NULL abbrev means the end of a series of children.  */
14775       if (abbrev == NULL)
14776         {
14777           if (--nesting_level == 0)
14778             {
14779               /* PART_DIE was probably the last thing allocated on the
14780                  comp_unit_obstack, so we could call obstack_free
14781                  here.  We don't do that because the waste is small,
14782                  and will be cleaned up when we're done with this
14783                  compilation unit.  This way, we're also more robust
14784                  against other users of the comp_unit_obstack.  */
14785               return first_die;
14786             }
14787           info_ptr += bytes_read;
14788           last_die = parent_die;
14789           parent_die = parent_die->die_parent;
14790           continue;
14791         }
14792
14793       /* Check for template arguments.  We never save these; if
14794          they're seen, we just mark the parent, and go on our way.  */
14795       if (parent_die != NULL
14796           && cu->language == language_cplus
14797           && (abbrev->tag == DW_TAG_template_type_param
14798               || abbrev->tag == DW_TAG_template_value_param))
14799         {
14800           parent_die->has_template_arguments = 1;
14801
14802           if (!load_all)
14803             {
14804               /* We don't need a partial DIE for the template argument.  */
14805               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14806               continue;
14807             }
14808         }
14809
14810       /* We only recurse into c++ subprograms looking for template arguments.
14811          Skip their other children.  */
14812       if (!load_all
14813           && cu->language == language_cplus
14814           && parent_die != NULL
14815           && parent_die->tag == DW_TAG_subprogram)
14816         {
14817           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14818           continue;
14819         }
14820
14821       /* Check whether this DIE is interesting enough to save.  Normally
14822          we would not be interested in members here, but there may be
14823          later variables referencing them via DW_AT_specification (for
14824          static members).  */
14825       if (!load_all
14826           && !is_type_tag_for_partial (abbrev->tag)
14827           && abbrev->tag != DW_TAG_constant
14828           && abbrev->tag != DW_TAG_enumerator
14829           && abbrev->tag != DW_TAG_subprogram
14830           && abbrev->tag != DW_TAG_lexical_block
14831           && abbrev->tag != DW_TAG_variable
14832           && abbrev->tag != DW_TAG_namespace
14833           && abbrev->tag != DW_TAG_module
14834           && abbrev->tag != DW_TAG_member
14835           && abbrev->tag != DW_TAG_imported_unit)
14836         {
14837           /* Otherwise we skip to the next sibling, if any.  */
14838           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
14839           continue;
14840         }
14841
14842       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
14843                                    info_ptr);
14844
14845       /* This two-pass algorithm for processing partial symbols has a
14846          high cost in cache pressure.  Thus, handle some simple cases
14847          here which cover the majority of C partial symbols.  DIEs
14848          which neither have specification tags in them, nor could have
14849          specification tags elsewhere pointing at them, can simply be
14850          processed and discarded.
14851
14852          This segment is also optional; scan_partial_symbols and
14853          add_partial_symbol will handle these DIEs if we chain
14854          them in normally.  When compilers which do not emit large
14855          quantities of duplicate debug information are more common,
14856          this code can probably be removed.  */
14857
14858       /* Any complete simple types at the top level (pretty much all
14859          of them, for a language without namespaces), can be processed
14860          directly.  */
14861       if (parent_die == NULL
14862           && part_die->has_specification == 0
14863           && part_die->is_declaration == 0
14864           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
14865               || part_die->tag == DW_TAG_base_type
14866               || part_die->tag == DW_TAG_subrange_type))
14867         {
14868           if (building_psymtab && part_die->name != NULL)
14869             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14870                                  VAR_DOMAIN, LOC_TYPEDEF,
14871                                  &objfile->static_psymbols,
14872                                  0, (CORE_ADDR) 0, cu->language, objfile);
14873           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14874           continue;
14875         }
14876
14877       /* The exception for DW_TAG_typedef with has_children above is
14878          a workaround of GCC PR debug/47510.  In the case of this complaint
14879          type_name_no_tag_or_error will error on such types later.
14880
14881          GDB skipped children of DW_TAG_typedef by the shortcut above and then
14882          it could not find the child DIEs referenced later, this is checked
14883          above.  In correct DWARF DW_TAG_typedef should have no children.  */
14884
14885       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
14886         complaint (&symfile_complaints,
14887                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
14888                      "- DIE at 0x%x [in module %s]"),
14889                    part_die->offset.sect_off, objfile_name (objfile));
14890
14891       /* If we're at the second level, and we're an enumerator, and
14892          our parent has no specification (meaning possibly lives in a
14893          namespace elsewhere), then we can add the partial symbol now
14894          instead of queueing it.  */
14895       if (part_die->tag == DW_TAG_enumerator
14896           && parent_die != NULL
14897           && parent_die->die_parent == NULL
14898           && parent_die->tag == DW_TAG_enumeration_type
14899           && parent_die->has_specification == 0)
14900         {
14901           if (part_die->name == NULL)
14902             complaint (&symfile_complaints,
14903                        _("malformed enumerator DIE ignored"));
14904           else if (building_psymtab)
14905             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
14906                                  VAR_DOMAIN, LOC_CONST,
14907                                  (cu->language == language_cplus
14908                                   || cu->language == language_java)
14909                                  ? &objfile->global_psymbols
14910                                  : &objfile->static_psymbols,
14911                                  0, (CORE_ADDR) 0, cu->language, objfile);
14912
14913           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
14914           continue;
14915         }
14916
14917       /* We'll save this DIE so link it in.  */
14918       part_die->die_parent = parent_die;
14919       part_die->die_sibling = NULL;
14920       part_die->die_child = NULL;
14921
14922       if (last_die && last_die == parent_die)
14923         last_die->die_child = part_die;
14924       else if (last_die)
14925         last_die->die_sibling = part_die;
14926
14927       last_die = part_die;
14928
14929       if (first_die == NULL)
14930         first_die = part_die;
14931
14932       /* Maybe add the DIE to the hash table.  Not all DIEs that we
14933          find interesting need to be in the hash table, because we
14934          also have the parent/sibling/child chains; only those that we
14935          might refer to by offset later during partial symbol reading.
14936
14937          For now this means things that might have be the target of a
14938          DW_AT_specification, DW_AT_abstract_origin, or
14939          DW_AT_extension.  DW_AT_extension will refer only to
14940          namespaces; DW_AT_abstract_origin refers to functions (and
14941          many things under the function DIE, but we do not recurse
14942          into function DIEs during partial symbol reading) and
14943          possibly variables as well; DW_AT_specification refers to
14944          declarations.  Declarations ought to have the DW_AT_declaration
14945          flag.  It happens that GCC forgets to put it in sometimes, but
14946          only for functions, not for types.
14947
14948          Adding more things than necessary to the hash table is harmless
14949          except for the performance cost.  Adding too few will result in
14950          wasted time in find_partial_die, when we reread the compilation
14951          unit with load_all_dies set.  */
14952
14953       if (load_all
14954           || abbrev->tag == DW_TAG_constant
14955           || abbrev->tag == DW_TAG_subprogram
14956           || abbrev->tag == DW_TAG_variable
14957           || abbrev->tag == DW_TAG_namespace
14958           || part_die->is_declaration)
14959         {
14960           void **slot;
14961
14962           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
14963                                            part_die->offset.sect_off, INSERT);
14964           *slot = part_die;
14965         }
14966
14967       part_die = obstack_alloc (&cu->comp_unit_obstack,
14968                                 sizeof (struct partial_die_info));
14969
14970       /* For some DIEs we want to follow their children (if any).  For C
14971          we have no reason to follow the children of structures; for other
14972          languages we have to, so that we can get at method physnames
14973          to infer fully qualified class names, for DW_AT_specification,
14974          and for C++ template arguments.  For C++, we also look one level
14975          inside functions to find template arguments (if the name of the
14976          function does not already contain the template arguments).
14977
14978          For Ada, we need to scan the children of subprograms and lexical
14979          blocks as well because Ada allows the definition of nested
14980          entities that could be interesting for the debugger, such as
14981          nested subprograms for instance.  */
14982       if (last_die->has_children
14983           && (load_all
14984               || last_die->tag == DW_TAG_namespace
14985               || last_die->tag == DW_TAG_module
14986               || last_die->tag == DW_TAG_enumeration_type
14987               || (cu->language == language_cplus
14988                   && last_die->tag == DW_TAG_subprogram
14989                   && (last_die->name == NULL
14990                       || strchr (last_die->name, '<') == NULL))
14991               || (cu->language != language_c
14992                   && (last_die->tag == DW_TAG_class_type
14993                       || last_die->tag == DW_TAG_interface_type
14994                       || last_die->tag == DW_TAG_structure_type
14995                       || last_die->tag == DW_TAG_union_type))
14996               || (cu->language == language_ada
14997                   && (last_die->tag == DW_TAG_subprogram
14998                       || last_die->tag == DW_TAG_lexical_block))))
14999         {
15000           nesting_level++;
15001           parent_die = last_die;
15002           continue;
15003         }
15004
15005       /* Otherwise we skip to the next sibling, if any.  */
15006       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
15007
15008       /* Back to the top, do it again.  */
15009     }
15010 }
15011
15012 /* Read a minimal amount of information into the minimal die structure.  */
15013
15014 static const gdb_byte *
15015 read_partial_die (const struct die_reader_specs *reader,
15016                   struct partial_die_info *part_die,
15017                   struct abbrev_info *abbrev, unsigned int abbrev_len,
15018                   const gdb_byte *info_ptr)
15019 {
15020   struct dwarf2_cu *cu = reader->cu;
15021   struct objfile *objfile = cu->objfile;
15022   const gdb_byte *buffer = reader->buffer;
15023   unsigned int i;
15024   struct attribute attr;
15025   int has_low_pc_attr = 0;
15026   int has_high_pc_attr = 0;
15027   int high_pc_relative = 0;
15028
15029   memset (part_die, 0, sizeof (struct partial_die_info));
15030
15031   part_die->offset.sect_off = info_ptr - buffer;
15032
15033   info_ptr += abbrev_len;
15034
15035   if (abbrev == NULL)
15036     return info_ptr;
15037
15038   part_die->tag = abbrev->tag;
15039   part_die->has_children = abbrev->has_children;
15040
15041   for (i = 0; i < abbrev->num_attrs; ++i)
15042     {
15043       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
15044
15045       /* Store the data if it is of an attribute we want to keep in a
15046          partial symbol table.  */
15047       switch (attr.name)
15048         {
15049         case DW_AT_name:
15050           switch (part_die->tag)
15051             {
15052             case DW_TAG_compile_unit:
15053             case DW_TAG_partial_unit:
15054             case DW_TAG_type_unit:
15055               /* Compilation units have a DW_AT_name that is a filename, not
15056                  a source language identifier.  */
15057             case DW_TAG_enumeration_type:
15058             case DW_TAG_enumerator:
15059               /* These tags always have simple identifiers already; no need
15060                  to canonicalize them.  */
15061               part_die->name = DW_STRING (&attr);
15062               break;
15063             default:
15064               part_die->name
15065                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
15066                                             &objfile->objfile_obstack);
15067               break;
15068             }
15069           break;
15070         case DW_AT_linkage_name:
15071         case DW_AT_MIPS_linkage_name:
15072           /* Note that both forms of linkage name might appear.  We
15073              assume they will be the same, and we only store the last
15074              one we see.  */
15075           if (cu->language == language_ada)
15076             part_die->name = DW_STRING (&attr);
15077           part_die->linkage_name = DW_STRING (&attr);
15078           break;
15079         case DW_AT_low_pc:
15080           has_low_pc_attr = 1;
15081           part_die->lowpc = DW_ADDR (&attr);
15082           break;
15083         case DW_AT_high_pc:
15084           has_high_pc_attr = 1;
15085           if (attr.form == DW_FORM_addr
15086               || attr.form == DW_FORM_GNU_addr_index)
15087             part_die->highpc = DW_ADDR (&attr);
15088           else
15089             {
15090               high_pc_relative = 1;
15091               part_die->highpc = DW_UNSND (&attr);
15092             }
15093           break;
15094         case DW_AT_location:
15095           /* Support the .debug_loc offsets.  */
15096           if (attr_form_is_block (&attr))
15097             {
15098                part_die->d.locdesc = DW_BLOCK (&attr);
15099             }
15100           else if (attr_form_is_section_offset (&attr))
15101             {
15102               dwarf2_complex_location_expr_complaint ();
15103             }
15104           else
15105             {
15106               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15107                                                      "partial symbol information");
15108             }
15109           break;
15110         case DW_AT_external:
15111           part_die->is_external = DW_UNSND (&attr);
15112           break;
15113         case DW_AT_declaration:
15114           part_die->is_declaration = DW_UNSND (&attr);
15115           break;
15116         case DW_AT_type:
15117           part_die->has_type = 1;
15118           break;
15119         case DW_AT_abstract_origin:
15120         case DW_AT_specification:
15121         case DW_AT_extension:
15122           part_die->has_specification = 1;
15123           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
15124           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15125                                    || cu->per_cu->is_dwz);
15126           break;
15127         case DW_AT_sibling:
15128           /* Ignore absolute siblings, they might point outside of
15129              the current compile unit.  */
15130           if (attr.form == DW_FORM_ref_addr)
15131             complaint (&symfile_complaints,
15132                        _("ignoring absolute DW_AT_sibling"));
15133           else
15134             part_die->sibling = buffer + dwarf2_get_ref_die_offset (&attr).sect_off;
15135           break;
15136         case DW_AT_byte_size:
15137           part_die->has_byte_size = 1;
15138           break;
15139         case DW_AT_calling_convention:
15140           /* DWARF doesn't provide a way to identify a program's source-level
15141              entry point.  DW_AT_calling_convention attributes are only meant
15142              to describe functions' calling conventions.
15143
15144              However, because it's a necessary piece of information in
15145              Fortran, and because DW_CC_program is the only piece of debugging
15146              information whose definition refers to a 'main program' at all,
15147              several compilers have begun marking Fortran main programs with
15148              DW_CC_program --- even when those functions use the standard
15149              calling conventions.
15150
15151              So until DWARF specifies a way to provide this information and
15152              compilers pick up the new representation, we'll support this
15153              practice.  */
15154           if (DW_UNSND (&attr) == DW_CC_program
15155               && cu->language == language_fortran)
15156             {
15157               set_main_name (part_die->name);
15158
15159               /* As this DIE has a static linkage the name would be difficult
15160                  to look up later.  */
15161               language_of_main = language_fortran;
15162             }
15163           break;
15164         case DW_AT_inline:
15165           if (DW_UNSND (&attr) == DW_INL_inlined
15166               || DW_UNSND (&attr) == DW_INL_declared_inlined)
15167             part_die->may_be_inlined = 1;
15168           break;
15169
15170         case DW_AT_import:
15171           if (part_die->tag == DW_TAG_imported_unit)
15172             {
15173               part_die->d.offset = dwarf2_get_ref_die_offset (&attr);
15174               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
15175                                   || cu->per_cu->is_dwz);
15176             }
15177           break;
15178
15179         default:
15180           break;
15181         }
15182     }
15183
15184   if (high_pc_relative)
15185     part_die->highpc += part_die->lowpc;
15186
15187   if (has_low_pc_attr && has_high_pc_attr)
15188     {
15189       /* When using the GNU linker, .gnu.linkonce. sections are used to
15190          eliminate duplicate copies of functions and vtables and such.
15191          The linker will arbitrarily choose one and discard the others.
15192          The AT_*_pc values for such functions refer to local labels in
15193          these sections.  If the section from that file was discarded, the
15194          labels are not in the output, so the relocs get a value of 0.
15195          If this is a discarded function, mark the pc bounds as invalid,
15196          so that GDB will ignore it.  */
15197       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
15198         {
15199           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15200
15201           complaint (&symfile_complaints,
15202                      _("DW_AT_low_pc %s is zero "
15203                        "for DIE at 0x%x [in module %s]"),
15204                      paddress (gdbarch, part_die->lowpc),
15205                      part_die->offset.sect_off, objfile_name (objfile));
15206         }
15207       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
15208       else if (part_die->lowpc >= part_die->highpc)
15209         {
15210           struct gdbarch *gdbarch = get_objfile_arch (objfile);
15211
15212           complaint (&symfile_complaints,
15213                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
15214                        "for DIE at 0x%x [in module %s]"),
15215                      paddress (gdbarch, part_die->lowpc),
15216                      paddress (gdbarch, part_die->highpc),
15217                      part_die->offset.sect_off, objfile_name (objfile));
15218         }
15219       else
15220         part_die->has_pc_info = 1;
15221     }
15222
15223   return info_ptr;
15224 }
15225
15226 /* Find a cached partial DIE at OFFSET in CU.  */
15227
15228 static struct partial_die_info *
15229 find_partial_die_in_comp_unit (sect_offset offset, struct dwarf2_cu *cu)
15230 {
15231   struct partial_die_info *lookup_die = NULL;
15232   struct partial_die_info part_die;
15233
15234   part_die.offset = offset;
15235   lookup_die = htab_find_with_hash (cu->partial_dies, &part_die,
15236                                     offset.sect_off);
15237
15238   return lookup_die;
15239 }
15240
15241 /* Find a partial DIE at OFFSET, which may or may not be in CU,
15242    except in the case of .debug_types DIEs which do not reference
15243    outside their CU (they do however referencing other types via
15244    DW_FORM_ref_sig8).  */
15245
15246 static struct partial_die_info *
15247 find_partial_die (sect_offset offset, int offset_in_dwz, struct dwarf2_cu *cu)
15248 {
15249   struct objfile *objfile = cu->objfile;
15250   struct dwarf2_per_cu_data *per_cu = NULL;
15251   struct partial_die_info *pd = NULL;
15252
15253   if (offset_in_dwz == cu->per_cu->is_dwz
15254       && offset_in_cu_p (&cu->header, offset))
15255     {
15256       pd = find_partial_die_in_comp_unit (offset, cu);
15257       if (pd != NULL)
15258         return pd;
15259       /* We missed recording what we needed.
15260          Load all dies and try again.  */
15261       per_cu = cu->per_cu;
15262     }
15263   else
15264     {
15265       /* TUs don't reference other CUs/TUs (except via type signatures).  */
15266       if (cu->per_cu->is_debug_types)
15267         {
15268           error (_("Dwarf Error: Type Unit at offset 0x%lx contains"
15269                    " external reference to offset 0x%lx [in module %s].\n"),
15270                  (long) cu->header.offset.sect_off, (long) offset.sect_off,
15271                  bfd_get_filename (objfile->obfd));
15272         }
15273       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
15274                                                  objfile);
15275
15276       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
15277         load_partial_comp_unit (per_cu);
15278
15279       per_cu->cu->last_used = 0;
15280       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15281     }
15282
15283   /* If we didn't find it, and not all dies have been loaded,
15284      load them all and try again.  */
15285
15286   if (pd == NULL && per_cu->load_all_dies == 0)
15287     {
15288       per_cu->load_all_dies = 1;
15289
15290       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
15291          THIS_CU->cu may already be in use.  So we can't just free it and
15292          replace its DIEs with the ones we read in.  Instead, we leave those
15293          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
15294          and clobber THIS_CU->cu->partial_dies with the hash table for the new
15295          set.  */
15296       load_partial_comp_unit (per_cu);
15297
15298       pd = find_partial_die_in_comp_unit (offset, per_cu->cu);
15299     }
15300
15301   if (pd == NULL)
15302     internal_error (__FILE__, __LINE__,
15303                     _("could not find partial DIE 0x%x "
15304                       "in cache [from module %s]\n"),
15305                     offset.sect_off, bfd_get_filename (objfile->obfd));
15306   return pd;
15307 }
15308
15309 /* See if we can figure out if the class lives in a namespace.  We do
15310    this by looking for a member function; its demangled name will
15311    contain namespace info, if there is any.  */
15312
15313 static void
15314 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
15315                                   struct dwarf2_cu *cu)
15316 {
15317   /* NOTE: carlton/2003-10-07: Getting the info this way changes
15318      what template types look like, because the demangler
15319      frequently doesn't give the same name as the debug info.  We
15320      could fix this by only using the demangled name to get the
15321      prefix (but see comment in read_structure_type).  */
15322
15323   struct partial_die_info *real_pdi;
15324   struct partial_die_info *child_pdi;
15325
15326   /* If this DIE (this DIE's specification, if any) has a parent, then
15327      we should not do this.  We'll prepend the parent's fully qualified
15328      name when we create the partial symbol.  */
15329
15330   real_pdi = struct_pdi;
15331   while (real_pdi->has_specification)
15332     real_pdi = find_partial_die (real_pdi->spec_offset,
15333                                  real_pdi->spec_is_dwz, cu);
15334
15335   if (real_pdi->die_parent != NULL)
15336     return;
15337
15338   for (child_pdi = struct_pdi->die_child;
15339        child_pdi != NULL;
15340        child_pdi = child_pdi->die_sibling)
15341     {
15342       if (child_pdi->tag == DW_TAG_subprogram
15343           && child_pdi->linkage_name != NULL)
15344         {
15345           char *actual_class_name
15346             = language_class_name_from_physname (cu->language_defn,
15347                                                  child_pdi->linkage_name);
15348           if (actual_class_name != NULL)
15349             {
15350               struct_pdi->name
15351                 = obstack_copy0 (&cu->objfile->objfile_obstack,
15352                                  actual_class_name,
15353                                  strlen (actual_class_name));
15354               xfree (actual_class_name);
15355             }
15356           break;
15357         }
15358     }
15359 }
15360
15361 /* Adjust PART_DIE before generating a symbol for it.  This function
15362    may set the is_external flag or change the DIE's name.  */
15363
15364 static void
15365 fixup_partial_die (struct partial_die_info *part_die,
15366                    struct dwarf2_cu *cu)
15367 {
15368   /* Once we've fixed up a die, there's no point in doing so again.
15369      This also avoids a memory leak if we were to call
15370      guess_partial_die_structure_name multiple times.  */
15371   if (part_die->fixup_called)
15372     return;
15373
15374   /* If we found a reference attribute and the DIE has no name, try
15375      to find a name in the referred to DIE.  */
15376
15377   if (part_die->name == NULL && part_die->has_specification)
15378     {
15379       struct partial_die_info *spec_die;
15380
15381       spec_die = find_partial_die (part_die->spec_offset,
15382                                    part_die->spec_is_dwz, cu);
15383
15384       fixup_partial_die (spec_die, cu);
15385
15386       if (spec_die->name)
15387         {
15388           part_die->name = spec_die->name;
15389
15390           /* Copy DW_AT_external attribute if it is set.  */
15391           if (spec_die->is_external)
15392             part_die->is_external = spec_die->is_external;
15393         }
15394     }
15395
15396   /* Set default names for some unnamed DIEs.  */
15397
15398   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
15399     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
15400
15401   /* If there is no parent die to provide a namespace, and there are
15402      children, see if we can determine the namespace from their linkage
15403      name.  */
15404   if (cu->language == language_cplus
15405       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
15406       && part_die->die_parent == NULL
15407       && part_die->has_children
15408       && (part_die->tag == DW_TAG_class_type
15409           || part_die->tag == DW_TAG_structure_type
15410           || part_die->tag == DW_TAG_union_type))
15411     guess_partial_die_structure_name (part_die, cu);
15412
15413   /* GCC might emit a nameless struct or union that has a linkage
15414      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
15415   if (part_die->name == NULL
15416       && (part_die->tag == DW_TAG_class_type
15417           || part_die->tag == DW_TAG_interface_type
15418           || part_die->tag == DW_TAG_structure_type
15419           || part_die->tag == DW_TAG_union_type)
15420       && part_die->linkage_name != NULL)
15421     {
15422       char *demangled;
15423
15424       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
15425       if (demangled)
15426         {
15427           const char *base;
15428
15429           /* Strip any leading namespaces/classes, keep only the base name.
15430              DW_AT_name for named DIEs does not contain the prefixes.  */
15431           base = strrchr (demangled, ':');
15432           if (base && base > demangled && base[-1] == ':')
15433             base++;
15434           else
15435             base = demangled;
15436
15437           part_die->name = obstack_copy0 (&cu->objfile->objfile_obstack,
15438                                           base, strlen (base));
15439           xfree (demangled);
15440         }
15441     }
15442
15443   part_die->fixup_called = 1;
15444 }
15445
15446 /* Read an attribute value described by an attribute form.  */
15447
15448 static const gdb_byte *
15449 read_attribute_value (const struct die_reader_specs *reader,
15450                       struct attribute *attr, unsigned form,
15451                       const gdb_byte *info_ptr)
15452 {
15453   struct dwarf2_cu *cu = reader->cu;
15454   bfd *abfd = reader->abfd;
15455   struct comp_unit_head *cu_header = &cu->header;
15456   unsigned int bytes_read;
15457   struct dwarf_block *blk;
15458
15459   attr->form = form;
15460   switch (form)
15461     {
15462     case DW_FORM_ref_addr:
15463       if (cu->header.version == 2)
15464         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15465       else
15466         DW_UNSND (attr) = read_offset (abfd, info_ptr,
15467                                        &cu->header, &bytes_read);
15468       info_ptr += bytes_read;
15469       break;
15470     case DW_FORM_GNU_ref_alt:
15471       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15472       info_ptr += bytes_read;
15473       break;
15474     case DW_FORM_addr:
15475       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
15476       info_ptr += bytes_read;
15477       break;
15478     case DW_FORM_block2:
15479       blk = dwarf_alloc_block (cu);
15480       blk->size = read_2_bytes (abfd, info_ptr);
15481       info_ptr += 2;
15482       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15483       info_ptr += blk->size;
15484       DW_BLOCK (attr) = blk;
15485       break;
15486     case DW_FORM_block4:
15487       blk = dwarf_alloc_block (cu);
15488       blk->size = read_4_bytes (abfd, info_ptr);
15489       info_ptr += 4;
15490       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15491       info_ptr += blk->size;
15492       DW_BLOCK (attr) = blk;
15493       break;
15494     case DW_FORM_data2:
15495       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
15496       info_ptr += 2;
15497       break;
15498     case DW_FORM_data4:
15499       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
15500       info_ptr += 4;
15501       break;
15502     case DW_FORM_data8:
15503       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
15504       info_ptr += 8;
15505       break;
15506     case DW_FORM_sec_offset:
15507       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
15508       info_ptr += bytes_read;
15509       break;
15510     case DW_FORM_string:
15511       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
15512       DW_STRING_IS_CANONICAL (attr) = 0;
15513       info_ptr += bytes_read;
15514       break;
15515     case DW_FORM_strp:
15516       if (!cu->per_cu->is_dwz)
15517         {
15518           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
15519                                                    &bytes_read);
15520           DW_STRING_IS_CANONICAL (attr) = 0;
15521           info_ptr += bytes_read;
15522           break;
15523         }
15524       /* FALLTHROUGH */
15525     case DW_FORM_GNU_strp_alt:
15526       {
15527         struct dwz_file *dwz = dwarf2_get_dwz_file ();
15528         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
15529                                           &bytes_read);
15530
15531         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
15532         DW_STRING_IS_CANONICAL (attr) = 0;
15533         info_ptr += bytes_read;
15534       }
15535       break;
15536     case DW_FORM_exprloc:
15537     case DW_FORM_block:
15538       blk = dwarf_alloc_block (cu);
15539       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15540       info_ptr += bytes_read;
15541       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15542       info_ptr += blk->size;
15543       DW_BLOCK (attr) = blk;
15544       break;
15545     case DW_FORM_block1:
15546       blk = dwarf_alloc_block (cu);
15547       blk->size = read_1_byte (abfd, info_ptr);
15548       info_ptr += 1;
15549       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
15550       info_ptr += blk->size;
15551       DW_BLOCK (attr) = blk;
15552       break;
15553     case DW_FORM_data1:
15554       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15555       info_ptr += 1;
15556       break;
15557     case DW_FORM_flag:
15558       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
15559       info_ptr += 1;
15560       break;
15561     case DW_FORM_flag_present:
15562       DW_UNSND (attr) = 1;
15563       break;
15564     case DW_FORM_sdata:
15565       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
15566       info_ptr += bytes_read;
15567       break;
15568     case DW_FORM_udata:
15569       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15570       info_ptr += bytes_read;
15571       break;
15572     case DW_FORM_ref1:
15573       DW_UNSND (attr) = (cu->header.offset.sect_off
15574                          + read_1_byte (abfd, info_ptr));
15575       info_ptr += 1;
15576       break;
15577     case DW_FORM_ref2:
15578       DW_UNSND (attr) = (cu->header.offset.sect_off
15579                          + read_2_bytes (abfd, info_ptr));
15580       info_ptr += 2;
15581       break;
15582     case DW_FORM_ref4:
15583       DW_UNSND (attr) = (cu->header.offset.sect_off
15584                          + read_4_bytes (abfd, info_ptr));
15585       info_ptr += 4;
15586       break;
15587     case DW_FORM_ref8:
15588       DW_UNSND (attr) = (cu->header.offset.sect_off
15589                          + read_8_bytes (abfd, info_ptr));
15590       info_ptr += 8;
15591       break;
15592     case DW_FORM_ref_sig8:
15593       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
15594       info_ptr += 8;
15595       break;
15596     case DW_FORM_ref_udata:
15597       DW_UNSND (attr) = (cu->header.offset.sect_off
15598                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
15599       info_ptr += bytes_read;
15600       break;
15601     case DW_FORM_indirect:
15602       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15603       info_ptr += bytes_read;
15604       info_ptr = read_attribute_value (reader, attr, form, info_ptr);
15605       break;
15606     case DW_FORM_GNU_addr_index:
15607       if (reader->dwo_file == NULL)
15608         {
15609           /* For now flag a hard error.
15610              Later we can turn this into a complaint.  */
15611           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15612                  dwarf_form_name (form),
15613                  bfd_get_filename (abfd));
15614         }
15615       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
15616       info_ptr += bytes_read;
15617       break;
15618     case DW_FORM_GNU_str_index:
15619       if (reader->dwo_file == NULL)
15620         {
15621           /* For now flag a hard error.
15622              Later we can turn this into a complaint if warranted.  */
15623           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
15624                  dwarf_form_name (form),
15625                  bfd_get_filename (abfd));
15626         }
15627       {
15628         ULONGEST str_index =
15629           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15630
15631         DW_STRING (attr) = read_str_index (reader, cu, str_index);
15632         DW_STRING_IS_CANONICAL (attr) = 0;
15633         info_ptr += bytes_read;
15634       }
15635       break;
15636     default:
15637       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
15638              dwarf_form_name (form),
15639              bfd_get_filename (abfd));
15640     }
15641
15642   /* Super hack.  */
15643   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
15644     attr->form = DW_FORM_GNU_ref_alt;
15645
15646   /* We have seen instances where the compiler tried to emit a byte
15647      size attribute of -1 which ended up being encoded as an unsigned
15648      0xffffffff.  Although 0xffffffff is technically a valid size value,
15649      an object of this size seems pretty unlikely so we can relatively
15650      safely treat these cases as if the size attribute was invalid and
15651      treat them as zero by default.  */
15652   if (attr->name == DW_AT_byte_size
15653       && form == DW_FORM_data4
15654       && DW_UNSND (attr) >= 0xffffffff)
15655     {
15656       complaint
15657         (&symfile_complaints,
15658          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
15659          hex_string (DW_UNSND (attr)));
15660       DW_UNSND (attr) = 0;
15661     }
15662
15663   return info_ptr;
15664 }
15665
15666 /* Read an attribute described by an abbreviated attribute.  */
15667
15668 static const gdb_byte *
15669 read_attribute (const struct die_reader_specs *reader,
15670                 struct attribute *attr, struct attr_abbrev *abbrev,
15671                 const gdb_byte *info_ptr)
15672 {
15673   attr->name = abbrev->name;
15674   return read_attribute_value (reader, attr, abbrev->form, info_ptr);
15675 }
15676
15677 /* Read dwarf information from a buffer.  */
15678
15679 static unsigned int
15680 read_1_byte (bfd *abfd, const gdb_byte *buf)
15681 {
15682   return bfd_get_8 (abfd, buf);
15683 }
15684
15685 static int
15686 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
15687 {
15688   return bfd_get_signed_8 (abfd, buf);
15689 }
15690
15691 static unsigned int
15692 read_2_bytes (bfd *abfd, const gdb_byte *buf)
15693 {
15694   return bfd_get_16 (abfd, buf);
15695 }
15696
15697 static int
15698 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
15699 {
15700   return bfd_get_signed_16 (abfd, buf);
15701 }
15702
15703 static unsigned int
15704 read_4_bytes (bfd *abfd, const gdb_byte *buf)
15705 {
15706   return bfd_get_32 (abfd, buf);
15707 }
15708
15709 static int
15710 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
15711 {
15712   return bfd_get_signed_32 (abfd, buf);
15713 }
15714
15715 static ULONGEST
15716 read_8_bytes (bfd *abfd, const gdb_byte *buf)
15717 {
15718   return bfd_get_64 (abfd, buf);
15719 }
15720
15721 static CORE_ADDR
15722 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
15723               unsigned int *bytes_read)
15724 {
15725   struct comp_unit_head *cu_header = &cu->header;
15726   CORE_ADDR retval = 0;
15727
15728   if (cu_header->signed_addr_p)
15729     {
15730       switch (cu_header->addr_size)
15731         {
15732         case 2:
15733           retval = bfd_get_signed_16 (abfd, buf);
15734           break;
15735         case 4:
15736           retval = bfd_get_signed_32 (abfd, buf);
15737           break;
15738         case 8:
15739           retval = bfd_get_signed_64 (abfd, buf);
15740           break;
15741         default:
15742           internal_error (__FILE__, __LINE__,
15743                           _("read_address: bad switch, signed [in module %s]"),
15744                           bfd_get_filename (abfd));
15745         }
15746     }
15747   else
15748     {
15749       switch (cu_header->addr_size)
15750         {
15751         case 2:
15752           retval = bfd_get_16 (abfd, buf);
15753           break;
15754         case 4:
15755           retval = bfd_get_32 (abfd, buf);
15756           break;
15757         case 8:
15758           retval = bfd_get_64 (abfd, buf);
15759           break;
15760         default:
15761           internal_error (__FILE__, __LINE__,
15762                           _("read_address: bad switch, "
15763                             "unsigned [in module %s]"),
15764                           bfd_get_filename (abfd));
15765         }
15766     }
15767
15768   *bytes_read = cu_header->addr_size;
15769   return retval;
15770 }
15771
15772 /* Read the initial length from a section.  The (draft) DWARF 3
15773    specification allows the initial length to take up either 4 bytes
15774    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
15775    bytes describe the length and all offsets will be 8 bytes in length
15776    instead of 4.
15777
15778    An older, non-standard 64-bit format is also handled by this
15779    function.  The older format in question stores the initial length
15780    as an 8-byte quantity without an escape value.  Lengths greater
15781    than 2^32 aren't very common which means that the initial 4 bytes
15782    is almost always zero.  Since a length value of zero doesn't make
15783    sense for the 32-bit format, this initial zero can be considered to
15784    be an escape value which indicates the presence of the older 64-bit
15785    format.  As written, the code can't detect (old format) lengths
15786    greater than 4GB.  If it becomes necessary to handle lengths
15787    somewhat larger than 4GB, we could allow other small values (such
15788    as the non-sensical values of 1, 2, and 3) to also be used as
15789    escape values indicating the presence of the old format.
15790
15791    The value returned via bytes_read should be used to increment the
15792    relevant pointer after calling read_initial_length().
15793
15794    [ Note:  read_initial_length() and read_offset() are based on the
15795      document entitled "DWARF Debugging Information Format", revision
15796      3, draft 8, dated November 19, 2001.  This document was obtained
15797      from:
15798
15799         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
15800
15801      This document is only a draft and is subject to change.  (So beware.)
15802
15803      Details regarding the older, non-standard 64-bit format were
15804      determined empirically by examining 64-bit ELF files produced by
15805      the SGI toolchain on an IRIX 6.5 machine.
15806
15807      - Kevin, July 16, 2002
15808    ] */
15809
15810 static LONGEST
15811 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
15812 {
15813   LONGEST length = bfd_get_32 (abfd, buf);
15814
15815   if (length == 0xffffffff)
15816     {
15817       length = bfd_get_64 (abfd, buf + 4);
15818       *bytes_read = 12;
15819     }
15820   else if (length == 0)
15821     {
15822       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
15823       length = bfd_get_64 (abfd, buf);
15824       *bytes_read = 8;
15825     }
15826   else
15827     {
15828       *bytes_read = 4;
15829     }
15830
15831   return length;
15832 }
15833
15834 /* Cover function for read_initial_length.
15835    Returns the length of the object at BUF, and stores the size of the
15836    initial length in *BYTES_READ and stores the size that offsets will be in
15837    *OFFSET_SIZE.
15838    If the initial length size is not equivalent to that specified in
15839    CU_HEADER then issue a complaint.
15840    This is useful when reading non-comp-unit headers.  */
15841
15842 static LONGEST
15843 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
15844                                         const struct comp_unit_head *cu_header,
15845                                         unsigned int *bytes_read,
15846                                         unsigned int *offset_size)
15847 {
15848   LONGEST length = read_initial_length (abfd, buf, bytes_read);
15849
15850   gdb_assert (cu_header->initial_length_size == 4
15851               || cu_header->initial_length_size == 8
15852               || cu_header->initial_length_size == 12);
15853
15854   if (cu_header->initial_length_size != *bytes_read)
15855     complaint (&symfile_complaints,
15856                _("intermixed 32-bit and 64-bit DWARF sections"));
15857
15858   *offset_size = (*bytes_read == 4) ? 4 : 8;
15859   return length;
15860 }
15861
15862 /* Read an offset from the data stream.  The size of the offset is
15863    given by cu_header->offset_size.  */
15864
15865 static LONGEST
15866 read_offset (bfd *abfd, const gdb_byte *buf,
15867              const struct comp_unit_head *cu_header,
15868              unsigned int *bytes_read)
15869 {
15870   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
15871
15872   *bytes_read = cu_header->offset_size;
15873   return offset;
15874 }
15875
15876 /* Read an offset from the data stream.  */
15877
15878 static LONGEST
15879 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
15880 {
15881   LONGEST retval = 0;
15882
15883   switch (offset_size)
15884     {
15885     case 4:
15886       retval = bfd_get_32 (abfd, buf);
15887       break;
15888     case 8:
15889       retval = bfd_get_64 (abfd, buf);
15890       break;
15891     default:
15892       internal_error (__FILE__, __LINE__,
15893                       _("read_offset_1: bad switch [in module %s]"),
15894                       bfd_get_filename (abfd));
15895     }
15896
15897   return retval;
15898 }
15899
15900 static const gdb_byte *
15901 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
15902 {
15903   /* If the size of a host char is 8 bits, we can return a pointer
15904      to the buffer, otherwise we have to copy the data to a buffer
15905      allocated on the temporary obstack.  */
15906   gdb_assert (HOST_CHAR_BIT == 8);
15907   return buf;
15908 }
15909
15910 static const char *
15911 read_direct_string (bfd *abfd, const gdb_byte *buf,
15912                     unsigned int *bytes_read_ptr)
15913 {
15914   /* If the size of a host char is 8 bits, we can return a pointer
15915      to the string, otherwise we have to copy the string to a buffer
15916      allocated on the temporary obstack.  */
15917   gdb_assert (HOST_CHAR_BIT == 8);
15918   if (*buf == '\0')
15919     {
15920       *bytes_read_ptr = 1;
15921       return NULL;
15922     }
15923   *bytes_read_ptr = strlen ((const char *) buf) + 1;
15924   return (const char *) buf;
15925 }
15926
15927 static const char *
15928 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
15929 {
15930   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwarf2_per_objfile->str);
15931   if (dwarf2_per_objfile->str.buffer == NULL)
15932     error (_("DW_FORM_strp used without .debug_str section [in module %s]"),
15933            bfd_get_filename (abfd));
15934   if (str_offset >= dwarf2_per_objfile->str.size)
15935     error (_("DW_FORM_strp pointing outside of "
15936              ".debug_str section [in module %s]"),
15937            bfd_get_filename (abfd));
15938   gdb_assert (HOST_CHAR_BIT == 8);
15939   if (dwarf2_per_objfile->str.buffer[str_offset] == '\0')
15940     return NULL;
15941   return (const char *) (dwarf2_per_objfile->str.buffer + str_offset);
15942 }
15943
15944 /* Read a string at offset STR_OFFSET in the .debug_str section from
15945    the .dwz file DWZ.  Throw an error if the offset is too large.  If
15946    the string consists of a single NUL byte, return NULL; otherwise
15947    return a pointer to the string.  */
15948
15949 static const char *
15950 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
15951 {
15952   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
15953
15954   if (dwz->str.buffer == NULL)
15955     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
15956              "section [in module %s]"),
15957            bfd_get_filename (dwz->dwz_bfd));
15958   if (str_offset >= dwz->str.size)
15959     error (_("DW_FORM_GNU_strp_alt pointing outside of "
15960              ".debug_str section [in module %s]"),
15961            bfd_get_filename (dwz->dwz_bfd));
15962   gdb_assert (HOST_CHAR_BIT == 8);
15963   if (dwz->str.buffer[str_offset] == '\0')
15964     return NULL;
15965   return (const char *) (dwz->str.buffer + str_offset);
15966 }
15967
15968 static const char *
15969 read_indirect_string (bfd *abfd, const gdb_byte *buf,
15970                       const struct comp_unit_head *cu_header,
15971                       unsigned int *bytes_read_ptr)
15972 {
15973   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
15974
15975   return read_indirect_string_at_offset (abfd, str_offset);
15976 }
15977
15978 static ULONGEST
15979 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
15980                       unsigned int *bytes_read_ptr)
15981 {
15982   ULONGEST result;
15983   unsigned int num_read;
15984   int i, shift;
15985   unsigned char byte;
15986
15987   result = 0;
15988   shift = 0;
15989   num_read = 0;
15990   i = 0;
15991   while (1)
15992     {
15993       byte = bfd_get_8 (abfd, buf);
15994       buf++;
15995       num_read++;
15996       result |= ((ULONGEST) (byte & 127) << shift);
15997       if ((byte & 128) == 0)
15998         {
15999           break;
16000         }
16001       shift += 7;
16002     }
16003   *bytes_read_ptr = num_read;
16004   return result;
16005 }
16006
16007 static LONGEST
16008 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
16009                     unsigned int *bytes_read_ptr)
16010 {
16011   LONGEST result;
16012   int i, shift, num_read;
16013   unsigned char byte;
16014
16015   result = 0;
16016   shift = 0;
16017   num_read = 0;
16018   i = 0;
16019   while (1)
16020     {
16021       byte = bfd_get_8 (abfd, buf);
16022       buf++;
16023       num_read++;
16024       result |= ((LONGEST) (byte & 127) << shift);
16025       shift += 7;
16026       if ((byte & 128) == 0)
16027         {
16028           break;
16029         }
16030     }
16031   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
16032     result |= -(((LONGEST) 1) << shift);
16033   *bytes_read_ptr = num_read;
16034   return result;
16035 }
16036
16037 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
16038    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
16039    ADDR_SIZE is the size of addresses from the CU header.  */
16040
16041 static CORE_ADDR
16042 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
16043 {
16044   struct objfile *objfile = dwarf2_per_objfile->objfile;
16045   bfd *abfd = objfile->obfd;
16046   const gdb_byte *info_ptr;
16047
16048   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
16049   if (dwarf2_per_objfile->addr.buffer == NULL)
16050     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
16051            objfile_name (objfile));
16052   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
16053     error (_("DW_FORM_addr_index pointing outside of "
16054              ".debug_addr section [in module %s]"),
16055            objfile_name (objfile));
16056   info_ptr = (dwarf2_per_objfile->addr.buffer
16057               + addr_base + addr_index * addr_size);
16058   if (addr_size == 4)
16059     return bfd_get_32 (abfd, info_ptr);
16060   else
16061     return bfd_get_64 (abfd, info_ptr);
16062 }
16063
16064 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
16065
16066 static CORE_ADDR
16067 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
16068 {
16069   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
16070 }
16071
16072 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
16073
16074 static CORE_ADDR
16075 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
16076                              unsigned int *bytes_read)
16077 {
16078   bfd *abfd = cu->objfile->obfd;
16079   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
16080
16081   return read_addr_index (cu, addr_index);
16082 }
16083
16084 /* Data structure to pass results from dwarf2_read_addr_index_reader
16085    back to dwarf2_read_addr_index.  */
16086
16087 struct dwarf2_read_addr_index_data
16088 {
16089   ULONGEST addr_base;
16090   int addr_size;
16091 };
16092
16093 /* die_reader_func for dwarf2_read_addr_index.  */
16094
16095 static void
16096 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
16097                                const gdb_byte *info_ptr,
16098                                struct die_info *comp_unit_die,
16099                                int has_children,
16100                                void *data)
16101 {
16102   struct dwarf2_cu *cu = reader->cu;
16103   struct dwarf2_read_addr_index_data *aidata =
16104     (struct dwarf2_read_addr_index_data *) data;
16105
16106   aidata->addr_base = cu->addr_base;
16107   aidata->addr_size = cu->header.addr_size;
16108 }
16109
16110 /* Given an index in .debug_addr, fetch the value.
16111    NOTE: This can be called during dwarf expression evaluation,
16112    long after the debug information has been read, and thus per_cu->cu
16113    may no longer exist.  */
16114
16115 CORE_ADDR
16116 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
16117                         unsigned int addr_index)
16118 {
16119   struct objfile *objfile = per_cu->objfile;
16120   struct dwarf2_cu *cu = per_cu->cu;
16121   ULONGEST addr_base;
16122   int addr_size;
16123
16124   /* This is intended to be called from outside this file.  */
16125   dw2_setup (objfile);
16126
16127   /* We need addr_base and addr_size.
16128      If we don't have PER_CU->cu, we have to get it.
16129      Nasty, but the alternative is storing the needed info in PER_CU,
16130      which at this point doesn't seem justified: it's not clear how frequently
16131      it would get used and it would increase the size of every PER_CU.
16132      Entry points like dwarf2_per_cu_addr_size do a similar thing
16133      so we're not in uncharted territory here.
16134      Alas we need to be a bit more complicated as addr_base is contained
16135      in the DIE.
16136
16137      We don't need to read the entire CU(/TU).
16138      We just need the header and top level die.
16139
16140      IWBN to use the aging mechanism to let us lazily later discard the CU.
16141      For now we skip this optimization.  */
16142
16143   if (cu != NULL)
16144     {
16145       addr_base = cu->addr_base;
16146       addr_size = cu->header.addr_size;
16147     }
16148   else
16149     {
16150       struct dwarf2_read_addr_index_data aidata;
16151
16152       /* Note: We can't use init_cutu_and_read_dies_simple here,
16153          we need addr_base.  */
16154       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
16155                                dwarf2_read_addr_index_reader, &aidata);
16156       addr_base = aidata.addr_base;
16157       addr_size = aidata.addr_size;
16158     }
16159
16160   return read_addr_index_1 (addr_index, addr_base, addr_size);
16161 }
16162
16163 /* Given a DW_FORM_GNU_str_index, fetch the string.
16164    This is only used by the Fission support.  */
16165
16166 static const char *
16167 read_str_index (const struct die_reader_specs *reader,
16168                 struct dwarf2_cu *cu, ULONGEST str_index)
16169 {
16170   struct objfile *objfile = dwarf2_per_objfile->objfile;
16171   const char *dwo_name = objfile_name (objfile);
16172   bfd *abfd = objfile->obfd;
16173   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
16174   struct dwarf2_section_info *str_offsets_section =
16175     &reader->dwo_file->sections.str_offsets;
16176   const gdb_byte *info_ptr;
16177   ULONGEST str_offset;
16178   static const char form_name[] = "DW_FORM_GNU_str_index";
16179
16180   dwarf2_read_section (objfile, str_section);
16181   dwarf2_read_section (objfile, str_offsets_section);
16182   if (str_section->buffer == NULL)
16183     error (_("%s used without .debug_str.dwo section"
16184              " in CU at offset 0x%lx [in module %s]"),
16185            form_name, (long) cu->header.offset.sect_off, dwo_name);
16186   if (str_offsets_section->buffer == NULL)
16187     error (_("%s used without .debug_str_offsets.dwo section"
16188              " in CU at offset 0x%lx [in module %s]"),
16189            form_name, (long) cu->header.offset.sect_off, dwo_name);
16190   if (str_index * cu->header.offset_size >= str_offsets_section->size)
16191     error (_("%s pointing outside of .debug_str_offsets.dwo"
16192              " section in CU at offset 0x%lx [in module %s]"),
16193            form_name, (long) cu->header.offset.sect_off, dwo_name);
16194   info_ptr = (str_offsets_section->buffer
16195               + str_index * cu->header.offset_size);
16196   if (cu->header.offset_size == 4)
16197     str_offset = bfd_get_32 (abfd, info_ptr);
16198   else
16199     str_offset = bfd_get_64 (abfd, info_ptr);
16200   if (str_offset >= str_section->size)
16201     error (_("Offset from %s pointing outside of"
16202              " .debug_str.dwo section in CU at offset 0x%lx [in module %s]"),
16203            form_name, (long) cu->header.offset.sect_off, dwo_name);
16204   return (const char *) (str_section->buffer + str_offset);
16205 }
16206
16207 /* Return the length of an LEB128 number in BUF.  */
16208
16209 static int
16210 leb128_size (const gdb_byte *buf)
16211 {
16212   const gdb_byte *begin = buf;
16213   gdb_byte byte;
16214
16215   while (1)
16216     {
16217       byte = *buf++;
16218       if ((byte & 128) == 0)
16219         return buf - begin;
16220     }
16221 }
16222
16223 static void
16224 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
16225 {
16226   switch (lang)
16227     {
16228     case DW_LANG_C89:
16229     case DW_LANG_C99:
16230     case DW_LANG_C:
16231     case DW_LANG_UPC:
16232       cu->language = language_c;
16233       break;
16234     case DW_LANG_C_plus_plus:
16235       cu->language = language_cplus;
16236       break;
16237     case DW_LANG_D:
16238       cu->language = language_d;
16239       break;
16240     case DW_LANG_Fortran77:
16241     case DW_LANG_Fortran90:
16242     case DW_LANG_Fortran95:
16243       cu->language = language_fortran;
16244       break;
16245     case DW_LANG_Go:
16246       cu->language = language_go;
16247       break;
16248     case DW_LANG_Mips_Assembler:
16249       cu->language = language_asm;
16250       break;
16251     case DW_LANG_Java:
16252       cu->language = language_java;
16253       break;
16254     case DW_LANG_Ada83:
16255     case DW_LANG_Ada95:
16256       cu->language = language_ada;
16257       break;
16258     case DW_LANG_Modula2:
16259       cu->language = language_m2;
16260       break;
16261     case DW_LANG_Pascal83:
16262       cu->language = language_pascal;
16263       break;
16264     case DW_LANG_ObjC:
16265       cu->language = language_objc;
16266       break;
16267     case DW_LANG_Cobol74:
16268     case DW_LANG_Cobol85:
16269     default:
16270       cu->language = language_minimal;
16271       break;
16272     }
16273   cu->language_defn = language_def (cu->language);
16274 }
16275
16276 /* Return the named attribute or NULL if not there.  */
16277
16278 static struct attribute *
16279 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
16280 {
16281   for (;;)
16282     {
16283       unsigned int i;
16284       struct attribute *spec = NULL;
16285
16286       for (i = 0; i < die->num_attrs; ++i)
16287         {
16288           if (die->attrs[i].name == name)
16289             return &die->attrs[i];
16290           if (die->attrs[i].name == DW_AT_specification
16291               || die->attrs[i].name == DW_AT_abstract_origin)
16292             spec = &die->attrs[i];
16293         }
16294
16295       if (!spec)
16296         break;
16297
16298       die = follow_die_ref (die, spec, &cu);
16299     }
16300
16301   return NULL;
16302 }
16303
16304 /* Return the named attribute or NULL if not there,
16305    but do not follow DW_AT_specification, etc.
16306    This is for use in contexts where we're reading .debug_types dies.
16307    Following DW_AT_specification, DW_AT_abstract_origin will take us
16308    back up the chain, and we want to go down.  */
16309
16310 static struct attribute *
16311 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
16312 {
16313   unsigned int i;
16314
16315   for (i = 0; i < die->num_attrs; ++i)
16316     if (die->attrs[i].name == name)
16317       return &die->attrs[i];
16318
16319   return NULL;
16320 }
16321
16322 /* Return non-zero iff the attribute NAME is defined for the given DIE,
16323    and holds a non-zero value.  This function should only be used for
16324    DW_FORM_flag or DW_FORM_flag_present attributes.  */
16325
16326 static int
16327 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
16328 {
16329   struct attribute *attr = dwarf2_attr (die, name, cu);
16330
16331   return (attr && DW_UNSND (attr));
16332 }
16333
16334 static int
16335 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
16336 {
16337   /* A DIE is a declaration if it has a DW_AT_declaration attribute
16338      which value is non-zero.  However, we have to be careful with
16339      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
16340      (via dwarf2_flag_true_p) follows this attribute.  So we may
16341      end up accidently finding a declaration attribute that belongs
16342      to a different DIE referenced by the specification attribute,
16343      even though the given DIE does not have a declaration attribute.  */
16344   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
16345           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
16346 }
16347
16348 /* Return the die giving the specification for DIE, if there is
16349    one.  *SPEC_CU is the CU containing DIE on input, and the CU
16350    containing the return value on output.  If there is no
16351    specification, but there is an abstract origin, that is
16352    returned.  */
16353
16354 static struct die_info *
16355 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
16356 {
16357   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
16358                                              *spec_cu);
16359
16360   if (spec_attr == NULL)
16361     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
16362
16363   if (spec_attr == NULL)
16364     return NULL;
16365   else
16366     return follow_die_ref (die, spec_attr, spec_cu);
16367 }
16368
16369 /* Free the line_header structure *LH, and any arrays and strings it
16370    refers to.
16371    NOTE: This is also used as a "cleanup" function.  */
16372
16373 static void
16374 free_line_header (struct line_header *lh)
16375 {
16376   if (lh->standard_opcode_lengths)
16377     xfree (lh->standard_opcode_lengths);
16378
16379   /* Remember that all the lh->file_names[i].name pointers are
16380      pointers into debug_line_buffer, and don't need to be freed.  */
16381   if (lh->file_names)
16382     xfree (lh->file_names);
16383
16384   /* Similarly for the include directory names.  */
16385   if (lh->include_dirs)
16386     xfree (lh->include_dirs);
16387
16388   xfree (lh);
16389 }
16390
16391 /* Add an entry to LH's include directory table.  */
16392
16393 static void
16394 add_include_dir (struct line_header *lh, const char *include_dir)
16395 {
16396   /* Grow the array if necessary.  */
16397   if (lh->include_dirs_size == 0)
16398     {
16399       lh->include_dirs_size = 1; /* for testing */
16400       lh->include_dirs = xmalloc (lh->include_dirs_size
16401                                   * sizeof (*lh->include_dirs));
16402     }
16403   else if (lh->num_include_dirs >= lh->include_dirs_size)
16404     {
16405       lh->include_dirs_size *= 2;
16406       lh->include_dirs = xrealloc (lh->include_dirs,
16407                                    (lh->include_dirs_size
16408                                     * sizeof (*lh->include_dirs)));
16409     }
16410
16411   lh->include_dirs[lh->num_include_dirs++] = include_dir;
16412 }
16413
16414 /* Add an entry to LH's file name table.  */
16415
16416 static void
16417 add_file_name (struct line_header *lh,
16418                const char *name,
16419                unsigned int dir_index,
16420                unsigned int mod_time,
16421                unsigned int length)
16422 {
16423   struct file_entry *fe;
16424
16425   /* Grow the array if necessary.  */
16426   if (lh->file_names_size == 0)
16427     {
16428       lh->file_names_size = 1; /* for testing */
16429       lh->file_names = xmalloc (lh->file_names_size
16430                                 * sizeof (*lh->file_names));
16431     }
16432   else if (lh->num_file_names >= lh->file_names_size)
16433     {
16434       lh->file_names_size *= 2;
16435       lh->file_names = xrealloc (lh->file_names,
16436                                  (lh->file_names_size
16437                                   * sizeof (*lh->file_names)));
16438     }
16439
16440   fe = &lh->file_names[lh->num_file_names++];
16441   fe->name = name;
16442   fe->dir_index = dir_index;
16443   fe->mod_time = mod_time;
16444   fe->length = length;
16445   fe->included_p = 0;
16446   fe->symtab = NULL;
16447 }
16448
16449 /* A convenience function to find the proper .debug_line section for a
16450    CU.  */
16451
16452 static struct dwarf2_section_info *
16453 get_debug_line_section (struct dwarf2_cu *cu)
16454 {
16455   struct dwarf2_section_info *section;
16456
16457   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
16458      DWO file.  */
16459   if (cu->dwo_unit && cu->per_cu->is_debug_types)
16460     section = &cu->dwo_unit->dwo_file->sections.line;
16461   else if (cu->per_cu->is_dwz)
16462     {
16463       struct dwz_file *dwz = dwarf2_get_dwz_file ();
16464
16465       section = &dwz->line;
16466     }
16467   else
16468     section = &dwarf2_per_objfile->line;
16469
16470   return section;
16471 }
16472
16473 /* Read the statement program header starting at OFFSET in
16474    .debug_line, or .debug_line.dwo.  Return a pointer
16475    to a struct line_header, allocated using xmalloc.
16476
16477    NOTE: the strings in the include directory and file name tables of
16478    the returned object point into the dwarf line section buffer,
16479    and must not be freed.  */
16480
16481 static struct line_header *
16482 dwarf_decode_line_header (unsigned int offset, struct dwarf2_cu *cu)
16483 {
16484   struct cleanup *back_to;
16485   struct line_header *lh;
16486   const gdb_byte *line_ptr;
16487   unsigned int bytes_read, offset_size;
16488   int i;
16489   const char *cur_dir, *cur_file;
16490   struct dwarf2_section_info *section;
16491   bfd *abfd;
16492
16493   section = get_debug_line_section (cu);
16494   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
16495   if (section->buffer == NULL)
16496     {
16497       if (cu->dwo_unit && cu->per_cu->is_debug_types)
16498         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
16499       else
16500         complaint (&symfile_complaints, _("missing .debug_line section"));
16501       return 0;
16502     }
16503
16504   /* We can't do this until we know the section is non-empty.
16505      Only then do we know we have such a section.  */
16506   abfd = get_section_bfd_owner (section);
16507
16508   /* Make sure that at least there's room for the total_length field.
16509      That could be 12 bytes long, but we're just going to fudge that.  */
16510   if (offset + 4 >= section->size)
16511     {
16512       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16513       return 0;
16514     }
16515
16516   lh = xmalloc (sizeof (*lh));
16517   memset (lh, 0, sizeof (*lh));
16518   back_to = make_cleanup ((make_cleanup_ftype *) free_line_header,
16519                           (void *) lh);
16520
16521   line_ptr = section->buffer + offset;
16522
16523   /* Read in the header.  */
16524   lh->total_length =
16525     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
16526                                             &bytes_read, &offset_size);
16527   line_ptr += bytes_read;
16528   if (line_ptr + lh->total_length > (section->buffer + section->size))
16529     {
16530       dwarf2_statement_list_fits_in_line_number_section_complaint ();
16531       do_cleanups (back_to);
16532       return 0;
16533     }
16534   lh->statement_program_end = line_ptr + lh->total_length;
16535   lh->version = read_2_bytes (abfd, line_ptr);
16536   line_ptr += 2;
16537   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
16538   line_ptr += offset_size;
16539   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
16540   line_ptr += 1;
16541   if (lh->version >= 4)
16542     {
16543       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
16544       line_ptr += 1;
16545     }
16546   else
16547     lh->maximum_ops_per_instruction = 1;
16548
16549   if (lh->maximum_ops_per_instruction == 0)
16550     {
16551       lh->maximum_ops_per_instruction = 1;
16552       complaint (&symfile_complaints,
16553                  _("invalid maximum_ops_per_instruction "
16554                    "in `.debug_line' section"));
16555     }
16556
16557   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
16558   line_ptr += 1;
16559   lh->line_base = read_1_signed_byte (abfd, line_ptr);
16560   line_ptr += 1;
16561   lh->line_range = read_1_byte (abfd, line_ptr);
16562   line_ptr += 1;
16563   lh->opcode_base = read_1_byte (abfd, line_ptr);
16564   line_ptr += 1;
16565   lh->standard_opcode_lengths
16566     = xmalloc (lh->opcode_base * sizeof (lh->standard_opcode_lengths[0]));
16567
16568   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
16569   for (i = 1; i < lh->opcode_base; ++i)
16570     {
16571       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
16572       line_ptr += 1;
16573     }
16574
16575   /* Read directory table.  */
16576   while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16577     {
16578       line_ptr += bytes_read;
16579       add_include_dir (lh, cur_dir);
16580     }
16581   line_ptr += bytes_read;
16582
16583   /* Read file name table.  */
16584   while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
16585     {
16586       unsigned int dir_index, mod_time, length;
16587
16588       line_ptr += bytes_read;
16589       dir_index = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16590       line_ptr += bytes_read;
16591       mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16592       line_ptr += bytes_read;
16593       length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16594       line_ptr += bytes_read;
16595
16596       add_file_name (lh, cur_file, dir_index, mod_time, length);
16597     }
16598   line_ptr += bytes_read;
16599   lh->statement_program_start = line_ptr;
16600
16601   if (line_ptr > (section->buffer + section->size))
16602     complaint (&symfile_complaints,
16603                _("line number info header doesn't "
16604                  "fit in `.debug_line' section"));
16605
16606   discard_cleanups (back_to);
16607   return lh;
16608 }
16609
16610 /* Subroutine of dwarf_decode_lines to simplify it.
16611    Return the file name of the psymtab for included file FILE_INDEX
16612    in line header LH of PST.
16613    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
16614    If space for the result is malloc'd, it will be freed by a cleanup.
16615    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
16616
16617    The function creates dangling cleanup registration.  */
16618
16619 static const char *
16620 psymtab_include_file_name (const struct line_header *lh, int file_index,
16621                            const struct partial_symtab *pst,
16622                            const char *comp_dir)
16623 {
16624   const struct file_entry fe = lh->file_names [file_index];
16625   const char *include_name = fe.name;
16626   const char *include_name_to_compare = include_name;
16627   const char *dir_name = NULL;
16628   const char *pst_filename;
16629   char *copied_name = NULL;
16630   int file_is_pst;
16631
16632   if (fe.dir_index)
16633     dir_name = lh->include_dirs[fe.dir_index - 1];
16634
16635   if (!IS_ABSOLUTE_PATH (include_name)
16636       && (dir_name != NULL || comp_dir != NULL))
16637     {
16638       /* Avoid creating a duplicate psymtab for PST.
16639          We do this by comparing INCLUDE_NAME and PST_FILENAME.
16640          Before we do the comparison, however, we need to account
16641          for DIR_NAME and COMP_DIR.
16642          First prepend dir_name (if non-NULL).  If we still don't
16643          have an absolute path prepend comp_dir (if non-NULL).
16644          However, the directory we record in the include-file's
16645          psymtab does not contain COMP_DIR (to match the
16646          corresponding symtab(s)).
16647
16648          Example:
16649
16650          bash$ cd /tmp
16651          bash$ gcc -g ./hello.c
16652          include_name = "hello.c"
16653          dir_name = "."
16654          DW_AT_comp_dir = comp_dir = "/tmp"
16655          DW_AT_name = "./hello.c"  */
16656
16657       if (dir_name != NULL)
16658         {
16659           char *tem = concat (dir_name, SLASH_STRING,
16660                               include_name, (char *)NULL);
16661
16662           make_cleanup (xfree, tem);
16663           include_name = tem;
16664           include_name_to_compare = include_name;
16665         }
16666       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
16667         {
16668           char *tem = concat (comp_dir, SLASH_STRING,
16669                               include_name, (char *)NULL);
16670
16671           make_cleanup (xfree, tem);
16672           include_name_to_compare = tem;
16673         }
16674     }
16675
16676   pst_filename = pst->filename;
16677   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
16678     {
16679       copied_name = concat (pst->dirname, SLASH_STRING,
16680                             pst_filename, (char *)NULL);
16681       pst_filename = copied_name;
16682     }
16683
16684   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
16685
16686   if (copied_name != NULL)
16687     xfree (copied_name);
16688
16689   if (file_is_pst)
16690     return NULL;
16691   return include_name;
16692 }
16693
16694 /* Ignore this record_line request.  */
16695
16696 static void
16697 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
16698 {
16699   return;
16700 }
16701
16702 /* Subroutine of dwarf_decode_lines to simplify it.
16703    Process the line number information in LH.  */
16704
16705 static void
16706 dwarf_decode_lines_1 (struct line_header *lh, const char *comp_dir,
16707                       struct dwarf2_cu *cu, struct partial_symtab *pst)
16708 {
16709   const gdb_byte *line_ptr, *extended_end;
16710   const gdb_byte *line_end;
16711   unsigned int bytes_read, extended_len;
16712   unsigned char op_code, extended_op, adj_opcode;
16713   CORE_ADDR baseaddr;
16714   struct objfile *objfile = cu->objfile;
16715   bfd *abfd = objfile->obfd;
16716   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16717   const int decode_for_pst_p = (pst != NULL);
16718   struct subfile *last_subfile = NULL;
16719   void (*p_record_line) (struct subfile *subfile, int line, CORE_ADDR pc)
16720     = record_line;
16721
16722   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
16723
16724   line_ptr = lh->statement_program_start;
16725   line_end = lh->statement_program_end;
16726
16727   /* Read the statement sequences until there's nothing left.  */
16728   while (line_ptr < line_end)
16729     {
16730       /* state machine registers  */
16731       CORE_ADDR address = 0;
16732       unsigned int file = 1;
16733       unsigned int line = 1;
16734       unsigned int column = 0;
16735       int is_stmt = lh->default_is_stmt;
16736       int basic_block = 0;
16737       int end_sequence = 0;
16738       CORE_ADDR addr;
16739       unsigned char op_index = 0;
16740
16741       if (!decode_for_pst_p && lh->num_file_names >= file)
16742         {
16743           /* Start a subfile for the current file of the state machine.  */
16744           /* lh->include_dirs and lh->file_names are 0-based, but the
16745              directory and file name numbers in the statement program
16746              are 1-based.  */
16747           struct file_entry *fe = &lh->file_names[file - 1];
16748           const char *dir = NULL;
16749
16750           if (fe->dir_index)
16751             dir = lh->include_dirs[fe->dir_index - 1];
16752
16753           dwarf2_start_subfile (fe->name, dir, comp_dir);
16754         }
16755
16756       /* Decode the table.  */
16757       while (!end_sequence)
16758         {
16759           op_code = read_1_byte (abfd, line_ptr);
16760           line_ptr += 1;
16761           if (line_ptr > line_end)
16762             {
16763               dwarf2_debug_line_missing_end_sequence_complaint ();
16764               break;
16765             }
16766
16767           if (op_code >= lh->opcode_base)
16768             {
16769               /* Special operand.  */
16770               adj_opcode = op_code - lh->opcode_base;
16771               address += (((op_index + (adj_opcode / lh->line_range))
16772                            / lh->maximum_ops_per_instruction)
16773                           * lh->minimum_instruction_length);
16774               op_index = ((op_index + (adj_opcode / lh->line_range))
16775                           % lh->maximum_ops_per_instruction);
16776               line += lh->line_base + (adj_opcode % lh->line_range);
16777               if (lh->num_file_names < file || file == 0)
16778                 dwarf2_debug_line_missing_file_complaint ();
16779               /* For now we ignore lines not starting on an
16780                  instruction boundary.  */
16781               else if (op_index == 0)
16782                 {
16783                   lh->file_names[file - 1].included_p = 1;
16784                   if (!decode_for_pst_p && is_stmt)
16785                     {
16786                       if (last_subfile != current_subfile)
16787                         {
16788                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16789                           if (last_subfile)
16790                             (*p_record_line) (last_subfile, 0, addr);
16791                           last_subfile = current_subfile;
16792                         }
16793                       /* Append row to matrix using current values.  */
16794                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16795                       (*p_record_line) (current_subfile, line, addr);
16796                     }
16797                 }
16798               basic_block = 0;
16799             }
16800           else switch (op_code)
16801             {
16802             case DW_LNS_extended_op:
16803               extended_len = read_unsigned_leb128 (abfd, line_ptr,
16804                                                    &bytes_read);
16805               line_ptr += bytes_read;
16806               extended_end = line_ptr + extended_len;
16807               extended_op = read_1_byte (abfd, line_ptr);
16808               line_ptr += 1;
16809               switch (extended_op)
16810                 {
16811                 case DW_LNE_end_sequence:
16812                   p_record_line = record_line;
16813                   end_sequence = 1;
16814                   break;
16815                 case DW_LNE_set_address:
16816                   address = read_address (abfd, line_ptr, cu, &bytes_read);
16817
16818                   if (address == 0 && !dwarf2_per_objfile->has_section_at_zero)
16819                     {
16820                       /* This line table is for a function which has been
16821                          GCd by the linker.  Ignore it.  PR gdb/12528 */
16822
16823                       long line_offset
16824                         = line_ptr - get_debug_line_section (cu)->buffer;
16825
16826                       complaint (&symfile_complaints,
16827                                  _(".debug_line address at offset 0x%lx is 0 "
16828                                    "[in module %s]"),
16829                                  line_offset, objfile_name (objfile));
16830                       p_record_line = noop_record_line;
16831                     }
16832
16833                   op_index = 0;
16834                   line_ptr += bytes_read;
16835                   address += baseaddr;
16836                   break;
16837                 case DW_LNE_define_file:
16838                   {
16839                     const char *cur_file;
16840                     unsigned int dir_index, mod_time, length;
16841
16842                     cur_file = read_direct_string (abfd, line_ptr,
16843                                                    &bytes_read);
16844                     line_ptr += bytes_read;
16845                     dir_index =
16846                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16847                     line_ptr += bytes_read;
16848                     mod_time =
16849                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16850                     line_ptr += bytes_read;
16851                     length =
16852                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16853                     line_ptr += bytes_read;
16854                     add_file_name (lh, cur_file, dir_index, mod_time, length);
16855                   }
16856                   break;
16857                 case DW_LNE_set_discriminator:
16858                   /* The discriminator is not interesting to the debugger;
16859                      just ignore it.  */
16860                   line_ptr = extended_end;
16861                   break;
16862                 default:
16863                   complaint (&symfile_complaints,
16864                              _("mangled .debug_line section"));
16865                   return;
16866                 }
16867               /* Make sure that we parsed the extended op correctly.  If e.g.
16868                  we expected a different address size than the producer used,
16869                  we may have read the wrong number of bytes.  */
16870               if (line_ptr != extended_end)
16871                 {
16872                   complaint (&symfile_complaints,
16873                              _("mangled .debug_line section"));
16874                   return;
16875                 }
16876               break;
16877             case DW_LNS_copy:
16878               if (lh->num_file_names < file || file == 0)
16879                 dwarf2_debug_line_missing_file_complaint ();
16880               else
16881                 {
16882                   lh->file_names[file - 1].included_p = 1;
16883                   if (!decode_for_pst_p && is_stmt)
16884                     {
16885                       if (last_subfile != current_subfile)
16886                         {
16887                           addr = gdbarch_addr_bits_remove (gdbarch, address);
16888                           if (last_subfile)
16889                             (*p_record_line) (last_subfile, 0, addr);
16890                           last_subfile = current_subfile;
16891                         }
16892                       addr = gdbarch_addr_bits_remove (gdbarch, address);
16893                       (*p_record_line) (current_subfile, line, addr);
16894                     }
16895                 }
16896               basic_block = 0;
16897               break;
16898             case DW_LNS_advance_pc:
16899               {
16900                 CORE_ADDR adjust
16901                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16902
16903                 address += (((op_index + adjust)
16904                              / lh->maximum_ops_per_instruction)
16905                             * lh->minimum_instruction_length);
16906                 op_index = ((op_index + adjust)
16907                             % lh->maximum_ops_per_instruction);
16908                 line_ptr += bytes_read;
16909               }
16910               break;
16911             case DW_LNS_advance_line:
16912               line += read_signed_leb128 (abfd, line_ptr, &bytes_read);
16913               line_ptr += bytes_read;
16914               break;
16915             case DW_LNS_set_file:
16916               {
16917                 /* The arrays lh->include_dirs and lh->file_names are
16918                    0-based, but the directory and file name numbers in
16919                    the statement program are 1-based.  */
16920                 struct file_entry *fe;
16921                 const char *dir = NULL;
16922
16923                 file = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16924                 line_ptr += bytes_read;
16925                 if (lh->num_file_names < file || file == 0)
16926                   dwarf2_debug_line_missing_file_complaint ();
16927                 else
16928                   {
16929                     fe = &lh->file_names[file - 1];
16930                     if (fe->dir_index)
16931                       dir = lh->include_dirs[fe->dir_index - 1];
16932                     if (!decode_for_pst_p)
16933                       {
16934                         last_subfile = current_subfile;
16935                         dwarf2_start_subfile (fe->name, dir, comp_dir);
16936                       }
16937                   }
16938               }
16939               break;
16940             case DW_LNS_set_column:
16941               column = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16942               line_ptr += bytes_read;
16943               break;
16944             case DW_LNS_negate_stmt:
16945               is_stmt = (!is_stmt);
16946               break;
16947             case DW_LNS_set_basic_block:
16948               basic_block = 1;
16949               break;
16950             /* Add to the address register of the state machine the
16951                address increment value corresponding to special opcode
16952                255.  I.e., this value is scaled by the minimum
16953                instruction length since special opcode 255 would have
16954                scaled the increment.  */
16955             case DW_LNS_const_add_pc:
16956               {
16957                 CORE_ADDR adjust = (255 - lh->opcode_base) / lh->line_range;
16958
16959                 address += (((op_index + adjust)
16960                              / lh->maximum_ops_per_instruction)
16961                             * lh->minimum_instruction_length);
16962                 op_index = ((op_index + adjust)
16963                             % lh->maximum_ops_per_instruction);
16964               }
16965               break;
16966             case DW_LNS_fixed_advance_pc:
16967               address += read_2_bytes (abfd, line_ptr);
16968               op_index = 0;
16969               line_ptr += 2;
16970               break;
16971             default:
16972               {
16973                 /* Unknown standard opcode, ignore it.  */
16974                 int i;
16975
16976                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
16977                   {
16978                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
16979                     line_ptr += bytes_read;
16980                   }
16981               }
16982             }
16983         }
16984       if (lh->num_file_names < file || file == 0)
16985         dwarf2_debug_line_missing_file_complaint ();
16986       else
16987         {
16988           lh->file_names[file - 1].included_p = 1;
16989           if (!decode_for_pst_p)
16990             {
16991               addr = gdbarch_addr_bits_remove (gdbarch, address);
16992               (*p_record_line) (current_subfile, 0, addr);
16993             }
16994         }
16995     }
16996 }
16997
16998 /* Decode the Line Number Program (LNP) for the given line_header
16999    structure and CU.  The actual information extracted and the type
17000    of structures created from the LNP depends on the value of PST.
17001
17002    1. If PST is NULL, then this procedure uses the data from the program
17003       to create all necessary symbol tables, and their linetables.
17004
17005    2. If PST is not NULL, this procedure reads the program to determine
17006       the list of files included by the unit represented by PST, and
17007       builds all the associated partial symbol tables.
17008
17009    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
17010    It is used for relative paths in the line table.
17011    NOTE: When processing partial symtabs (pst != NULL),
17012    comp_dir == pst->dirname.
17013
17014    NOTE: It is important that psymtabs have the same file name (via strcmp)
17015    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
17016    symtab we don't use it in the name of the psymtabs we create.
17017    E.g. expand_line_sal requires this when finding psymtabs to expand.
17018    A good testcase for this is mb-inline.exp.  */
17019
17020 static void
17021 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
17022                     struct dwarf2_cu *cu, struct partial_symtab *pst,
17023                     int want_line_info)
17024 {
17025   struct objfile *objfile = cu->objfile;
17026   const int decode_for_pst_p = (pst != NULL);
17027   struct subfile *first_subfile = current_subfile;
17028
17029   if (want_line_info)
17030     dwarf_decode_lines_1 (lh, comp_dir, cu, pst);
17031
17032   if (decode_for_pst_p)
17033     {
17034       int file_index;
17035
17036       /* Now that we're done scanning the Line Header Program, we can
17037          create the psymtab of each included file.  */
17038       for (file_index = 0; file_index < lh->num_file_names; file_index++)
17039         if (lh->file_names[file_index].included_p == 1)
17040           {
17041             const char *include_name =
17042               psymtab_include_file_name (lh, file_index, pst, comp_dir);
17043             if (include_name != NULL)
17044               dwarf2_create_include_psymtab (include_name, pst, objfile);
17045           }
17046     }
17047   else
17048     {
17049       /* Make sure a symtab is created for every file, even files
17050          which contain only variables (i.e. no code with associated
17051          line numbers).  */
17052       int i;
17053
17054       for (i = 0; i < lh->num_file_names; i++)
17055         {
17056           const char *dir = NULL;
17057           struct file_entry *fe;
17058
17059           fe = &lh->file_names[i];
17060           if (fe->dir_index)
17061             dir = lh->include_dirs[fe->dir_index - 1];
17062           dwarf2_start_subfile (fe->name, dir, comp_dir);
17063
17064           /* Skip the main file; we don't need it, and it must be
17065              allocated last, so that it will show up before the
17066              non-primary symtabs in the objfile's symtab list.  */
17067           if (current_subfile == first_subfile)
17068             continue;
17069
17070           if (current_subfile->symtab == NULL)
17071             current_subfile->symtab = allocate_symtab (current_subfile->name,
17072                                                        objfile);
17073           fe->symtab = current_subfile->symtab;
17074         }
17075     }
17076 }
17077
17078 /* Start a subfile for DWARF.  FILENAME is the name of the file and
17079    DIRNAME the name of the source directory which contains FILENAME
17080    or NULL if not known.  COMP_DIR is the compilation directory for the
17081    linetable's compilation unit or NULL if not known.
17082    This routine tries to keep line numbers from identical absolute and
17083    relative file names in a common subfile.
17084
17085    Using the `list' example from the GDB testsuite, which resides in
17086    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
17087    of /srcdir/list0.c yields the following debugging information for list0.c:
17088
17089    DW_AT_name:          /srcdir/list0.c
17090    DW_AT_comp_dir:              /compdir
17091    files.files[0].name: list0.h
17092    files.files[0].dir:  /srcdir
17093    files.files[1].name: list0.c
17094    files.files[1].dir:  /srcdir
17095
17096    The line number information for list0.c has to end up in a single
17097    subfile, so that `break /srcdir/list0.c:1' works as expected.
17098    start_subfile will ensure that this happens provided that we pass the
17099    concatenation of files.files[1].dir and files.files[1].name as the
17100    subfile's name.  */
17101
17102 static void
17103 dwarf2_start_subfile (const char *filename, const char *dirname,
17104                       const char *comp_dir)
17105 {
17106   char *copy = NULL;
17107
17108   /* While reading the DIEs, we call start_symtab(DW_AT_name, DW_AT_comp_dir).
17109      `start_symtab' will always pass the contents of DW_AT_comp_dir as
17110      second argument to start_subfile.  To be consistent, we do the
17111      same here.  In order not to lose the line information directory,
17112      we concatenate it to the filename when it makes sense.
17113      Note that the Dwarf3 standard says (speaking of filenames in line
17114      information): ``The directory index is ignored for file names
17115      that represent full path names''.  Thus ignoring dirname in the
17116      `else' branch below isn't an issue.  */
17117
17118   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
17119     {
17120       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
17121       filename = copy;
17122     }
17123
17124   start_subfile (filename, comp_dir);
17125
17126   if (copy != NULL)
17127     xfree (copy);
17128 }
17129
17130 /* Start a symtab for DWARF.
17131    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
17132
17133 static void
17134 dwarf2_start_symtab (struct dwarf2_cu *cu,
17135                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
17136 {
17137   start_symtab (name, comp_dir, low_pc);
17138   record_debugformat ("DWARF 2");
17139   record_producer (cu->producer);
17140
17141   /* We assume that we're processing GCC output.  */
17142   processing_gcc_compilation = 2;
17143
17144   cu->processing_has_namespace_info = 0;
17145 }
17146
17147 static void
17148 var_decode_location (struct attribute *attr, struct symbol *sym,
17149                      struct dwarf2_cu *cu)
17150 {
17151   struct objfile *objfile = cu->objfile;
17152   struct comp_unit_head *cu_header = &cu->header;
17153
17154   /* NOTE drow/2003-01-30: There used to be a comment and some special
17155      code here to turn a symbol with DW_AT_external and a
17156      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
17157      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
17158      with some versions of binutils) where shared libraries could have
17159      relocations against symbols in their debug information - the
17160      minimal symbol would have the right address, but the debug info
17161      would not.  It's no longer necessary, because we will explicitly
17162      apply relocations when we read in the debug information now.  */
17163
17164   /* A DW_AT_location attribute with no contents indicates that a
17165      variable has been optimized away.  */
17166   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
17167     {
17168       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17169       return;
17170     }
17171
17172   /* Handle one degenerate form of location expression specially, to
17173      preserve GDB's previous behavior when section offsets are
17174      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
17175      then mark this symbol as LOC_STATIC.  */
17176
17177   if (attr_form_is_block (attr)
17178       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
17179            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
17180           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
17181               && (DW_BLOCK (attr)->size
17182                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
17183     {
17184       unsigned int dummy;
17185
17186       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
17187         SYMBOL_VALUE_ADDRESS (sym) =
17188           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
17189       else
17190         SYMBOL_VALUE_ADDRESS (sym) =
17191           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
17192       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
17193       fixup_symbol_section (sym, objfile);
17194       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
17195                                               SYMBOL_SECTION (sym));
17196       return;
17197     }
17198
17199   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
17200      expression evaluator, and use LOC_COMPUTED only when necessary
17201      (i.e. when the value of a register or memory location is
17202      referenced, or a thread-local block, etc.).  Then again, it might
17203      not be worthwhile.  I'm assuming that it isn't unless performance
17204      or memory numbers show me otherwise.  */
17205
17206   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
17207
17208   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
17209     cu->has_loclist = 1;
17210 }
17211
17212 /* Given a pointer to a DWARF information entry, figure out if we need
17213    to make a symbol table entry for it, and if so, create a new entry
17214    and return a pointer to it.
17215    If TYPE is NULL, determine symbol type from the die, otherwise
17216    used the passed type.
17217    If SPACE is not NULL, use it to hold the new symbol.  If it is
17218    NULL, allocate a new symbol on the objfile's obstack.  */
17219
17220 static struct symbol *
17221 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
17222                  struct symbol *space)
17223 {
17224   struct objfile *objfile = cu->objfile;
17225   struct symbol *sym = NULL;
17226   const char *name;
17227   struct attribute *attr = NULL;
17228   struct attribute *attr2 = NULL;
17229   CORE_ADDR baseaddr;
17230   struct pending **list_to_add = NULL;
17231
17232   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
17233
17234   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
17235
17236   name = dwarf2_name (die, cu);
17237   if (name)
17238     {
17239       const char *linkagename;
17240       int suppress_add = 0;
17241
17242       if (space)
17243         sym = space;
17244       else
17245         sym = allocate_symbol (objfile);
17246       OBJSTAT (objfile, n_syms++);
17247
17248       /* Cache this symbol's name and the name's demangled form (if any).  */
17249       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
17250       linkagename = dwarf2_physname (name, die, cu);
17251       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
17252
17253       /* Fortran does not have mangling standard and the mangling does differ
17254          between gfortran, iFort etc.  */
17255       if (cu->language == language_fortran
17256           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
17257         symbol_set_demangled_name (&(sym->ginfo),
17258                                    dwarf2_full_name (name, die, cu),
17259                                    NULL);
17260
17261       /* Default assumptions.
17262          Use the passed type or decode it from the die.  */
17263       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17264       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
17265       if (type != NULL)
17266         SYMBOL_TYPE (sym) = type;
17267       else
17268         SYMBOL_TYPE (sym) = die_type (die, cu);
17269       attr = dwarf2_attr (die,
17270                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
17271                           cu);
17272       if (attr)
17273         {
17274           SYMBOL_LINE (sym) = DW_UNSND (attr);
17275         }
17276
17277       attr = dwarf2_attr (die,
17278                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
17279                           cu);
17280       if (attr)
17281         {
17282           int file_index = DW_UNSND (attr);
17283
17284           if (cu->line_header == NULL
17285               || file_index > cu->line_header->num_file_names)
17286             complaint (&symfile_complaints,
17287                        _("file index out of range"));
17288           else if (file_index > 0)
17289             {
17290               struct file_entry *fe;
17291
17292               fe = &cu->line_header->file_names[file_index - 1];
17293               SYMBOL_SYMTAB (sym) = fe->symtab;
17294             }
17295         }
17296
17297       switch (die->tag)
17298         {
17299         case DW_TAG_label:
17300           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
17301           if (attr)
17302             {
17303               SYMBOL_VALUE_ADDRESS (sym) = DW_ADDR (attr) + baseaddr;
17304             }
17305           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
17306           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
17307           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
17308           add_symbol_to_list (sym, cu->list_in_scope);
17309           break;
17310         case DW_TAG_subprogram:
17311           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17312              finish_block.  */
17313           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17314           attr2 = dwarf2_attr (die, DW_AT_external, cu);
17315           if ((attr2 && (DW_UNSND (attr2) != 0))
17316               || cu->language == language_ada)
17317             {
17318               /* Subprograms marked external are stored as a global symbol.
17319                  Ada subprograms, whether marked external or not, are always
17320                  stored as a global symbol, because we want to be able to
17321                  access them globally.  For instance, we want to be able
17322                  to break on a nested subprogram without having to
17323                  specify the context.  */
17324               list_to_add = &global_symbols;
17325             }
17326           else
17327             {
17328               list_to_add = cu->list_in_scope;
17329             }
17330           break;
17331         case DW_TAG_inlined_subroutine:
17332           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
17333              finish_block.  */
17334           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
17335           SYMBOL_INLINED (sym) = 1;
17336           list_to_add = cu->list_in_scope;
17337           break;
17338         case DW_TAG_template_value_param:
17339           suppress_add = 1;
17340           /* Fall through.  */
17341         case DW_TAG_constant:
17342         case DW_TAG_variable:
17343         case DW_TAG_member:
17344           /* Compilation with minimal debug info may result in
17345              variables with missing type entries.  Change the
17346              misleading `void' type to something sensible.  */
17347           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
17348             SYMBOL_TYPE (sym)
17349               = objfile_type (objfile)->nodebug_data_symbol;
17350
17351           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17352           /* In the case of DW_TAG_member, we should only be called for
17353              static const members.  */
17354           if (die->tag == DW_TAG_member)
17355             {
17356               /* dwarf2_add_field uses die_is_declaration,
17357                  so we do the same.  */
17358               gdb_assert (die_is_declaration (die, cu));
17359               gdb_assert (attr);
17360             }
17361           if (attr)
17362             {
17363               dwarf2_const_value (attr, sym, cu);
17364               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17365               if (!suppress_add)
17366                 {
17367                   if (attr2 && (DW_UNSND (attr2) != 0))
17368                     list_to_add = &global_symbols;
17369                   else
17370                     list_to_add = cu->list_in_scope;
17371                 }
17372               break;
17373             }
17374           attr = dwarf2_attr (die, DW_AT_location, cu);
17375           if (attr)
17376             {
17377               var_decode_location (attr, sym, cu);
17378               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17379
17380               /* Fortran explicitly imports any global symbols to the local
17381                  scope by DW_TAG_common_block.  */
17382               if (cu->language == language_fortran && die->parent
17383                   && die->parent->tag == DW_TAG_common_block)
17384                 attr2 = NULL;
17385
17386               if (SYMBOL_CLASS (sym) == LOC_STATIC
17387                   && SYMBOL_VALUE_ADDRESS (sym) == 0
17388                   && !dwarf2_per_objfile->has_section_at_zero)
17389                 {
17390                   /* When a static variable is eliminated by the linker,
17391                      the corresponding debug information is not stripped
17392                      out, but the variable address is set to null;
17393                      do not add such variables into symbol table.  */
17394                 }
17395               else if (attr2 && (DW_UNSND (attr2) != 0))
17396                 {
17397                   /* Workaround gfortran PR debug/40040 - it uses
17398                      DW_AT_location for variables in -fPIC libraries which may
17399                      get overriden by other libraries/executable and get
17400                      a different address.  Resolve it by the minimal symbol
17401                      which may come from inferior's executable using copy
17402                      relocation.  Make this workaround only for gfortran as for
17403                      other compilers GDB cannot guess the minimal symbol
17404                      Fortran mangling kind.  */
17405                   if (cu->language == language_fortran && die->parent
17406                       && die->parent->tag == DW_TAG_module
17407                       && cu->producer
17408                       && strncmp (cu->producer, "GNU Fortran ", 12) == 0)
17409                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17410
17411                   /* A variable with DW_AT_external is never static,
17412                      but it may be block-scoped.  */
17413                   list_to_add = (cu->list_in_scope == &file_symbols
17414                                  ? &global_symbols : cu->list_in_scope);
17415                 }
17416               else
17417                 list_to_add = cu->list_in_scope;
17418             }
17419           else
17420             {
17421               /* We do not know the address of this symbol.
17422                  If it is an external symbol and we have type information
17423                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
17424                  The address of the variable will then be determined from
17425                  the minimal symbol table whenever the variable is
17426                  referenced.  */
17427               attr2 = dwarf2_attr (die, DW_AT_external, cu);
17428
17429               /* Fortran explicitly imports any global symbols to the local
17430                  scope by DW_TAG_common_block.  */
17431               if (cu->language == language_fortran && die->parent
17432                   && die->parent->tag == DW_TAG_common_block)
17433                 {
17434                   /* SYMBOL_CLASS doesn't matter here because
17435                      read_common_block is going to reset it.  */
17436                   if (!suppress_add)
17437                     list_to_add = cu->list_in_scope;
17438                 }
17439               else if (attr2 && (DW_UNSND (attr2) != 0)
17440                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
17441                 {
17442                   /* A variable with DW_AT_external is never static, but it
17443                      may be block-scoped.  */
17444                   list_to_add = (cu->list_in_scope == &file_symbols
17445                                  ? &global_symbols : cu->list_in_scope);
17446
17447                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
17448                 }
17449               else if (!die_is_declaration (die, cu))
17450                 {
17451                   /* Use the default LOC_OPTIMIZED_OUT class.  */
17452                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
17453                   if (!suppress_add)
17454                     list_to_add = cu->list_in_scope;
17455                 }
17456             }
17457           break;
17458         case DW_TAG_formal_parameter:
17459           /* If we are inside a function, mark this as an argument.  If
17460              not, we might be looking at an argument to an inlined function
17461              when we do not have enough information to show inlined frames;
17462              pretend it's a local variable in that case so that the user can
17463              still see it.  */
17464           if (context_stack_depth > 0
17465               && context_stack[context_stack_depth - 1].name != NULL)
17466             SYMBOL_IS_ARGUMENT (sym) = 1;
17467           attr = dwarf2_attr (die, DW_AT_location, cu);
17468           if (attr)
17469             {
17470               var_decode_location (attr, sym, cu);
17471             }
17472           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17473           if (attr)
17474             {
17475               dwarf2_const_value (attr, sym, cu);
17476             }
17477
17478           list_to_add = cu->list_in_scope;
17479           break;
17480         case DW_TAG_unspecified_parameters:
17481           /* From varargs functions; gdb doesn't seem to have any
17482              interest in this information, so just ignore it for now.
17483              (FIXME?) */
17484           break;
17485         case DW_TAG_template_type_param:
17486           suppress_add = 1;
17487           /* Fall through.  */
17488         case DW_TAG_class_type:
17489         case DW_TAG_interface_type:
17490         case DW_TAG_structure_type:
17491         case DW_TAG_union_type:
17492         case DW_TAG_set_type:
17493         case DW_TAG_enumeration_type:
17494           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17495           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
17496
17497           {
17498             /* NOTE: carlton/2003-11-10: C++ and Java class symbols shouldn't
17499                really ever be static objects: otherwise, if you try
17500                to, say, break of a class's method and you're in a file
17501                which doesn't mention that class, it won't work unless
17502                the check for all static symbols in lookup_symbol_aux
17503                saves you.  See the OtherFileClass tests in
17504                gdb.c++/namespace.exp.  */
17505
17506             if (!suppress_add)
17507               {
17508                 list_to_add = (cu->list_in_scope == &file_symbols
17509                                && (cu->language == language_cplus
17510                                    || cu->language == language_java)
17511                                ? &global_symbols : cu->list_in_scope);
17512
17513                 /* The semantics of C++ state that "struct foo {
17514                    ... }" also defines a typedef for "foo".  A Java
17515                    class declaration also defines a typedef for the
17516                    class.  */
17517                 if (cu->language == language_cplus
17518                     || cu->language == language_java
17519                     || cu->language == language_ada)
17520                   {
17521                     /* The symbol's name is already allocated along
17522                        with this objfile, so we don't need to
17523                        duplicate it for the type.  */
17524                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
17525                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
17526                   }
17527               }
17528           }
17529           break;
17530         case DW_TAG_typedef:
17531           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17532           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17533           list_to_add = cu->list_in_scope;
17534           break;
17535         case DW_TAG_base_type:
17536         case DW_TAG_subrange_type:
17537           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17538           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
17539           list_to_add = cu->list_in_scope;
17540           break;
17541         case DW_TAG_enumerator:
17542           attr = dwarf2_attr (die, DW_AT_const_value, cu);
17543           if (attr)
17544             {
17545               dwarf2_const_value (attr, sym, cu);
17546             }
17547           {
17548             /* NOTE: carlton/2003-11-10: See comment above in the
17549                DW_TAG_class_type, etc. block.  */
17550
17551             list_to_add = (cu->list_in_scope == &file_symbols
17552                            && (cu->language == language_cplus
17553                                || cu->language == language_java)
17554                            ? &global_symbols : cu->list_in_scope);
17555           }
17556           break;
17557         case DW_TAG_namespace:
17558           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
17559           list_to_add = &global_symbols;
17560           break;
17561         case DW_TAG_common_block:
17562           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
17563           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
17564           add_symbol_to_list (sym, cu->list_in_scope);
17565           break;
17566         default:
17567           /* Not a tag we recognize.  Hopefully we aren't processing
17568              trash data, but since we must specifically ignore things
17569              we don't recognize, there is nothing else we should do at
17570              this point.  */
17571           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
17572                      dwarf_tag_name (die->tag));
17573           break;
17574         }
17575
17576       if (suppress_add)
17577         {
17578           sym->hash_next = objfile->template_symbols;
17579           objfile->template_symbols = sym;
17580           list_to_add = NULL;
17581         }
17582
17583       if (list_to_add != NULL)
17584         add_symbol_to_list (sym, list_to_add);
17585
17586       /* For the benefit of old versions of GCC, check for anonymous
17587          namespaces based on the demangled name.  */
17588       if (!cu->processing_has_namespace_info
17589           && cu->language == language_cplus)
17590         cp_scan_for_anonymous_namespaces (sym, objfile);
17591     }
17592   return (sym);
17593 }
17594
17595 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
17596
17597 static struct symbol *
17598 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
17599 {
17600   return new_symbol_full (die, type, cu, NULL);
17601 }
17602
17603 /* Given an attr with a DW_FORM_dataN value in host byte order,
17604    zero-extend it as appropriate for the symbol's type.  The DWARF
17605    standard (v4) is not entirely clear about the meaning of using
17606    DW_FORM_dataN for a constant with a signed type, where the type is
17607    wider than the data.  The conclusion of a discussion on the DWARF
17608    list was that this is unspecified.  We choose to always zero-extend
17609    because that is the interpretation long in use by GCC.  */
17610
17611 static gdb_byte *
17612 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
17613                          struct dwarf2_cu *cu, LONGEST *value, int bits)
17614 {
17615   struct objfile *objfile = cu->objfile;
17616   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
17617                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
17618   LONGEST l = DW_UNSND (attr);
17619
17620   if (bits < sizeof (*value) * 8)
17621     {
17622       l &= ((LONGEST) 1 << bits) - 1;
17623       *value = l;
17624     }
17625   else if (bits == sizeof (*value) * 8)
17626     *value = l;
17627   else
17628     {
17629       gdb_byte *bytes = obstack_alloc (obstack, bits / 8);
17630       store_unsigned_integer (bytes, bits / 8, byte_order, l);
17631       return bytes;
17632     }
17633
17634   return NULL;
17635 }
17636
17637 /* Read a constant value from an attribute.  Either set *VALUE, or if
17638    the value does not fit in *VALUE, set *BYTES - either already
17639    allocated on the objfile obstack, or newly allocated on OBSTACK,
17640    or, set *BATON, if we translated the constant to a location
17641    expression.  */
17642
17643 static void
17644 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
17645                          const char *name, struct obstack *obstack,
17646                          struct dwarf2_cu *cu,
17647                          LONGEST *value, const gdb_byte **bytes,
17648                          struct dwarf2_locexpr_baton **baton)
17649 {
17650   struct objfile *objfile = cu->objfile;
17651   struct comp_unit_head *cu_header = &cu->header;
17652   struct dwarf_block *blk;
17653   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
17654                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
17655
17656   *value = 0;
17657   *bytes = NULL;
17658   *baton = NULL;
17659
17660   switch (attr->form)
17661     {
17662     case DW_FORM_addr:
17663     case DW_FORM_GNU_addr_index:
17664       {
17665         gdb_byte *data;
17666
17667         if (TYPE_LENGTH (type) != cu_header->addr_size)
17668           dwarf2_const_value_length_mismatch_complaint (name,
17669                                                         cu_header->addr_size,
17670                                                         TYPE_LENGTH (type));
17671         /* Symbols of this form are reasonably rare, so we just
17672            piggyback on the existing location code rather than writing
17673            a new implementation of symbol_computed_ops.  */
17674         *baton = obstack_alloc (obstack, sizeof (struct dwarf2_locexpr_baton));
17675         (*baton)->per_cu = cu->per_cu;
17676         gdb_assert ((*baton)->per_cu);
17677
17678         (*baton)->size = 2 + cu_header->addr_size;
17679         data = obstack_alloc (obstack, (*baton)->size);
17680         (*baton)->data = data;
17681
17682         data[0] = DW_OP_addr;
17683         store_unsigned_integer (&data[1], cu_header->addr_size,
17684                                 byte_order, DW_ADDR (attr));
17685         data[cu_header->addr_size + 1] = DW_OP_stack_value;
17686       }
17687       break;
17688     case DW_FORM_string:
17689     case DW_FORM_strp:
17690     case DW_FORM_GNU_str_index:
17691     case DW_FORM_GNU_strp_alt:
17692       /* DW_STRING is already allocated on the objfile obstack, point
17693          directly to it.  */
17694       *bytes = (const gdb_byte *) DW_STRING (attr);
17695       break;
17696     case DW_FORM_block1:
17697     case DW_FORM_block2:
17698     case DW_FORM_block4:
17699     case DW_FORM_block:
17700     case DW_FORM_exprloc:
17701       blk = DW_BLOCK (attr);
17702       if (TYPE_LENGTH (type) != blk->size)
17703         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
17704                                                       TYPE_LENGTH (type));
17705       *bytes = blk->data;
17706       break;
17707
17708       /* The DW_AT_const_value attributes are supposed to carry the
17709          symbol's value "represented as it would be on the target
17710          architecture."  By the time we get here, it's already been
17711          converted to host endianness, so we just need to sign- or
17712          zero-extend it as appropriate.  */
17713     case DW_FORM_data1:
17714       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
17715       break;
17716     case DW_FORM_data2:
17717       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
17718       break;
17719     case DW_FORM_data4:
17720       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
17721       break;
17722     case DW_FORM_data8:
17723       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
17724       break;
17725
17726     case DW_FORM_sdata:
17727       *value = DW_SND (attr);
17728       break;
17729
17730     case DW_FORM_udata:
17731       *value = DW_UNSND (attr);
17732       break;
17733
17734     default:
17735       complaint (&symfile_complaints,
17736                  _("unsupported const value attribute form: '%s'"),
17737                  dwarf_form_name (attr->form));
17738       *value = 0;
17739       break;
17740     }
17741 }
17742
17743
17744 /* Copy constant value from an attribute to a symbol.  */
17745
17746 static void
17747 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
17748                     struct dwarf2_cu *cu)
17749 {
17750   struct objfile *objfile = cu->objfile;
17751   struct comp_unit_head *cu_header = &cu->header;
17752   LONGEST value;
17753   const gdb_byte *bytes;
17754   struct dwarf2_locexpr_baton *baton;
17755
17756   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
17757                            SYMBOL_PRINT_NAME (sym),
17758                            &objfile->objfile_obstack, cu,
17759                            &value, &bytes, &baton);
17760
17761   if (baton != NULL)
17762     {
17763       SYMBOL_LOCATION_BATON (sym) = baton;
17764       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
17765     }
17766   else if (bytes != NULL)
17767      {
17768       SYMBOL_VALUE_BYTES (sym) = bytes;
17769       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
17770     }
17771   else
17772     {
17773       SYMBOL_VALUE (sym) = value;
17774       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
17775     }
17776 }
17777
17778 /* Return the type of the die in question using its DW_AT_type attribute.  */
17779
17780 static struct type *
17781 die_type (struct die_info *die, struct dwarf2_cu *cu)
17782 {
17783   struct attribute *type_attr;
17784
17785   type_attr = dwarf2_attr (die, DW_AT_type, cu);
17786   if (!type_attr)
17787     {
17788       /* A missing DW_AT_type represents a void type.  */
17789       return objfile_type (cu->objfile)->builtin_void;
17790     }
17791
17792   return lookup_die_type (die, type_attr, cu);
17793 }
17794
17795 /* True iff CU's producer generates GNAT Ada auxiliary information
17796    that allows to find parallel types through that information instead
17797    of having to do expensive parallel lookups by type name.  */
17798
17799 static int
17800 need_gnat_info (struct dwarf2_cu *cu)
17801 {
17802   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
17803      of GNAT produces this auxiliary information, without any indication
17804      that it is produced.  Part of enhancing the FSF version of GNAT
17805      to produce that information will be to put in place an indicator
17806      that we can use in order to determine whether the descriptive type
17807      info is available or not.  One suggestion that has been made is
17808      to use a new attribute, attached to the CU die.  For now, assume
17809      that the descriptive type info is not available.  */
17810   return 0;
17811 }
17812
17813 /* Return the auxiliary type of the die in question using its
17814    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
17815    attribute is not present.  */
17816
17817 static struct type *
17818 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
17819 {
17820   struct attribute *type_attr;
17821
17822   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
17823   if (!type_attr)
17824     return NULL;
17825
17826   return lookup_die_type (die, type_attr, cu);
17827 }
17828
17829 /* If DIE has a descriptive_type attribute, then set the TYPE's
17830    descriptive type accordingly.  */
17831
17832 static void
17833 set_descriptive_type (struct type *type, struct die_info *die,
17834                       struct dwarf2_cu *cu)
17835 {
17836   struct type *descriptive_type = die_descriptive_type (die, cu);
17837
17838   if (descriptive_type)
17839     {
17840       ALLOCATE_GNAT_AUX_TYPE (type);
17841       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
17842     }
17843 }
17844
17845 /* Return the containing type of the die in question using its
17846    DW_AT_containing_type attribute.  */
17847
17848 static struct type *
17849 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
17850 {
17851   struct attribute *type_attr;
17852
17853   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
17854   if (!type_attr)
17855     error (_("Dwarf Error: Problem turning containing type into gdb type "
17856              "[in module %s]"), objfile_name (cu->objfile));
17857
17858   return lookup_die_type (die, type_attr, cu);
17859 }
17860
17861 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
17862
17863 static struct type *
17864 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
17865 {
17866   struct objfile *objfile = dwarf2_per_objfile->objfile;
17867   char *message, *saved;
17868
17869   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
17870                         objfile_name (objfile),
17871                         cu->header.offset.sect_off,
17872                         die->offset.sect_off);
17873   saved = obstack_copy0 (&objfile->objfile_obstack,
17874                          message, strlen (message));
17875   xfree (message);
17876
17877   return init_type (TYPE_CODE_ERROR, 0, 0, saved, objfile);
17878 }
17879
17880 /* Look up the type of DIE in CU using its type attribute ATTR.
17881    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
17882    DW_AT_containing_type.
17883    If there is no type substitute an error marker.  */
17884
17885 static struct type *
17886 lookup_die_type (struct die_info *die, const struct attribute *attr,
17887                  struct dwarf2_cu *cu)
17888 {
17889   struct objfile *objfile = cu->objfile;
17890   struct type *this_type;
17891
17892   gdb_assert (attr->name == DW_AT_type
17893               || attr->name == DW_AT_GNAT_descriptive_type
17894               || attr->name == DW_AT_containing_type);
17895
17896   /* First see if we have it cached.  */
17897
17898   if (attr->form == DW_FORM_GNU_ref_alt)
17899     {
17900       struct dwarf2_per_cu_data *per_cu;
17901       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17902
17903       per_cu = dwarf2_find_containing_comp_unit (offset, 1, cu->objfile);
17904       this_type = get_die_type_at_offset (offset, per_cu);
17905     }
17906   else if (attr_form_is_ref (attr))
17907     {
17908       sect_offset offset = dwarf2_get_ref_die_offset (attr);
17909
17910       this_type = get_die_type_at_offset (offset, cu->per_cu);
17911     }
17912   else if (attr->form == DW_FORM_ref_sig8)
17913     {
17914       ULONGEST signature = DW_SIGNATURE (attr);
17915
17916       return get_signatured_type (die, signature, cu);
17917     }
17918   else
17919     {
17920       complaint (&symfile_complaints,
17921                  _("Dwarf Error: Bad type attribute %s in DIE"
17922                    " at 0x%x [in module %s]"),
17923                  dwarf_attr_name (attr->name), die->offset.sect_off,
17924                  objfile_name (objfile));
17925       return build_error_marker_type (cu, die);
17926     }
17927
17928   /* If not cached we need to read it in.  */
17929
17930   if (this_type == NULL)
17931     {
17932       struct die_info *type_die = NULL;
17933       struct dwarf2_cu *type_cu = cu;
17934
17935       if (attr_form_is_ref (attr))
17936         type_die = follow_die_ref (die, attr, &type_cu);
17937       if (type_die == NULL)
17938         return build_error_marker_type (cu, die);
17939       /* If we find the type now, it's probably because the type came
17940          from an inter-CU reference and the type's CU got expanded before
17941          ours.  */
17942       this_type = read_type_die (type_die, type_cu);
17943     }
17944
17945   /* If we still don't have a type use an error marker.  */
17946
17947   if (this_type == NULL)
17948     return build_error_marker_type (cu, die);
17949
17950   return this_type;
17951 }
17952
17953 /* Return the type in DIE, CU.
17954    Returns NULL for invalid types.
17955
17956    This first does a lookup in die_type_hash,
17957    and only reads the die in if necessary.
17958
17959    NOTE: This can be called when reading in partial or full symbols.  */
17960
17961 static struct type *
17962 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
17963 {
17964   struct type *this_type;
17965
17966   this_type = get_die_type (die, cu);
17967   if (this_type)
17968     return this_type;
17969
17970   return read_type_die_1 (die, cu);
17971 }
17972
17973 /* Read the type in DIE, CU.
17974    Returns NULL for invalid types.  */
17975
17976 static struct type *
17977 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
17978 {
17979   struct type *this_type = NULL;
17980
17981   switch (die->tag)
17982     {
17983     case DW_TAG_class_type:
17984     case DW_TAG_interface_type:
17985     case DW_TAG_structure_type:
17986     case DW_TAG_union_type:
17987       this_type = read_structure_type (die, cu);
17988       break;
17989     case DW_TAG_enumeration_type:
17990       this_type = read_enumeration_type (die, cu);
17991       break;
17992     case DW_TAG_subprogram:
17993     case DW_TAG_subroutine_type:
17994     case DW_TAG_inlined_subroutine:
17995       this_type = read_subroutine_type (die, cu);
17996       break;
17997     case DW_TAG_array_type:
17998       this_type = read_array_type (die, cu);
17999       break;
18000     case DW_TAG_set_type:
18001       this_type = read_set_type (die, cu);
18002       break;
18003     case DW_TAG_pointer_type:
18004       this_type = read_tag_pointer_type (die, cu);
18005       break;
18006     case DW_TAG_ptr_to_member_type:
18007       this_type = read_tag_ptr_to_member_type (die, cu);
18008       break;
18009     case DW_TAG_reference_type:
18010       this_type = read_tag_reference_type (die, cu);
18011       break;
18012     case DW_TAG_const_type:
18013       this_type = read_tag_const_type (die, cu);
18014       break;
18015     case DW_TAG_volatile_type:
18016       this_type = read_tag_volatile_type (die, cu);
18017       break;
18018     case DW_TAG_restrict_type:
18019       this_type = read_tag_restrict_type (die, cu);
18020       break;
18021     case DW_TAG_string_type:
18022       this_type = read_tag_string_type (die, cu);
18023       break;
18024     case DW_TAG_typedef:
18025       this_type = read_typedef (die, cu);
18026       break;
18027     case DW_TAG_subrange_type:
18028       this_type = read_subrange_type (die, cu);
18029       break;
18030     case DW_TAG_base_type:
18031       this_type = read_base_type (die, cu);
18032       break;
18033     case DW_TAG_unspecified_type:
18034       this_type = read_unspecified_type (die, cu);
18035       break;
18036     case DW_TAG_namespace:
18037       this_type = read_namespace_type (die, cu);
18038       break;
18039     case DW_TAG_module:
18040       this_type = read_module_type (die, cu);
18041       break;
18042     default:
18043       complaint (&symfile_complaints,
18044                  _("unexpected tag in read_type_die: '%s'"),
18045                  dwarf_tag_name (die->tag));
18046       break;
18047     }
18048
18049   return this_type;
18050 }
18051
18052 /* See if we can figure out if the class lives in a namespace.  We do
18053    this by looking for a member function; its demangled name will
18054    contain namespace info, if there is any.
18055    Return the computed name or NULL.
18056    Space for the result is allocated on the objfile's obstack.
18057    This is the full-die version of guess_partial_die_structure_name.
18058    In this case we know DIE has no useful parent.  */
18059
18060 static char *
18061 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
18062 {
18063   struct die_info *spec_die;
18064   struct dwarf2_cu *spec_cu;
18065   struct die_info *child;
18066
18067   spec_cu = cu;
18068   spec_die = die_specification (die, &spec_cu);
18069   if (spec_die != NULL)
18070     {
18071       die = spec_die;
18072       cu = spec_cu;
18073     }
18074
18075   for (child = die->child;
18076        child != NULL;
18077        child = child->sibling)
18078     {
18079       if (child->tag == DW_TAG_subprogram)
18080         {
18081           struct attribute *attr;
18082
18083           attr = dwarf2_attr (child, DW_AT_linkage_name, cu);
18084           if (attr == NULL)
18085             attr = dwarf2_attr (child, DW_AT_MIPS_linkage_name, cu);
18086           if (attr != NULL)
18087             {
18088               char *actual_name
18089                 = language_class_name_from_physname (cu->language_defn,
18090                                                      DW_STRING (attr));
18091               char *name = NULL;
18092
18093               if (actual_name != NULL)
18094                 {
18095                   const char *die_name = dwarf2_name (die, cu);
18096
18097                   if (die_name != NULL
18098                       && strcmp (die_name, actual_name) != 0)
18099                     {
18100                       /* Strip off the class name from the full name.
18101                          We want the prefix.  */
18102                       int die_name_len = strlen (die_name);
18103                       int actual_name_len = strlen (actual_name);
18104
18105                       /* Test for '::' as a sanity check.  */
18106                       if (actual_name_len > die_name_len + 2
18107                           && actual_name[actual_name_len
18108                                          - die_name_len - 1] == ':')
18109                         name =
18110                           obstack_copy0 (&cu->objfile->objfile_obstack,
18111                                          actual_name,
18112                                          actual_name_len - die_name_len - 2);
18113                     }
18114                 }
18115               xfree (actual_name);
18116               return name;
18117             }
18118         }
18119     }
18120
18121   return NULL;
18122 }
18123
18124 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
18125    prefix part in such case.  See
18126    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18127
18128 static char *
18129 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
18130 {
18131   struct attribute *attr;
18132   char *base;
18133
18134   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
18135       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
18136     return NULL;
18137
18138   attr = dwarf2_attr (die, DW_AT_name, cu);
18139   if (attr != NULL && DW_STRING (attr) != NULL)
18140     return NULL;
18141
18142   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18143   if (attr == NULL)
18144     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18145   if (attr == NULL || DW_STRING (attr) == NULL)
18146     return NULL;
18147
18148   /* dwarf2_name had to be already called.  */
18149   gdb_assert (DW_STRING_IS_CANONICAL (attr));
18150
18151   /* Strip the base name, keep any leading namespaces/classes.  */
18152   base = strrchr (DW_STRING (attr), ':');
18153   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
18154     return "";
18155
18156   return obstack_copy0 (&cu->objfile->objfile_obstack,
18157                         DW_STRING (attr), &base[-1] - DW_STRING (attr));
18158 }
18159
18160 /* Return the name of the namespace/class that DIE is defined within,
18161    or "" if we can't tell.  The caller should not xfree the result.
18162
18163    For example, if we're within the method foo() in the following
18164    code:
18165
18166    namespace N {
18167      class C {
18168        void foo () {
18169        }
18170      };
18171    }
18172
18173    then determine_prefix on foo's die will return "N::C".  */
18174
18175 static const char *
18176 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
18177 {
18178   struct die_info *parent, *spec_die;
18179   struct dwarf2_cu *spec_cu;
18180   struct type *parent_type;
18181   char *retval;
18182
18183   if (cu->language != language_cplus && cu->language != language_java
18184       && cu->language != language_fortran)
18185     return "";
18186
18187   retval = anonymous_struct_prefix (die, cu);
18188   if (retval)
18189     return retval;
18190
18191   /* We have to be careful in the presence of DW_AT_specification.
18192      For example, with GCC 3.4, given the code
18193
18194      namespace N {
18195        void foo() {
18196          // Definition of N::foo.
18197        }
18198      }
18199
18200      then we'll have a tree of DIEs like this:
18201
18202      1: DW_TAG_compile_unit
18203        2: DW_TAG_namespace        // N
18204          3: DW_TAG_subprogram     // declaration of N::foo
18205        4: DW_TAG_subprogram       // definition of N::foo
18206             DW_AT_specification   // refers to die #3
18207
18208      Thus, when processing die #4, we have to pretend that we're in
18209      the context of its DW_AT_specification, namely the contex of die
18210      #3.  */
18211   spec_cu = cu;
18212   spec_die = die_specification (die, &spec_cu);
18213   if (spec_die == NULL)
18214     parent = die->parent;
18215   else
18216     {
18217       parent = spec_die->parent;
18218       cu = spec_cu;
18219     }
18220
18221   if (parent == NULL)
18222     return "";
18223   else if (parent->building_fullname)
18224     {
18225       const char *name;
18226       const char *parent_name;
18227
18228       /* It has been seen on RealView 2.2 built binaries,
18229          DW_TAG_template_type_param types actually _defined_ as
18230          children of the parent class:
18231
18232          enum E {};
18233          template class <class Enum> Class{};
18234          Class<enum E> class_e;
18235
18236          1: DW_TAG_class_type (Class)
18237            2: DW_TAG_enumeration_type (E)
18238              3: DW_TAG_enumerator (enum1:0)
18239              3: DW_TAG_enumerator (enum2:1)
18240              ...
18241            2: DW_TAG_template_type_param
18242               DW_AT_type  DW_FORM_ref_udata (E)
18243
18244          Besides being broken debug info, it can put GDB into an
18245          infinite loop.  Consider:
18246
18247          When we're building the full name for Class<E>, we'll start
18248          at Class, and go look over its template type parameters,
18249          finding E.  We'll then try to build the full name of E, and
18250          reach here.  We're now trying to build the full name of E,
18251          and look over the parent DIE for containing scope.  In the
18252          broken case, if we followed the parent DIE of E, we'd again
18253          find Class, and once again go look at its template type
18254          arguments, etc., etc.  Simply don't consider such parent die
18255          as source-level parent of this die (it can't be, the language
18256          doesn't allow it), and break the loop here.  */
18257       name = dwarf2_name (die, cu);
18258       parent_name = dwarf2_name (parent, cu);
18259       complaint (&symfile_complaints,
18260                  _("template param type '%s' defined within parent '%s'"),
18261                  name ? name : "<unknown>",
18262                  parent_name ? parent_name : "<unknown>");
18263       return "";
18264     }
18265   else
18266     switch (parent->tag)
18267       {
18268       case DW_TAG_namespace:
18269         parent_type = read_type_die (parent, cu);
18270         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
18271            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
18272            Work around this problem here.  */
18273         if (cu->language == language_cplus
18274             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
18275           return "";
18276         /* We give a name to even anonymous namespaces.  */
18277         return TYPE_TAG_NAME (parent_type);
18278       case DW_TAG_class_type:
18279       case DW_TAG_interface_type:
18280       case DW_TAG_structure_type:
18281       case DW_TAG_union_type:
18282       case DW_TAG_module:
18283         parent_type = read_type_die (parent, cu);
18284         if (TYPE_TAG_NAME (parent_type) != NULL)
18285           return TYPE_TAG_NAME (parent_type);
18286         else
18287           /* An anonymous structure is only allowed non-static data
18288              members; no typedefs, no member functions, et cetera.
18289              So it does not need a prefix.  */
18290           return "";
18291       case DW_TAG_compile_unit:
18292       case DW_TAG_partial_unit:
18293         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
18294         if (cu->language == language_cplus
18295             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18296             && die->child != NULL
18297             && (die->tag == DW_TAG_class_type
18298                 || die->tag == DW_TAG_structure_type
18299                 || die->tag == DW_TAG_union_type))
18300           {
18301             char *name = guess_full_die_structure_name (die, cu);
18302             if (name != NULL)
18303               return name;
18304           }
18305         return "";
18306       default:
18307         return determine_prefix (parent, cu);
18308       }
18309 }
18310
18311 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
18312    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
18313    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
18314    an obconcat, otherwise allocate storage for the result.  The CU argument is
18315    used to determine the language and hence, the appropriate separator.  */
18316
18317 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
18318
18319 static char *
18320 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
18321                  int physname, struct dwarf2_cu *cu)
18322 {
18323   const char *lead = "";
18324   const char *sep;
18325
18326   if (suffix == NULL || suffix[0] == '\0'
18327       || prefix == NULL || prefix[0] == '\0')
18328     sep = "";
18329   else if (cu->language == language_java)
18330     sep = ".";
18331   else if (cu->language == language_fortran && physname)
18332     {
18333       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
18334          DW_AT_MIPS_linkage_name is preferred and used instead.  */
18335
18336       lead = "__";
18337       sep = "_MOD_";
18338     }
18339   else
18340     sep = "::";
18341
18342   if (prefix == NULL)
18343     prefix = "";
18344   if (suffix == NULL)
18345     suffix = "";
18346
18347   if (obs == NULL)
18348     {
18349       char *retval
18350         = xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1);
18351
18352       strcpy (retval, lead);
18353       strcat (retval, prefix);
18354       strcat (retval, sep);
18355       strcat (retval, suffix);
18356       return retval;
18357     }
18358   else
18359     {
18360       /* We have an obstack.  */
18361       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
18362     }
18363 }
18364
18365 /* Return sibling of die, NULL if no sibling.  */
18366
18367 static struct die_info *
18368 sibling_die (struct die_info *die)
18369 {
18370   return die->sibling;
18371 }
18372
18373 /* Get name of a die, return NULL if not found.  */
18374
18375 static const char *
18376 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
18377                           struct obstack *obstack)
18378 {
18379   if (name && cu->language == language_cplus)
18380     {
18381       char *canon_name = cp_canonicalize_string (name);
18382
18383       if (canon_name != NULL)
18384         {
18385           if (strcmp (canon_name, name) != 0)
18386             name = obstack_copy0 (obstack, canon_name, strlen (canon_name));
18387           xfree (canon_name);
18388         }
18389     }
18390
18391   return name;
18392 }
18393
18394 /* Get name of a die, return NULL if not found.  */
18395
18396 static const char *
18397 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
18398 {
18399   struct attribute *attr;
18400
18401   attr = dwarf2_attr (die, DW_AT_name, cu);
18402   if ((!attr || !DW_STRING (attr))
18403       && die->tag != DW_TAG_class_type
18404       && die->tag != DW_TAG_interface_type
18405       && die->tag != DW_TAG_structure_type
18406       && die->tag != DW_TAG_union_type)
18407     return NULL;
18408
18409   switch (die->tag)
18410     {
18411     case DW_TAG_compile_unit:
18412     case DW_TAG_partial_unit:
18413       /* Compilation units have a DW_AT_name that is a filename, not
18414          a source language identifier.  */
18415     case DW_TAG_enumeration_type:
18416     case DW_TAG_enumerator:
18417       /* These tags always have simple identifiers already; no need
18418          to canonicalize them.  */
18419       return DW_STRING (attr);
18420
18421     case DW_TAG_subprogram:
18422       /* Java constructors will all be named "<init>", so return
18423          the class name when we see this special case.  */
18424       if (cu->language == language_java
18425           && DW_STRING (attr) != NULL
18426           && strcmp (DW_STRING (attr), "<init>") == 0)
18427         {
18428           struct dwarf2_cu *spec_cu = cu;
18429           struct die_info *spec_die;
18430
18431           /* GCJ will output '<init>' for Java constructor names.
18432              For this special case, return the name of the parent class.  */
18433
18434           /* GCJ may output suprogram DIEs with AT_specification set.
18435              If so, use the name of the specified DIE.  */
18436           spec_die = die_specification (die, &spec_cu);
18437           if (spec_die != NULL)
18438             return dwarf2_name (spec_die, spec_cu);
18439
18440           do
18441             {
18442               die = die->parent;
18443               if (die->tag == DW_TAG_class_type)
18444                 return dwarf2_name (die, cu);
18445             }
18446           while (die->tag != DW_TAG_compile_unit
18447                  && die->tag != DW_TAG_partial_unit);
18448         }
18449       break;
18450
18451     case DW_TAG_class_type:
18452     case DW_TAG_interface_type:
18453     case DW_TAG_structure_type:
18454     case DW_TAG_union_type:
18455       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
18456          structures or unions.  These were of the form "._%d" in GCC 4.1,
18457          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
18458          and GCC 4.4.  We work around this problem by ignoring these.  */
18459       if (attr && DW_STRING (attr)
18460           && (strncmp (DW_STRING (attr), "._", 2) == 0
18461               || strncmp (DW_STRING (attr), "<anonymous", 10) == 0))
18462         return NULL;
18463
18464       /* GCC might emit a nameless typedef that has a linkage name.  See
18465          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18466       if (!attr || DW_STRING (attr) == NULL)
18467         {
18468           char *demangled = NULL;
18469
18470           attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
18471           if (attr == NULL)
18472             attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
18473
18474           if (attr == NULL || DW_STRING (attr) == NULL)
18475             return NULL;
18476
18477           /* Avoid demangling DW_STRING (attr) the second time on a second
18478              call for the same DIE.  */
18479           if (!DW_STRING_IS_CANONICAL (attr))
18480             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
18481
18482           if (demangled)
18483             {
18484               char *base;
18485
18486               /* FIXME: we already did this for the partial symbol... */
18487               DW_STRING (attr) = obstack_copy0 (&cu->objfile->objfile_obstack,
18488                                                 demangled, strlen (demangled));
18489               DW_STRING_IS_CANONICAL (attr) = 1;
18490               xfree (demangled);
18491
18492               /* Strip any leading namespaces/classes, keep only the base name.
18493                  DW_AT_name for named DIEs does not contain the prefixes.  */
18494               base = strrchr (DW_STRING (attr), ':');
18495               if (base && base > DW_STRING (attr) && base[-1] == ':')
18496                 return &base[1];
18497               else
18498                 return DW_STRING (attr);
18499             }
18500         }
18501       break;
18502
18503     default:
18504       break;
18505     }
18506
18507   if (!DW_STRING_IS_CANONICAL (attr))
18508     {
18509       DW_STRING (attr)
18510         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
18511                                     &cu->objfile->objfile_obstack);
18512       DW_STRING_IS_CANONICAL (attr) = 1;
18513     }
18514   return DW_STRING (attr);
18515 }
18516
18517 /* Return the die that this die in an extension of, or NULL if there
18518    is none.  *EXT_CU is the CU containing DIE on input, and the CU
18519    containing the return value on output.  */
18520
18521 static struct die_info *
18522 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
18523 {
18524   struct attribute *attr;
18525
18526   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
18527   if (attr == NULL)
18528     return NULL;
18529
18530   return follow_die_ref (die, attr, ext_cu);
18531 }
18532
18533 /* Convert a DIE tag into its string name.  */
18534
18535 static const char *
18536 dwarf_tag_name (unsigned tag)
18537 {
18538   const char *name = get_DW_TAG_name (tag);
18539
18540   if (name == NULL)
18541     return "DW_TAG_<unknown>";
18542
18543   return name;
18544 }
18545
18546 /* Convert a DWARF attribute code into its string name.  */
18547
18548 static const char *
18549 dwarf_attr_name (unsigned attr)
18550 {
18551   const char *name;
18552
18553 #ifdef MIPS /* collides with DW_AT_HP_block_index */
18554   if (attr == DW_AT_MIPS_fde)
18555     return "DW_AT_MIPS_fde";
18556 #else
18557   if (attr == DW_AT_HP_block_index)
18558     return "DW_AT_HP_block_index";
18559 #endif
18560
18561   name = get_DW_AT_name (attr);
18562
18563   if (name == NULL)
18564     return "DW_AT_<unknown>";
18565
18566   return name;
18567 }
18568
18569 /* Convert a DWARF value form code into its string name.  */
18570
18571 static const char *
18572 dwarf_form_name (unsigned form)
18573 {
18574   const char *name = get_DW_FORM_name (form);
18575
18576   if (name == NULL)
18577     return "DW_FORM_<unknown>";
18578
18579   return name;
18580 }
18581
18582 static char *
18583 dwarf_bool_name (unsigned mybool)
18584 {
18585   if (mybool)
18586     return "TRUE";
18587   else
18588     return "FALSE";
18589 }
18590
18591 /* Convert a DWARF type code into its string name.  */
18592
18593 static const char *
18594 dwarf_type_encoding_name (unsigned enc)
18595 {
18596   const char *name = get_DW_ATE_name (enc);
18597
18598   if (name == NULL)
18599     return "DW_ATE_<unknown>";
18600
18601   return name;
18602 }
18603
18604 static void
18605 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
18606 {
18607   unsigned int i;
18608
18609   print_spaces (indent, f);
18610   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
18611            dwarf_tag_name (die->tag), die->abbrev, die->offset.sect_off);
18612
18613   if (die->parent != NULL)
18614     {
18615       print_spaces (indent, f);
18616       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
18617                           die->parent->offset.sect_off);
18618     }
18619
18620   print_spaces (indent, f);
18621   fprintf_unfiltered (f, "  has children: %s\n",
18622            dwarf_bool_name (die->child != NULL));
18623
18624   print_spaces (indent, f);
18625   fprintf_unfiltered (f, "  attributes:\n");
18626
18627   for (i = 0; i < die->num_attrs; ++i)
18628     {
18629       print_spaces (indent, f);
18630       fprintf_unfiltered (f, "    %s (%s) ",
18631                dwarf_attr_name (die->attrs[i].name),
18632                dwarf_form_name (die->attrs[i].form));
18633
18634       switch (die->attrs[i].form)
18635         {
18636         case DW_FORM_addr:
18637         case DW_FORM_GNU_addr_index:
18638           fprintf_unfiltered (f, "address: ");
18639           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
18640           break;
18641         case DW_FORM_block2:
18642         case DW_FORM_block4:
18643         case DW_FORM_block:
18644         case DW_FORM_block1:
18645           fprintf_unfiltered (f, "block: size %s",
18646                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18647           break;
18648         case DW_FORM_exprloc:
18649           fprintf_unfiltered (f, "expression: size %s",
18650                               pulongest (DW_BLOCK (&die->attrs[i])->size));
18651           break;
18652         case DW_FORM_ref_addr:
18653           fprintf_unfiltered (f, "ref address: ");
18654           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18655           break;
18656         case DW_FORM_GNU_ref_alt:
18657           fprintf_unfiltered (f, "alt ref address: ");
18658           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
18659           break;
18660         case DW_FORM_ref1:
18661         case DW_FORM_ref2:
18662         case DW_FORM_ref4:
18663         case DW_FORM_ref8:
18664         case DW_FORM_ref_udata:
18665           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
18666                               (long) (DW_UNSND (&die->attrs[i])));
18667           break;
18668         case DW_FORM_data1:
18669         case DW_FORM_data2:
18670         case DW_FORM_data4:
18671         case DW_FORM_data8:
18672         case DW_FORM_udata:
18673         case DW_FORM_sdata:
18674           fprintf_unfiltered (f, "constant: %s",
18675                               pulongest (DW_UNSND (&die->attrs[i])));
18676           break;
18677         case DW_FORM_sec_offset:
18678           fprintf_unfiltered (f, "section offset: %s",
18679                               pulongest (DW_UNSND (&die->attrs[i])));
18680           break;
18681         case DW_FORM_ref_sig8:
18682           fprintf_unfiltered (f, "signature: %s",
18683                               hex_string (DW_SIGNATURE (&die->attrs[i])));
18684           break;
18685         case DW_FORM_string:
18686         case DW_FORM_strp:
18687         case DW_FORM_GNU_str_index:
18688         case DW_FORM_GNU_strp_alt:
18689           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
18690                    DW_STRING (&die->attrs[i])
18691                    ? DW_STRING (&die->attrs[i]) : "",
18692                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
18693           break;
18694         case DW_FORM_flag:
18695           if (DW_UNSND (&die->attrs[i]))
18696             fprintf_unfiltered (f, "flag: TRUE");
18697           else
18698             fprintf_unfiltered (f, "flag: FALSE");
18699           break;
18700         case DW_FORM_flag_present:
18701           fprintf_unfiltered (f, "flag: TRUE");
18702           break;
18703         case DW_FORM_indirect:
18704           /* The reader will have reduced the indirect form to
18705              the "base form" so this form should not occur.  */
18706           fprintf_unfiltered (f, 
18707                               "unexpected attribute form: DW_FORM_indirect");
18708           break;
18709         default:
18710           fprintf_unfiltered (f, "unsupported attribute form: %d.",
18711                    die->attrs[i].form);
18712           break;
18713         }
18714       fprintf_unfiltered (f, "\n");
18715     }
18716 }
18717
18718 static void
18719 dump_die_for_error (struct die_info *die)
18720 {
18721   dump_die_shallow (gdb_stderr, 0, die);
18722 }
18723
18724 static void
18725 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
18726 {
18727   int indent = level * 4;
18728
18729   gdb_assert (die != NULL);
18730
18731   if (level >= max_level)
18732     return;
18733
18734   dump_die_shallow (f, indent, die);
18735
18736   if (die->child != NULL)
18737     {
18738       print_spaces (indent, f);
18739       fprintf_unfiltered (f, "  Children:");
18740       if (level + 1 < max_level)
18741         {
18742           fprintf_unfiltered (f, "\n");
18743           dump_die_1 (f, level + 1, max_level, die->child);
18744         }
18745       else
18746         {
18747           fprintf_unfiltered (f,
18748                               " [not printed, max nesting level reached]\n");
18749         }
18750     }
18751
18752   if (die->sibling != NULL && level > 0)
18753     {
18754       dump_die_1 (f, level, max_level, die->sibling);
18755     }
18756 }
18757
18758 /* This is called from the pdie macro in gdbinit.in.
18759    It's not static so gcc will keep a copy callable from gdb.  */
18760
18761 void
18762 dump_die (struct die_info *die, int max_level)
18763 {
18764   dump_die_1 (gdb_stdlog, 0, max_level, die);
18765 }
18766
18767 static void
18768 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
18769 {
18770   void **slot;
18771
18772   slot = htab_find_slot_with_hash (cu->die_hash, die, die->offset.sect_off,
18773                                    INSERT);
18774
18775   *slot = die;
18776 }
18777
18778 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
18779    required kind.  */
18780
18781 static sect_offset
18782 dwarf2_get_ref_die_offset (const struct attribute *attr)
18783 {
18784   sect_offset retval = { DW_UNSND (attr) };
18785
18786   if (attr_form_is_ref (attr))
18787     return retval;
18788
18789   retval.sect_off = 0;
18790   complaint (&symfile_complaints,
18791              _("unsupported die ref attribute form: '%s'"),
18792              dwarf_form_name (attr->form));
18793   return retval;
18794 }
18795
18796 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
18797  * the value held by the attribute is not constant.  */
18798
18799 static LONGEST
18800 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
18801 {
18802   if (attr->form == DW_FORM_sdata)
18803     return DW_SND (attr);
18804   else if (attr->form == DW_FORM_udata
18805            || attr->form == DW_FORM_data1
18806            || attr->form == DW_FORM_data2
18807            || attr->form == DW_FORM_data4
18808            || attr->form == DW_FORM_data8)
18809     return DW_UNSND (attr);
18810   else
18811     {
18812       complaint (&symfile_complaints,
18813                  _("Attribute value is not a constant (%s)"),
18814                  dwarf_form_name (attr->form));
18815       return default_value;
18816     }
18817 }
18818
18819 /* Follow reference or signature attribute ATTR of SRC_DIE.
18820    On entry *REF_CU is the CU of SRC_DIE.
18821    On exit *REF_CU is the CU of the result.  */
18822
18823 static struct die_info *
18824 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
18825                        struct dwarf2_cu **ref_cu)
18826 {
18827   struct die_info *die;
18828
18829   if (attr_form_is_ref (attr))
18830     die = follow_die_ref (src_die, attr, ref_cu);
18831   else if (attr->form == DW_FORM_ref_sig8)
18832     die = follow_die_sig (src_die, attr, ref_cu);
18833   else
18834     {
18835       dump_die_for_error (src_die);
18836       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
18837              objfile_name ((*ref_cu)->objfile));
18838     }
18839
18840   return die;
18841 }
18842
18843 /* Follow reference OFFSET.
18844    On entry *REF_CU is the CU of the source die referencing OFFSET.
18845    On exit *REF_CU is the CU of the result.
18846    Returns NULL if OFFSET is invalid.  */
18847
18848 static struct die_info *
18849 follow_die_offset (sect_offset offset, int offset_in_dwz,
18850                    struct dwarf2_cu **ref_cu)
18851 {
18852   struct die_info temp_die;
18853   struct dwarf2_cu *target_cu, *cu = *ref_cu;
18854
18855   gdb_assert (cu->per_cu != NULL);
18856
18857   target_cu = cu;
18858
18859   if (cu->per_cu->is_debug_types)
18860     {
18861       /* .debug_types CUs cannot reference anything outside their CU.
18862          If they need to, they have to reference a signatured type via
18863          DW_FORM_ref_sig8.  */
18864       if (! offset_in_cu_p (&cu->header, offset))
18865         return NULL;
18866     }
18867   else if (offset_in_dwz != cu->per_cu->is_dwz
18868            || ! offset_in_cu_p (&cu->header, offset))
18869     {
18870       struct dwarf2_per_cu_data *per_cu;
18871
18872       per_cu = dwarf2_find_containing_comp_unit (offset, offset_in_dwz,
18873                                                  cu->objfile);
18874
18875       /* If necessary, add it to the queue and load its DIEs.  */
18876       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
18877         load_full_comp_unit (per_cu, cu->language);
18878
18879       target_cu = per_cu->cu;
18880     }
18881   else if (cu->dies == NULL)
18882     {
18883       /* We're loading full DIEs during partial symbol reading.  */
18884       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
18885       load_full_comp_unit (cu->per_cu, language_minimal);
18886     }
18887
18888   *ref_cu = target_cu;
18889   temp_die.offset = offset;
18890   return htab_find_with_hash (target_cu->die_hash, &temp_die, offset.sect_off);
18891 }
18892
18893 /* Follow reference attribute ATTR of SRC_DIE.
18894    On entry *REF_CU is the CU of SRC_DIE.
18895    On exit *REF_CU is the CU of the result.  */
18896
18897 static struct die_info *
18898 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
18899                 struct dwarf2_cu **ref_cu)
18900 {
18901   sect_offset offset = dwarf2_get_ref_die_offset (attr);
18902   struct dwarf2_cu *cu = *ref_cu;
18903   struct die_info *die;
18904
18905   die = follow_die_offset (offset,
18906                            (attr->form == DW_FORM_GNU_ref_alt
18907                             || cu->per_cu->is_dwz),
18908                            ref_cu);
18909   if (!die)
18910     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
18911            "at 0x%x [in module %s]"),
18912            offset.sect_off, src_die->offset.sect_off,
18913            objfile_name (cu->objfile));
18914
18915   return die;
18916 }
18917
18918 /* Return DWARF block referenced by DW_AT_location of DIE at OFFSET at PER_CU.
18919    Returned value is intended for DW_OP_call*.  Returned
18920    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
18921
18922 struct dwarf2_locexpr_baton
18923 dwarf2_fetch_die_loc_sect_off (sect_offset offset,
18924                                struct dwarf2_per_cu_data *per_cu,
18925                                CORE_ADDR (*get_frame_pc) (void *baton),
18926                                void *baton)
18927 {
18928   struct dwarf2_cu *cu;
18929   struct die_info *die;
18930   struct attribute *attr;
18931   struct dwarf2_locexpr_baton retval;
18932
18933   dw2_setup (per_cu->objfile);
18934
18935   if (per_cu->cu == NULL)
18936     load_cu (per_cu);
18937   cu = per_cu->cu;
18938
18939   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
18940   if (!die)
18941     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
18942            offset.sect_off, objfile_name (per_cu->objfile));
18943
18944   attr = dwarf2_attr (die, DW_AT_location, cu);
18945   if (!attr)
18946     {
18947       /* DWARF: "If there is no such attribute, then there is no effect.".
18948          DATA is ignored if SIZE is 0.  */
18949
18950       retval.data = NULL;
18951       retval.size = 0;
18952     }
18953   else if (attr_form_is_section_offset (attr))
18954     {
18955       struct dwarf2_loclist_baton loclist_baton;
18956       CORE_ADDR pc = (*get_frame_pc) (baton);
18957       size_t size;
18958
18959       fill_in_loclist_baton (cu, &loclist_baton, attr);
18960
18961       retval.data = dwarf2_find_location_expression (&loclist_baton,
18962                                                      &size, pc);
18963       retval.size = size;
18964     }
18965   else
18966     {
18967       if (!attr_form_is_block (attr))
18968         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
18969                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
18970                offset.sect_off, objfile_name (per_cu->objfile));
18971
18972       retval.data = DW_BLOCK (attr)->data;
18973       retval.size = DW_BLOCK (attr)->size;
18974     }
18975   retval.per_cu = cu->per_cu;
18976
18977   age_cached_comp_units ();
18978
18979   return retval;
18980 }
18981
18982 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
18983    offset.  */
18984
18985 struct dwarf2_locexpr_baton
18986 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
18987                              struct dwarf2_per_cu_data *per_cu,
18988                              CORE_ADDR (*get_frame_pc) (void *baton),
18989                              void *baton)
18990 {
18991   sect_offset offset = { per_cu->offset.sect_off + offset_in_cu.cu_off };
18992
18993   return dwarf2_fetch_die_loc_sect_off (offset, per_cu, get_frame_pc, baton);
18994 }
18995
18996 /* Write a constant of a given type as target-ordered bytes into
18997    OBSTACK.  */
18998
18999 static const gdb_byte *
19000 write_constant_as_bytes (struct obstack *obstack,
19001                          enum bfd_endian byte_order,
19002                          struct type *type,
19003                          ULONGEST value,
19004                          LONGEST *len)
19005 {
19006   gdb_byte *result;
19007
19008   *len = TYPE_LENGTH (type);
19009   result = obstack_alloc (obstack, *len);
19010   store_unsigned_integer (result, *len, byte_order, value);
19011
19012   return result;
19013 }
19014
19015 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
19016    pointer to the constant bytes and set LEN to the length of the
19017    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
19018    does not have a DW_AT_const_value, return NULL.  */
19019
19020 const gdb_byte *
19021 dwarf2_fetch_constant_bytes (sect_offset offset,
19022                              struct dwarf2_per_cu_data *per_cu,
19023                              struct obstack *obstack,
19024                              LONGEST *len)
19025 {
19026   struct dwarf2_cu *cu;
19027   struct die_info *die;
19028   struct attribute *attr;
19029   const gdb_byte *result = NULL;
19030   struct type *type;
19031   LONGEST value;
19032   enum bfd_endian byte_order;
19033
19034   dw2_setup (per_cu->objfile);
19035
19036   if (per_cu->cu == NULL)
19037     load_cu (per_cu);
19038   cu = per_cu->cu;
19039
19040   die = follow_die_offset (offset, per_cu->is_dwz, &cu);
19041   if (!die)
19042     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
19043            offset.sect_off, objfile_name (per_cu->objfile));
19044
19045
19046   attr = dwarf2_attr (die, DW_AT_const_value, cu);
19047   if (attr == NULL)
19048     return NULL;
19049
19050   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
19051                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19052
19053   switch (attr->form)
19054     {
19055     case DW_FORM_addr:
19056     case DW_FORM_GNU_addr_index:
19057       {
19058         gdb_byte *tem;
19059
19060         *len = cu->header.addr_size;
19061         tem = obstack_alloc (obstack, *len);
19062         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
19063         result = tem;
19064       }
19065       break;
19066     case DW_FORM_string:
19067     case DW_FORM_strp:
19068     case DW_FORM_GNU_str_index:
19069     case DW_FORM_GNU_strp_alt:
19070       /* DW_STRING is already allocated on the objfile obstack, point
19071          directly to it.  */
19072       result = (const gdb_byte *) DW_STRING (attr);
19073       *len = strlen (DW_STRING (attr));
19074       break;
19075     case DW_FORM_block1:
19076     case DW_FORM_block2:
19077     case DW_FORM_block4:
19078     case DW_FORM_block:
19079     case DW_FORM_exprloc:
19080       result = DW_BLOCK (attr)->data;
19081       *len = DW_BLOCK (attr)->size;
19082       break;
19083
19084       /* The DW_AT_const_value attributes are supposed to carry the
19085          symbol's value "represented as it would be on the target
19086          architecture."  By the time we get here, it's already been
19087          converted to host endianness, so we just need to sign- or
19088          zero-extend it as appropriate.  */
19089     case DW_FORM_data1:
19090       type = die_type (die, cu);
19091       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
19092       if (result == NULL)
19093         result = write_constant_as_bytes (obstack, byte_order,
19094                                           type, value, len);
19095       break;
19096     case DW_FORM_data2:
19097       type = die_type (die, cu);
19098       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
19099       if (result == NULL)
19100         result = write_constant_as_bytes (obstack, byte_order,
19101                                           type, value, len);
19102       break;
19103     case DW_FORM_data4:
19104       type = die_type (die, cu);
19105       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
19106       if (result == NULL)
19107         result = write_constant_as_bytes (obstack, byte_order,
19108                                           type, value, len);
19109       break;
19110     case DW_FORM_data8:
19111       type = die_type (die, cu);
19112       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
19113       if (result == NULL)
19114         result = write_constant_as_bytes (obstack, byte_order,
19115                                           type, value, len);
19116       break;
19117
19118     case DW_FORM_sdata:
19119       type = die_type (die, cu);
19120       result = write_constant_as_bytes (obstack, byte_order,
19121                                         type, DW_SND (attr), len);
19122       break;
19123
19124     case DW_FORM_udata:
19125       type = die_type (die, cu);
19126       result = write_constant_as_bytes (obstack, byte_order,
19127                                         type, DW_UNSND (attr), len);
19128       break;
19129
19130     default:
19131       complaint (&symfile_complaints,
19132                  _("unsupported const value attribute form: '%s'"),
19133                  dwarf_form_name (attr->form));
19134       break;
19135     }
19136
19137   return result;
19138 }
19139
19140 /* Return the type of the DIE at DIE_OFFSET in the CU named by
19141    PER_CU.  */
19142
19143 struct type *
19144 dwarf2_get_die_type (cu_offset die_offset,
19145                      struct dwarf2_per_cu_data *per_cu)
19146 {
19147   sect_offset die_offset_sect;
19148
19149   dw2_setup (per_cu->objfile);
19150
19151   die_offset_sect.sect_off = per_cu->offset.sect_off + die_offset.cu_off;
19152   return get_die_type_at_offset (die_offset_sect, per_cu);
19153 }
19154
19155 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
19156    On entry *REF_CU is the CU of SRC_DIE.
19157    On exit *REF_CU is the CU of the result.
19158    Returns NULL if the referenced DIE isn't found.  */
19159
19160 static struct die_info *
19161 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
19162                   struct dwarf2_cu **ref_cu)
19163 {
19164   struct objfile *objfile = (*ref_cu)->objfile;
19165   struct die_info temp_die;
19166   struct dwarf2_cu *sig_cu;
19167   struct die_info *die;
19168
19169   /* While it might be nice to assert sig_type->type == NULL here,
19170      we can get here for DW_AT_imported_declaration where we need
19171      the DIE not the type.  */
19172
19173   /* If necessary, add it to the queue and load its DIEs.  */
19174
19175   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
19176     read_signatured_type (sig_type);
19177
19178   sig_cu = sig_type->per_cu.cu;
19179   gdb_assert (sig_cu != NULL);
19180   gdb_assert (sig_type->type_offset_in_section.sect_off != 0);
19181   temp_die.offset = sig_type->type_offset_in_section;
19182   die = htab_find_with_hash (sig_cu->die_hash, &temp_die,
19183                              temp_die.offset.sect_off);
19184   if (die)
19185     {
19186       /* For .gdb_index version 7 keep track of included TUs.
19187          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
19188       if (dwarf2_per_objfile->index_table != NULL
19189           && dwarf2_per_objfile->index_table->version <= 7)
19190         {
19191           VEC_safe_push (dwarf2_per_cu_ptr,
19192                          (*ref_cu)->per_cu->imported_symtabs,
19193                          sig_cu->per_cu);
19194         }
19195
19196       *ref_cu = sig_cu;
19197       return die;
19198     }
19199
19200   return NULL;
19201 }
19202
19203 /* Follow signatured type referenced by ATTR in SRC_DIE.
19204    On entry *REF_CU is the CU of SRC_DIE.
19205    On exit *REF_CU is the CU of the result.
19206    The result is the DIE of the type.
19207    If the referenced type cannot be found an error is thrown.  */
19208
19209 static struct die_info *
19210 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
19211                 struct dwarf2_cu **ref_cu)
19212 {
19213   ULONGEST signature = DW_SIGNATURE (attr);
19214   struct signatured_type *sig_type;
19215   struct die_info *die;
19216
19217   gdb_assert (attr->form == DW_FORM_ref_sig8);
19218
19219   sig_type = lookup_signatured_type (*ref_cu, signature);
19220   /* sig_type will be NULL if the signatured type is missing from
19221      the debug info.  */
19222   if (sig_type == NULL)
19223     {
19224       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
19225                " from DIE at 0x%x [in module %s]"),
19226              hex_string (signature), src_die->offset.sect_off,
19227              objfile_name ((*ref_cu)->objfile));
19228     }
19229
19230   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
19231   if (die == NULL)
19232     {
19233       dump_die_for_error (src_die);
19234       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
19235                " from DIE at 0x%x [in module %s]"),
19236              hex_string (signature), src_die->offset.sect_off,
19237              objfile_name ((*ref_cu)->objfile));
19238     }
19239
19240   return die;
19241 }
19242
19243 /* Get the type specified by SIGNATURE referenced in DIE/CU,
19244    reading in and processing the type unit if necessary.  */
19245
19246 static struct type *
19247 get_signatured_type (struct die_info *die, ULONGEST signature,
19248                      struct dwarf2_cu *cu)
19249 {
19250   struct signatured_type *sig_type;
19251   struct dwarf2_cu *type_cu;
19252   struct die_info *type_die;
19253   struct type *type;
19254
19255   sig_type = lookup_signatured_type (cu, signature);
19256   /* sig_type will be NULL if the signatured type is missing from
19257      the debug info.  */
19258   if (sig_type == NULL)
19259     {
19260       complaint (&symfile_complaints,
19261                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
19262                    " from DIE at 0x%x [in module %s]"),
19263                  hex_string (signature), die->offset.sect_off,
19264                  objfile_name (dwarf2_per_objfile->objfile));
19265       return build_error_marker_type (cu, die);
19266     }
19267
19268   /* If we already know the type we're done.  */
19269   if (sig_type->type != NULL)
19270     return sig_type->type;
19271
19272   type_cu = cu;
19273   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
19274   if (type_die != NULL)
19275     {
19276       /* N.B. We need to call get_die_type to ensure only one type for this DIE
19277          is created.  This is important, for example, because for c++ classes
19278          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
19279       type = read_type_die (type_die, type_cu);
19280       if (type == NULL)
19281         {
19282           complaint (&symfile_complaints,
19283                      _("Dwarf Error: Cannot build signatured type %s"
19284                        " referenced from DIE at 0x%x [in module %s]"),
19285                      hex_string (signature), die->offset.sect_off,
19286                      objfile_name (dwarf2_per_objfile->objfile));
19287           type = build_error_marker_type (cu, die);
19288         }
19289     }
19290   else
19291     {
19292       complaint (&symfile_complaints,
19293                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
19294                    " from DIE at 0x%x [in module %s]"),
19295                  hex_string (signature), die->offset.sect_off,
19296                  objfile_name (dwarf2_per_objfile->objfile));
19297       type = build_error_marker_type (cu, die);
19298     }
19299   sig_type->type = type;
19300
19301   return type;
19302 }
19303
19304 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
19305    reading in and processing the type unit if necessary.  */
19306
19307 static struct type *
19308 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
19309                           struct dwarf2_cu *cu) /* ARI: editCase function */
19310 {
19311   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
19312   if (attr_form_is_ref (attr))
19313     {
19314       struct dwarf2_cu *type_cu = cu;
19315       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
19316
19317       return read_type_die (type_die, type_cu);
19318     }
19319   else if (attr->form == DW_FORM_ref_sig8)
19320     {
19321       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
19322     }
19323   else
19324     {
19325       complaint (&symfile_complaints,
19326                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
19327                    " at 0x%x [in module %s]"),
19328                  dwarf_form_name (attr->form), die->offset.sect_off,
19329                  objfile_name (dwarf2_per_objfile->objfile));
19330       return build_error_marker_type (cu, die);
19331     }
19332 }
19333
19334 /* Load the DIEs associated with type unit PER_CU into memory.  */
19335
19336 static void
19337 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
19338 {
19339   struct signatured_type *sig_type;
19340
19341   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
19342   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
19343
19344   /* We have the per_cu, but we need the signatured_type.
19345      Fortunately this is an easy translation.  */
19346   gdb_assert (per_cu->is_debug_types);
19347   sig_type = (struct signatured_type *) per_cu;
19348
19349   gdb_assert (per_cu->cu == NULL);
19350
19351   read_signatured_type (sig_type);
19352
19353   gdb_assert (per_cu->cu != NULL);
19354 }
19355
19356 /* die_reader_func for read_signatured_type.
19357    This is identical to load_full_comp_unit_reader,
19358    but is kept separate for now.  */
19359
19360 static void
19361 read_signatured_type_reader (const struct die_reader_specs *reader,
19362                              const gdb_byte *info_ptr,
19363                              struct die_info *comp_unit_die,
19364                              int has_children,
19365                              void *data)
19366 {
19367   struct dwarf2_cu *cu = reader->cu;
19368
19369   gdb_assert (cu->die_hash == NULL);
19370   cu->die_hash =
19371     htab_create_alloc_ex (cu->header.length / 12,
19372                           die_hash,
19373                           die_eq,
19374                           NULL,
19375                           &cu->comp_unit_obstack,
19376                           hashtab_obstack_allocate,
19377                           dummy_obstack_deallocate);
19378
19379   if (has_children)
19380     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
19381                                                   &info_ptr, comp_unit_die);
19382   cu->dies = comp_unit_die;
19383   /* comp_unit_die is not stored in die_hash, no need.  */
19384
19385   /* We try not to read any attributes in this function, because not
19386      all CUs needed for references have been loaded yet, and symbol
19387      table processing isn't initialized.  But we have to set the CU language,
19388      or we won't be able to build types correctly.
19389      Similarly, if we do not read the producer, we can not apply
19390      producer-specific interpretation.  */
19391   prepare_one_comp_unit (cu, cu->dies, language_minimal);
19392 }
19393
19394 /* Read in a signatured type and build its CU and DIEs.
19395    If the type is a stub for the real type in a DWO file,
19396    read in the real type from the DWO file as well.  */
19397
19398 static void
19399 read_signatured_type (struct signatured_type *sig_type)
19400 {
19401   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
19402
19403   gdb_assert (per_cu->is_debug_types);
19404   gdb_assert (per_cu->cu == NULL);
19405
19406   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
19407                            read_signatured_type_reader, NULL);
19408   sig_type->per_cu.tu_read = 1;
19409 }
19410
19411 /* Decode simple location descriptions.
19412    Given a pointer to a dwarf block that defines a location, compute
19413    the location and return the value.
19414
19415    NOTE drow/2003-11-18: This function is called in two situations
19416    now: for the address of static or global variables (partial symbols
19417    only) and for offsets into structures which are expected to be
19418    (more or less) constant.  The partial symbol case should go away,
19419    and only the constant case should remain.  That will let this
19420    function complain more accurately.  A few special modes are allowed
19421    without complaint for global variables (for instance, global
19422    register values and thread-local values).
19423
19424    A location description containing no operations indicates that the
19425    object is optimized out.  The return value is 0 for that case.
19426    FIXME drow/2003-11-16: No callers check for this case any more; soon all
19427    callers will only want a very basic result and this can become a
19428    complaint.
19429
19430    Note that stack[0] is unused except as a default error return.  */
19431
19432 static CORE_ADDR
19433 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
19434 {
19435   struct objfile *objfile = cu->objfile;
19436   size_t i;
19437   size_t size = blk->size;
19438   const gdb_byte *data = blk->data;
19439   CORE_ADDR stack[64];
19440   int stacki;
19441   unsigned int bytes_read, unsnd;
19442   gdb_byte op;
19443
19444   i = 0;
19445   stacki = 0;
19446   stack[stacki] = 0;
19447   stack[++stacki] = 0;
19448
19449   while (i < size)
19450     {
19451       op = data[i++];
19452       switch (op)
19453         {
19454         case DW_OP_lit0:
19455         case DW_OP_lit1:
19456         case DW_OP_lit2:
19457         case DW_OP_lit3:
19458         case DW_OP_lit4:
19459         case DW_OP_lit5:
19460         case DW_OP_lit6:
19461         case DW_OP_lit7:
19462         case DW_OP_lit8:
19463         case DW_OP_lit9:
19464         case DW_OP_lit10:
19465         case DW_OP_lit11:
19466         case DW_OP_lit12:
19467         case DW_OP_lit13:
19468         case DW_OP_lit14:
19469         case DW_OP_lit15:
19470         case DW_OP_lit16:
19471         case DW_OP_lit17:
19472         case DW_OP_lit18:
19473         case DW_OP_lit19:
19474         case DW_OP_lit20:
19475         case DW_OP_lit21:
19476         case DW_OP_lit22:
19477         case DW_OP_lit23:
19478         case DW_OP_lit24:
19479         case DW_OP_lit25:
19480         case DW_OP_lit26:
19481         case DW_OP_lit27:
19482         case DW_OP_lit28:
19483         case DW_OP_lit29:
19484         case DW_OP_lit30:
19485         case DW_OP_lit31:
19486           stack[++stacki] = op - DW_OP_lit0;
19487           break;
19488
19489         case DW_OP_reg0:
19490         case DW_OP_reg1:
19491         case DW_OP_reg2:
19492         case DW_OP_reg3:
19493         case DW_OP_reg4:
19494         case DW_OP_reg5:
19495         case DW_OP_reg6:
19496         case DW_OP_reg7:
19497         case DW_OP_reg8:
19498         case DW_OP_reg9:
19499         case DW_OP_reg10:
19500         case DW_OP_reg11:
19501         case DW_OP_reg12:
19502         case DW_OP_reg13:
19503         case DW_OP_reg14:
19504         case DW_OP_reg15:
19505         case DW_OP_reg16:
19506         case DW_OP_reg17:
19507         case DW_OP_reg18:
19508         case DW_OP_reg19:
19509         case DW_OP_reg20:
19510         case DW_OP_reg21:
19511         case DW_OP_reg22:
19512         case DW_OP_reg23:
19513         case DW_OP_reg24:
19514         case DW_OP_reg25:
19515         case DW_OP_reg26:
19516         case DW_OP_reg27:
19517         case DW_OP_reg28:
19518         case DW_OP_reg29:
19519         case DW_OP_reg30:
19520         case DW_OP_reg31:
19521           stack[++stacki] = op - DW_OP_reg0;
19522           if (i < size)
19523             dwarf2_complex_location_expr_complaint ();
19524           break;
19525
19526         case DW_OP_regx:
19527           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
19528           i += bytes_read;
19529           stack[++stacki] = unsnd;
19530           if (i < size)
19531             dwarf2_complex_location_expr_complaint ();
19532           break;
19533
19534         case DW_OP_addr:
19535           stack[++stacki] = read_address (objfile->obfd, &data[i],
19536                                           cu, &bytes_read);
19537           i += bytes_read;
19538           break;
19539
19540         case DW_OP_const1u:
19541           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
19542           i += 1;
19543           break;
19544
19545         case DW_OP_const1s:
19546           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
19547           i += 1;
19548           break;
19549
19550         case DW_OP_const2u:
19551           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
19552           i += 2;
19553           break;
19554
19555         case DW_OP_const2s:
19556           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
19557           i += 2;
19558           break;
19559
19560         case DW_OP_const4u:
19561           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
19562           i += 4;
19563           break;
19564
19565         case DW_OP_const4s:
19566           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
19567           i += 4;
19568           break;
19569
19570         case DW_OP_const8u:
19571           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
19572           i += 8;
19573           break;
19574
19575         case DW_OP_constu:
19576           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
19577                                                   &bytes_read);
19578           i += bytes_read;
19579           break;
19580
19581         case DW_OP_consts:
19582           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
19583           i += bytes_read;
19584           break;
19585
19586         case DW_OP_dup:
19587           stack[stacki + 1] = stack[stacki];
19588           stacki++;
19589           break;
19590
19591         case DW_OP_plus:
19592           stack[stacki - 1] += stack[stacki];
19593           stacki--;
19594           break;
19595
19596         case DW_OP_plus_uconst:
19597           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
19598                                                  &bytes_read);
19599           i += bytes_read;
19600           break;
19601
19602         case DW_OP_minus:
19603           stack[stacki - 1] -= stack[stacki];
19604           stacki--;
19605           break;
19606
19607         case DW_OP_deref:
19608           /* If we're not the last op, then we definitely can't encode
19609              this using GDB's address_class enum.  This is valid for partial
19610              global symbols, although the variable's address will be bogus
19611              in the psymtab.  */
19612           if (i < size)
19613             dwarf2_complex_location_expr_complaint ();
19614           break;
19615
19616         case DW_OP_GNU_push_tls_address:
19617           /* The top of the stack has the offset from the beginning
19618              of the thread control block at which the variable is located.  */
19619           /* Nothing should follow this operator, so the top of stack would
19620              be returned.  */
19621           /* This is valid for partial global symbols, but the variable's
19622              address will be bogus in the psymtab.  Make it always at least
19623              non-zero to not look as a variable garbage collected by linker
19624              which have DW_OP_addr 0.  */
19625           if (i < size)
19626             dwarf2_complex_location_expr_complaint ();
19627           stack[stacki]++;
19628           break;
19629
19630         case DW_OP_GNU_uninit:
19631           break;
19632
19633         case DW_OP_GNU_addr_index:
19634         case DW_OP_GNU_const_index:
19635           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
19636                                                          &bytes_read);
19637           i += bytes_read;
19638           break;
19639
19640         default:
19641           {
19642             const char *name = get_DW_OP_name (op);
19643
19644             if (name)
19645               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
19646                          name);
19647             else
19648               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
19649                          op);
19650           }
19651
19652           return (stack[stacki]);
19653         }
19654
19655       /* Enforce maximum stack depth of SIZE-1 to avoid writing
19656          outside of the allocated space.  Also enforce minimum>0.  */
19657       if (stacki >= ARRAY_SIZE (stack) - 1)
19658         {
19659           complaint (&symfile_complaints,
19660                      _("location description stack overflow"));
19661           return 0;
19662         }
19663
19664       if (stacki <= 0)
19665         {
19666           complaint (&symfile_complaints,
19667                      _("location description stack underflow"));
19668           return 0;
19669         }
19670     }
19671   return (stack[stacki]);
19672 }
19673
19674 /* memory allocation interface */
19675
19676 static struct dwarf_block *
19677 dwarf_alloc_block (struct dwarf2_cu *cu)
19678 {
19679   struct dwarf_block *blk;
19680
19681   blk = (struct dwarf_block *)
19682     obstack_alloc (&cu->comp_unit_obstack, sizeof (struct dwarf_block));
19683   return (blk);
19684 }
19685
19686 static struct die_info *
19687 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
19688 {
19689   struct die_info *die;
19690   size_t size = sizeof (struct die_info);
19691
19692   if (num_attrs > 1)
19693     size += (num_attrs - 1) * sizeof (struct attribute);
19694
19695   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
19696   memset (die, 0, sizeof (struct die_info));
19697   return (die);
19698 }
19699
19700 \f
19701 /* Macro support.  */
19702
19703 /* Return file name relative to the compilation directory of file number I in
19704    *LH's file name table.  The result is allocated using xmalloc; the caller is
19705    responsible for freeing it.  */
19706
19707 static char *
19708 file_file_name (int file, struct line_header *lh)
19709 {
19710   /* Is the file number a valid index into the line header's file name
19711      table?  Remember that file numbers start with one, not zero.  */
19712   if (1 <= file && file <= lh->num_file_names)
19713     {
19714       struct file_entry *fe = &lh->file_names[file - 1];
19715
19716       if (IS_ABSOLUTE_PATH (fe->name) || fe->dir_index == 0)
19717         return xstrdup (fe->name);
19718       return concat (lh->include_dirs[fe->dir_index - 1], SLASH_STRING,
19719                      fe->name, NULL);
19720     }
19721   else
19722     {
19723       /* The compiler produced a bogus file number.  We can at least
19724          record the macro definitions made in the file, even if we
19725          won't be able to find the file by name.  */
19726       char fake_name[80];
19727
19728       xsnprintf (fake_name, sizeof (fake_name),
19729                  "<bad macro file number %d>", file);
19730
19731       complaint (&symfile_complaints,
19732                  _("bad file number in macro information (%d)"),
19733                  file);
19734
19735       return xstrdup (fake_name);
19736     }
19737 }
19738
19739 /* Return the full name of file number I in *LH's file name table.
19740    Use COMP_DIR as the name of the current directory of the
19741    compilation.  The result is allocated using xmalloc; the caller is
19742    responsible for freeing it.  */
19743 static char *
19744 file_full_name (int file, struct line_header *lh, const char *comp_dir)
19745 {
19746   /* Is the file number a valid index into the line header's file name
19747      table?  Remember that file numbers start with one, not zero.  */
19748   if (1 <= file && file <= lh->num_file_names)
19749     {
19750       char *relative = file_file_name (file, lh);
19751
19752       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
19753         return relative;
19754       return reconcat (relative, comp_dir, SLASH_STRING, relative, NULL);
19755     }
19756   else
19757     return file_file_name (file, lh);
19758 }
19759
19760
19761 static struct macro_source_file *
19762 macro_start_file (int file, int line,
19763                   struct macro_source_file *current_file,
19764                   const char *comp_dir,
19765                   struct line_header *lh, struct objfile *objfile)
19766 {
19767   /* File name relative to the compilation directory of this source file.  */
19768   char *file_name = file_file_name (file, lh);
19769
19770   if (! current_file)
19771     {
19772       /* Note: We don't create a macro table for this compilation unit
19773          at all until we actually get a filename.  */
19774       struct macro_table *macro_table = get_macro_table (objfile, comp_dir);
19775
19776       /* If we have no current file, then this must be the start_file
19777          directive for the compilation unit's main source file.  */
19778       current_file = macro_set_main (macro_table, file_name);
19779       macro_define_special (macro_table);
19780     }
19781   else
19782     current_file = macro_include (current_file, line, file_name);
19783
19784   xfree (file_name);
19785
19786   return current_file;
19787 }
19788
19789
19790 /* Copy the LEN characters at BUF to a xmalloc'ed block of memory,
19791    followed by a null byte.  */
19792 static char *
19793 copy_string (const char *buf, int len)
19794 {
19795   char *s = xmalloc (len + 1);
19796
19797   memcpy (s, buf, len);
19798   s[len] = '\0';
19799   return s;
19800 }
19801
19802
19803 static const char *
19804 consume_improper_spaces (const char *p, const char *body)
19805 {
19806   if (*p == ' ')
19807     {
19808       complaint (&symfile_complaints,
19809                  _("macro definition contains spaces "
19810                    "in formal argument list:\n`%s'"),
19811                  body);
19812
19813       while (*p == ' ')
19814         p++;
19815     }
19816
19817   return p;
19818 }
19819
19820
19821 static void
19822 parse_macro_definition (struct macro_source_file *file, int line,
19823                         const char *body)
19824 {
19825   const char *p;
19826
19827   /* The body string takes one of two forms.  For object-like macro
19828      definitions, it should be:
19829
19830         <macro name> " " <definition>
19831
19832      For function-like macro definitions, it should be:
19833
19834         <macro name> "() " <definition>
19835      or
19836         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
19837
19838      Spaces may appear only where explicitly indicated, and in the
19839      <definition>.
19840
19841      The Dwarf 2 spec says that an object-like macro's name is always
19842      followed by a space, but versions of GCC around March 2002 omit
19843      the space when the macro's definition is the empty string.
19844
19845      The Dwarf 2 spec says that there should be no spaces between the
19846      formal arguments in a function-like macro's formal argument list,
19847      but versions of GCC around March 2002 include spaces after the
19848      commas.  */
19849
19850
19851   /* Find the extent of the macro name.  The macro name is terminated
19852      by either a space or null character (for an object-like macro) or
19853      an opening paren (for a function-like macro).  */
19854   for (p = body; *p; p++)
19855     if (*p == ' ' || *p == '(')
19856       break;
19857
19858   if (*p == ' ' || *p == '\0')
19859     {
19860       /* It's an object-like macro.  */
19861       int name_len = p - body;
19862       char *name = copy_string (body, name_len);
19863       const char *replacement;
19864
19865       if (*p == ' ')
19866         replacement = body + name_len + 1;
19867       else
19868         {
19869           dwarf2_macro_malformed_definition_complaint (body);
19870           replacement = body + name_len;
19871         }
19872
19873       macro_define_object (file, line, name, replacement);
19874
19875       xfree (name);
19876     }
19877   else if (*p == '(')
19878     {
19879       /* It's a function-like macro.  */
19880       char *name = copy_string (body, p - body);
19881       int argc = 0;
19882       int argv_size = 1;
19883       char **argv = xmalloc (argv_size * sizeof (*argv));
19884
19885       p++;
19886
19887       p = consume_improper_spaces (p, body);
19888
19889       /* Parse the formal argument list.  */
19890       while (*p && *p != ')')
19891         {
19892           /* Find the extent of the current argument name.  */
19893           const char *arg_start = p;
19894
19895           while (*p && *p != ',' && *p != ')' && *p != ' ')
19896             p++;
19897
19898           if (! *p || p == arg_start)
19899             dwarf2_macro_malformed_definition_complaint (body);
19900           else
19901             {
19902               /* Make sure argv has room for the new argument.  */
19903               if (argc >= argv_size)
19904                 {
19905                   argv_size *= 2;
19906                   argv = xrealloc (argv, argv_size * sizeof (*argv));
19907                 }
19908
19909               argv[argc++] = copy_string (arg_start, p - arg_start);
19910             }
19911
19912           p = consume_improper_spaces (p, body);
19913
19914           /* Consume the comma, if present.  */
19915           if (*p == ',')
19916             {
19917               p++;
19918
19919               p = consume_improper_spaces (p, body);
19920             }
19921         }
19922
19923       if (*p == ')')
19924         {
19925           p++;
19926
19927           if (*p == ' ')
19928             /* Perfectly formed definition, no complaints.  */
19929             macro_define_function (file, line, name,
19930                                    argc, (const char **) argv,
19931                                    p + 1);
19932           else if (*p == '\0')
19933             {
19934               /* Complain, but do define it.  */
19935               dwarf2_macro_malformed_definition_complaint (body);
19936               macro_define_function (file, line, name,
19937                                      argc, (const char **) argv,
19938                                      p);
19939             }
19940           else
19941             /* Just complain.  */
19942             dwarf2_macro_malformed_definition_complaint (body);
19943         }
19944       else
19945         /* Just complain.  */
19946         dwarf2_macro_malformed_definition_complaint (body);
19947
19948       xfree (name);
19949       {
19950         int i;
19951
19952         for (i = 0; i < argc; i++)
19953           xfree (argv[i]);
19954       }
19955       xfree (argv);
19956     }
19957   else
19958     dwarf2_macro_malformed_definition_complaint (body);
19959 }
19960
19961 /* Skip some bytes from BYTES according to the form given in FORM.
19962    Returns the new pointer.  */
19963
19964 static const gdb_byte *
19965 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
19966                  enum dwarf_form form,
19967                  unsigned int offset_size,
19968                  struct dwarf2_section_info *section)
19969 {
19970   unsigned int bytes_read;
19971
19972   switch (form)
19973     {
19974     case DW_FORM_data1:
19975     case DW_FORM_flag:
19976       ++bytes;
19977       break;
19978
19979     case DW_FORM_data2:
19980       bytes += 2;
19981       break;
19982
19983     case DW_FORM_data4:
19984       bytes += 4;
19985       break;
19986
19987     case DW_FORM_data8:
19988       bytes += 8;
19989       break;
19990
19991     case DW_FORM_string:
19992       read_direct_string (abfd, bytes, &bytes_read);
19993       bytes += bytes_read;
19994       break;
19995
19996     case DW_FORM_sec_offset:
19997     case DW_FORM_strp:
19998     case DW_FORM_GNU_strp_alt:
19999       bytes += offset_size;
20000       break;
20001
20002     case DW_FORM_block:
20003       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
20004       bytes += bytes_read;
20005       break;
20006
20007     case DW_FORM_block1:
20008       bytes += 1 + read_1_byte (abfd, bytes);
20009       break;
20010     case DW_FORM_block2:
20011       bytes += 2 + read_2_bytes (abfd, bytes);
20012       break;
20013     case DW_FORM_block4:
20014       bytes += 4 + read_4_bytes (abfd, bytes);
20015       break;
20016
20017     case DW_FORM_sdata:
20018     case DW_FORM_udata:
20019     case DW_FORM_GNU_addr_index:
20020     case DW_FORM_GNU_str_index:
20021       bytes = gdb_skip_leb128 (bytes, buffer_end);
20022       if (bytes == NULL)
20023         {
20024           dwarf2_section_buffer_overflow_complaint (section);
20025           return NULL;
20026         }
20027       break;
20028
20029     default:
20030       {
20031       complain:
20032         complaint (&symfile_complaints,
20033                    _("invalid form 0x%x in `%s'"),
20034                    form, get_section_name (section));
20035         return NULL;
20036       }
20037     }
20038
20039   return bytes;
20040 }
20041
20042 /* A helper for dwarf_decode_macros that handles skipping an unknown
20043    opcode.  Returns an updated pointer to the macro data buffer; or,
20044    on error, issues a complaint and returns NULL.  */
20045
20046 static const gdb_byte *
20047 skip_unknown_opcode (unsigned int opcode,
20048                      const gdb_byte **opcode_definitions,
20049                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20050                      bfd *abfd,
20051                      unsigned int offset_size,
20052                      struct dwarf2_section_info *section)
20053 {
20054   unsigned int bytes_read, i;
20055   unsigned long arg;
20056   const gdb_byte *defn;
20057
20058   if (opcode_definitions[opcode] == NULL)
20059     {
20060       complaint (&symfile_complaints,
20061                  _("unrecognized DW_MACFINO opcode 0x%x"),
20062                  opcode);
20063       return NULL;
20064     }
20065
20066   defn = opcode_definitions[opcode];
20067   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
20068   defn += bytes_read;
20069
20070   for (i = 0; i < arg; ++i)
20071     {
20072       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end, defn[i], offset_size,
20073                                  section);
20074       if (mac_ptr == NULL)
20075         {
20076           /* skip_form_bytes already issued the complaint.  */
20077           return NULL;
20078         }
20079     }
20080
20081   return mac_ptr;
20082 }
20083
20084 /* A helper function which parses the header of a macro section.
20085    If the macro section is the extended (for now called "GNU") type,
20086    then this updates *OFFSET_SIZE.  Returns a pointer to just after
20087    the header, or issues a complaint and returns NULL on error.  */
20088
20089 static const gdb_byte *
20090 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
20091                           bfd *abfd,
20092                           const gdb_byte *mac_ptr,
20093                           unsigned int *offset_size,
20094                           int section_is_gnu)
20095 {
20096   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
20097
20098   if (section_is_gnu)
20099     {
20100       unsigned int version, flags;
20101
20102       version = read_2_bytes (abfd, mac_ptr);
20103       if (version != 4)
20104         {
20105           complaint (&symfile_complaints,
20106                      _("unrecognized version `%d' in .debug_macro section"),
20107                      version);
20108           return NULL;
20109         }
20110       mac_ptr += 2;
20111
20112       flags = read_1_byte (abfd, mac_ptr);
20113       ++mac_ptr;
20114       *offset_size = (flags & 1) ? 8 : 4;
20115
20116       if ((flags & 2) != 0)
20117         /* We don't need the line table offset.  */
20118         mac_ptr += *offset_size;
20119
20120       /* Vendor opcode descriptions.  */
20121       if ((flags & 4) != 0)
20122         {
20123           unsigned int i, count;
20124
20125           count = read_1_byte (abfd, mac_ptr);
20126           ++mac_ptr;
20127           for (i = 0; i < count; ++i)
20128             {
20129               unsigned int opcode, bytes_read;
20130               unsigned long arg;
20131
20132               opcode = read_1_byte (abfd, mac_ptr);
20133               ++mac_ptr;
20134               opcode_definitions[opcode] = mac_ptr;
20135               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20136               mac_ptr += bytes_read;
20137               mac_ptr += arg;
20138             }
20139         }
20140     }
20141
20142   return mac_ptr;
20143 }
20144
20145 /* A helper for dwarf_decode_macros that handles the GNU extensions,
20146    including DW_MACRO_GNU_transparent_include.  */
20147
20148 static void
20149 dwarf_decode_macro_bytes (bfd *abfd,
20150                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
20151                           struct macro_source_file *current_file,
20152                           struct line_header *lh, const char *comp_dir,
20153                           struct dwarf2_section_info *section,
20154                           int section_is_gnu, int section_is_dwz,
20155                           unsigned int offset_size,
20156                           struct objfile *objfile,
20157                           htab_t include_hash)
20158 {
20159   enum dwarf_macro_record_type macinfo_type;
20160   int at_commandline;
20161   const gdb_byte *opcode_definitions[256];
20162
20163   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20164                                       &offset_size, section_is_gnu);
20165   if (mac_ptr == NULL)
20166     {
20167       /* We already issued a complaint.  */
20168       return;
20169     }
20170
20171   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
20172      GDB is still reading the definitions from command line.  First
20173      DW_MACINFO_start_file will need to be ignored as it was already executed
20174      to create CURRENT_FILE for the main source holding also the command line
20175      definitions.  On first met DW_MACINFO_start_file this flag is reset to
20176      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
20177
20178   at_commandline = 1;
20179
20180   do
20181     {
20182       /* Do we at least have room for a macinfo type byte?  */
20183       if (mac_ptr >= mac_end)
20184         {
20185           dwarf2_section_buffer_overflow_complaint (section);
20186           break;
20187         }
20188
20189       macinfo_type = read_1_byte (abfd, mac_ptr);
20190       mac_ptr++;
20191
20192       /* Note that we rely on the fact that the corresponding GNU and
20193          DWARF constants are the same.  */
20194       switch (macinfo_type)
20195         {
20196           /* A zero macinfo type indicates the end of the macro
20197              information.  */
20198         case 0:
20199           break;
20200
20201         case DW_MACRO_GNU_define:
20202         case DW_MACRO_GNU_undef:
20203         case DW_MACRO_GNU_define_indirect:
20204         case DW_MACRO_GNU_undef_indirect:
20205         case DW_MACRO_GNU_define_indirect_alt:
20206         case DW_MACRO_GNU_undef_indirect_alt:
20207           {
20208             unsigned int bytes_read;
20209             int line;
20210             const char *body;
20211             int is_define;
20212
20213             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20214             mac_ptr += bytes_read;
20215
20216             if (macinfo_type == DW_MACRO_GNU_define
20217                 || macinfo_type == DW_MACRO_GNU_undef)
20218               {
20219                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
20220                 mac_ptr += bytes_read;
20221               }
20222             else
20223               {
20224                 LONGEST str_offset;
20225
20226                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
20227                 mac_ptr += offset_size;
20228
20229                 if (macinfo_type == DW_MACRO_GNU_define_indirect_alt
20230                     || macinfo_type == DW_MACRO_GNU_undef_indirect_alt
20231                     || section_is_dwz)
20232                   {
20233                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
20234
20235                     body = read_indirect_string_from_dwz (dwz, str_offset);
20236                   }
20237                 else
20238                   body = read_indirect_string_at_offset (abfd, str_offset);
20239               }
20240
20241             is_define = (macinfo_type == DW_MACRO_GNU_define
20242                          || macinfo_type == DW_MACRO_GNU_define_indirect
20243                          || macinfo_type == DW_MACRO_GNU_define_indirect_alt);
20244             if (! current_file)
20245               {
20246                 /* DWARF violation as no main source is present.  */
20247                 complaint (&symfile_complaints,
20248                            _("debug info with no main source gives macro %s "
20249                              "on line %d: %s"),
20250                            is_define ? _("definition") : _("undefinition"),
20251                            line, body);
20252                 break;
20253               }
20254             if ((line == 0 && !at_commandline)
20255                 || (line != 0 && at_commandline))
20256               complaint (&symfile_complaints,
20257                          _("debug info gives %s macro %s with %s line %d: %s"),
20258                          at_commandline ? _("command-line") : _("in-file"),
20259                          is_define ? _("definition") : _("undefinition"),
20260                          line == 0 ? _("zero") : _("non-zero"), line, body);
20261
20262             if (is_define)
20263               parse_macro_definition (current_file, line, body);
20264             else
20265               {
20266                 gdb_assert (macinfo_type == DW_MACRO_GNU_undef
20267                             || macinfo_type == DW_MACRO_GNU_undef_indirect
20268                             || macinfo_type == DW_MACRO_GNU_undef_indirect_alt);
20269                 macro_undef (current_file, line, body);
20270               }
20271           }
20272           break;
20273
20274         case DW_MACRO_GNU_start_file:
20275           {
20276             unsigned int bytes_read;
20277             int line, file;
20278
20279             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20280             mac_ptr += bytes_read;
20281             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20282             mac_ptr += bytes_read;
20283
20284             if ((line == 0 && !at_commandline)
20285                 || (line != 0 && at_commandline))
20286               complaint (&symfile_complaints,
20287                          _("debug info gives source %d included "
20288                            "from %s at %s line %d"),
20289                          file, at_commandline ? _("command-line") : _("file"),
20290                          line == 0 ? _("zero") : _("non-zero"), line);
20291
20292             if (at_commandline)
20293               {
20294                 /* This DW_MACRO_GNU_start_file was executed in the
20295                    pass one.  */
20296                 at_commandline = 0;
20297               }
20298             else
20299               current_file = macro_start_file (file, line,
20300                                                current_file, comp_dir,
20301                                                lh, objfile);
20302           }
20303           break;
20304
20305         case DW_MACRO_GNU_end_file:
20306           if (! current_file)
20307             complaint (&symfile_complaints,
20308                        _("macro debug info has an unmatched "
20309                          "`close_file' directive"));
20310           else
20311             {
20312               current_file = current_file->included_by;
20313               if (! current_file)
20314                 {
20315                   enum dwarf_macro_record_type next_type;
20316
20317                   /* GCC circa March 2002 doesn't produce the zero
20318                      type byte marking the end of the compilation
20319                      unit.  Complain if it's not there, but exit no
20320                      matter what.  */
20321
20322                   /* Do we at least have room for a macinfo type byte?  */
20323                   if (mac_ptr >= mac_end)
20324                     {
20325                       dwarf2_section_buffer_overflow_complaint (section);
20326                       return;
20327                     }
20328
20329                   /* We don't increment mac_ptr here, so this is just
20330                      a look-ahead.  */
20331                   next_type = read_1_byte (abfd, mac_ptr);
20332                   if (next_type != 0)
20333                     complaint (&symfile_complaints,
20334                                _("no terminating 0-type entry for "
20335                                  "macros in `.debug_macinfo' section"));
20336
20337                   return;
20338                 }
20339             }
20340           break;
20341
20342         case DW_MACRO_GNU_transparent_include:
20343         case DW_MACRO_GNU_transparent_include_alt:
20344           {
20345             LONGEST offset;
20346             void **slot;
20347             bfd *include_bfd = abfd;
20348             struct dwarf2_section_info *include_section = section;
20349             struct dwarf2_section_info alt_section;
20350             const gdb_byte *include_mac_end = mac_end;
20351             int is_dwz = section_is_dwz;
20352             const gdb_byte *new_mac_ptr;
20353
20354             offset = read_offset_1 (abfd, mac_ptr, offset_size);
20355             mac_ptr += offset_size;
20356
20357             if (macinfo_type == DW_MACRO_GNU_transparent_include_alt)
20358               {
20359                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
20360
20361                 dwarf2_read_section (dwarf2_per_objfile->objfile,
20362                                      &dwz->macro);
20363
20364                 include_section = &dwz->macro;
20365                 include_bfd = get_section_bfd_owner (include_section);
20366                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
20367                 is_dwz = 1;
20368               }
20369
20370             new_mac_ptr = include_section->buffer + offset;
20371             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
20372
20373             if (*slot != NULL)
20374               {
20375                 /* This has actually happened; see
20376                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
20377                 complaint (&symfile_complaints,
20378                            _("recursive DW_MACRO_GNU_transparent_include in "
20379                              ".debug_macro section"));
20380               }
20381             else
20382               {
20383                 *slot = (void *) new_mac_ptr;
20384
20385                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
20386                                           include_mac_end, current_file,
20387                                           lh, comp_dir,
20388                                           section, section_is_gnu, is_dwz,
20389                                           offset_size, objfile, include_hash);
20390
20391                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
20392               }
20393           }
20394           break;
20395
20396         case DW_MACINFO_vendor_ext:
20397           if (!section_is_gnu)
20398             {
20399               unsigned int bytes_read;
20400               int constant;
20401
20402               constant = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20403               mac_ptr += bytes_read;
20404               read_direct_string (abfd, mac_ptr, &bytes_read);
20405               mac_ptr += bytes_read;
20406
20407               /* We don't recognize any vendor extensions.  */
20408               break;
20409             }
20410           /* FALLTHROUGH */
20411
20412         default:
20413           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20414                                          mac_ptr, mac_end, abfd, offset_size,
20415                                          section);
20416           if (mac_ptr == NULL)
20417             return;
20418           break;
20419         }
20420     } while (macinfo_type != 0);
20421 }
20422
20423 static void
20424 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
20425                      const char *comp_dir, int section_is_gnu)
20426 {
20427   struct objfile *objfile = dwarf2_per_objfile->objfile;
20428   struct line_header *lh = cu->line_header;
20429   bfd *abfd;
20430   const gdb_byte *mac_ptr, *mac_end;
20431   struct macro_source_file *current_file = 0;
20432   enum dwarf_macro_record_type macinfo_type;
20433   unsigned int offset_size = cu->header.offset_size;
20434   const gdb_byte *opcode_definitions[256];
20435   struct cleanup *cleanup;
20436   htab_t include_hash;
20437   void **slot;
20438   struct dwarf2_section_info *section;
20439   const char *section_name;
20440
20441   if (cu->dwo_unit != NULL)
20442     {
20443       if (section_is_gnu)
20444         {
20445           section = &cu->dwo_unit->dwo_file->sections.macro;
20446           section_name = ".debug_macro.dwo";
20447         }
20448       else
20449         {
20450           section = &cu->dwo_unit->dwo_file->sections.macinfo;
20451           section_name = ".debug_macinfo.dwo";
20452         }
20453     }
20454   else
20455     {
20456       if (section_is_gnu)
20457         {
20458           section = &dwarf2_per_objfile->macro;
20459           section_name = ".debug_macro";
20460         }
20461       else
20462         {
20463           section = &dwarf2_per_objfile->macinfo;
20464           section_name = ".debug_macinfo";
20465         }
20466     }
20467
20468   dwarf2_read_section (objfile, section);
20469   if (section->buffer == NULL)
20470     {
20471       complaint (&symfile_complaints, _("missing %s section"), section_name);
20472       return;
20473     }
20474   abfd = get_section_bfd_owner (section);
20475
20476   /* First pass: Find the name of the base filename.
20477      This filename is needed in order to process all macros whose definition
20478      (or undefinition) comes from the command line.  These macros are defined
20479      before the first DW_MACINFO_start_file entry, and yet still need to be
20480      associated to the base file.
20481
20482      To determine the base file name, we scan the macro definitions until we
20483      reach the first DW_MACINFO_start_file entry.  We then initialize
20484      CURRENT_FILE accordingly so that any macro definition found before the
20485      first DW_MACINFO_start_file can still be associated to the base file.  */
20486
20487   mac_ptr = section->buffer + offset;
20488   mac_end = section->buffer + section->size;
20489
20490   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
20491                                       &offset_size, section_is_gnu);
20492   if (mac_ptr == NULL)
20493     {
20494       /* We already issued a complaint.  */
20495       return;
20496     }
20497
20498   do
20499     {
20500       /* Do we at least have room for a macinfo type byte?  */
20501       if (mac_ptr >= mac_end)
20502         {
20503           /* Complaint is printed during the second pass as GDB will probably
20504              stop the first pass earlier upon finding
20505              DW_MACINFO_start_file.  */
20506           break;
20507         }
20508
20509       macinfo_type = read_1_byte (abfd, mac_ptr);
20510       mac_ptr++;
20511
20512       /* Note that we rely on the fact that the corresponding GNU and
20513          DWARF constants are the same.  */
20514       switch (macinfo_type)
20515         {
20516           /* A zero macinfo type indicates the end of the macro
20517              information.  */
20518         case 0:
20519           break;
20520
20521         case DW_MACRO_GNU_define:
20522         case DW_MACRO_GNU_undef:
20523           /* Only skip the data by MAC_PTR.  */
20524           {
20525             unsigned int bytes_read;
20526
20527             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20528             mac_ptr += bytes_read;
20529             read_direct_string (abfd, mac_ptr, &bytes_read);
20530             mac_ptr += bytes_read;
20531           }
20532           break;
20533
20534         case DW_MACRO_GNU_start_file:
20535           {
20536             unsigned int bytes_read;
20537             int line, file;
20538
20539             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20540             mac_ptr += bytes_read;
20541             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20542             mac_ptr += bytes_read;
20543
20544             current_file = macro_start_file (file, line, current_file,
20545                                              comp_dir, lh, objfile);
20546           }
20547           break;
20548
20549         case DW_MACRO_GNU_end_file:
20550           /* No data to skip by MAC_PTR.  */
20551           break;
20552
20553         case DW_MACRO_GNU_define_indirect:
20554         case DW_MACRO_GNU_undef_indirect:
20555         case DW_MACRO_GNU_define_indirect_alt:
20556         case DW_MACRO_GNU_undef_indirect_alt:
20557           {
20558             unsigned int bytes_read;
20559
20560             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20561             mac_ptr += bytes_read;
20562             mac_ptr += offset_size;
20563           }
20564           break;
20565
20566         case DW_MACRO_GNU_transparent_include:
20567         case DW_MACRO_GNU_transparent_include_alt:
20568           /* Note that, according to the spec, a transparent include
20569              chain cannot call DW_MACRO_GNU_start_file.  So, we can just
20570              skip this opcode.  */
20571           mac_ptr += offset_size;
20572           break;
20573
20574         case DW_MACINFO_vendor_ext:
20575           /* Only skip the data by MAC_PTR.  */
20576           if (!section_is_gnu)
20577             {
20578               unsigned int bytes_read;
20579
20580               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
20581               mac_ptr += bytes_read;
20582               read_direct_string (abfd, mac_ptr, &bytes_read);
20583               mac_ptr += bytes_read;
20584             }
20585           /* FALLTHROUGH */
20586
20587         default:
20588           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
20589                                          mac_ptr, mac_end, abfd, offset_size,
20590                                          section);
20591           if (mac_ptr == NULL)
20592             return;
20593           break;
20594         }
20595     } while (macinfo_type != 0 && current_file == NULL);
20596
20597   /* Second pass: Process all entries.
20598
20599      Use the AT_COMMAND_LINE flag to determine whether we are still processing
20600      command-line macro definitions/undefinitions.  This flag is unset when we
20601      reach the first DW_MACINFO_start_file entry.  */
20602
20603   include_hash = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
20604                                     NULL, xcalloc, xfree);
20605   cleanup = make_cleanup_htab_delete (include_hash);
20606   mac_ptr = section->buffer + offset;
20607   slot = htab_find_slot (include_hash, mac_ptr, INSERT);
20608   *slot = (void *) mac_ptr;
20609   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
20610                             current_file, lh, comp_dir, section,
20611                             section_is_gnu, 0,
20612                             offset_size, objfile, include_hash);
20613   do_cleanups (cleanup);
20614 }
20615
20616 /* Check if the attribute's form is a DW_FORM_block*
20617    if so return true else false.  */
20618
20619 static int
20620 attr_form_is_block (const struct attribute *attr)
20621 {
20622   return (attr == NULL ? 0 :
20623       attr->form == DW_FORM_block1
20624       || attr->form == DW_FORM_block2
20625       || attr->form == DW_FORM_block4
20626       || attr->form == DW_FORM_block
20627       || attr->form == DW_FORM_exprloc);
20628 }
20629
20630 /* Return non-zero if ATTR's value is a section offset --- classes
20631    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
20632    You may use DW_UNSND (attr) to retrieve such offsets.
20633
20634    Section 7.5.4, "Attribute Encodings", explains that no attribute
20635    may have a value that belongs to more than one of these classes; it
20636    would be ambiguous if we did, because we use the same forms for all
20637    of them.  */
20638
20639 static int
20640 attr_form_is_section_offset (const struct attribute *attr)
20641 {
20642   return (attr->form == DW_FORM_data4
20643           || attr->form == DW_FORM_data8
20644           || attr->form == DW_FORM_sec_offset);
20645 }
20646
20647 /* Return non-zero if ATTR's value falls in the 'constant' class, or
20648    zero otherwise.  When this function returns true, you can apply
20649    dwarf2_get_attr_constant_value to it.
20650
20651    However, note that for some attributes you must check
20652    attr_form_is_section_offset before using this test.  DW_FORM_data4
20653    and DW_FORM_data8 are members of both the constant class, and of
20654    the classes that contain offsets into other debug sections
20655    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
20656    that, if an attribute's can be either a constant or one of the
20657    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
20658    taken as section offsets, not constants.  */
20659
20660 static int
20661 attr_form_is_constant (const struct attribute *attr)
20662 {
20663   switch (attr->form)
20664     {
20665     case DW_FORM_sdata:
20666     case DW_FORM_udata:
20667     case DW_FORM_data1:
20668     case DW_FORM_data2:
20669     case DW_FORM_data4:
20670     case DW_FORM_data8:
20671       return 1;
20672     default:
20673       return 0;
20674     }
20675 }
20676
20677
20678 /* DW_ADDR is always stored already as sect_offset; despite for the forms
20679    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
20680
20681 static int
20682 attr_form_is_ref (const struct attribute *attr)
20683 {
20684   switch (attr->form)
20685     {
20686     case DW_FORM_ref_addr:
20687     case DW_FORM_ref1:
20688     case DW_FORM_ref2:
20689     case DW_FORM_ref4:
20690     case DW_FORM_ref8:
20691     case DW_FORM_ref_udata:
20692     case DW_FORM_GNU_ref_alt:
20693       return 1;
20694     default:
20695       return 0;
20696     }
20697 }
20698
20699 /* Return the .debug_loc section to use for CU.
20700    For DWO files use .debug_loc.dwo.  */
20701
20702 static struct dwarf2_section_info *
20703 cu_debug_loc_section (struct dwarf2_cu *cu)
20704 {
20705   if (cu->dwo_unit)
20706     return &cu->dwo_unit->dwo_file->sections.loc;
20707   return &dwarf2_per_objfile->loc;
20708 }
20709
20710 /* A helper function that fills in a dwarf2_loclist_baton.  */
20711
20712 static void
20713 fill_in_loclist_baton (struct dwarf2_cu *cu,
20714                        struct dwarf2_loclist_baton *baton,
20715                        const struct attribute *attr)
20716 {
20717   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20718
20719   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20720
20721   baton->per_cu = cu->per_cu;
20722   gdb_assert (baton->per_cu);
20723   /* We don't know how long the location list is, but make sure we
20724      don't run off the edge of the section.  */
20725   baton->size = section->size - DW_UNSND (attr);
20726   baton->data = section->buffer + DW_UNSND (attr);
20727   baton->base_address = cu->base_address;
20728   baton->from_dwo = cu->dwo_unit != NULL;
20729 }
20730
20731 static void
20732 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
20733                              struct dwarf2_cu *cu, int is_block)
20734 {
20735   struct objfile *objfile = dwarf2_per_objfile->objfile;
20736   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
20737
20738   if (attr_form_is_section_offset (attr)
20739       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
20740          the section.  If so, fall through to the complaint in the
20741          other branch.  */
20742       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
20743     {
20744       struct dwarf2_loclist_baton *baton;
20745
20746       baton = obstack_alloc (&objfile->objfile_obstack,
20747                              sizeof (struct dwarf2_loclist_baton));
20748
20749       fill_in_loclist_baton (cu, baton, attr);
20750
20751       if (cu->base_known == 0)
20752         complaint (&symfile_complaints,
20753                    _("Location list used without "
20754                      "specifying the CU base address."));
20755
20756       SYMBOL_ACLASS_INDEX (sym) = (is_block
20757                                    ? dwarf2_loclist_block_index
20758                                    : dwarf2_loclist_index);
20759       SYMBOL_LOCATION_BATON (sym) = baton;
20760     }
20761   else
20762     {
20763       struct dwarf2_locexpr_baton *baton;
20764
20765       baton = obstack_alloc (&objfile->objfile_obstack,
20766                              sizeof (struct dwarf2_locexpr_baton));
20767       baton->per_cu = cu->per_cu;
20768       gdb_assert (baton->per_cu);
20769
20770       if (attr_form_is_block (attr))
20771         {
20772           /* Note that we're just copying the block's data pointer
20773              here, not the actual data.  We're still pointing into the
20774              info_buffer for SYM's objfile; right now we never release
20775              that buffer, but when we do clean up properly this may
20776              need to change.  */
20777           baton->size = DW_BLOCK (attr)->size;
20778           baton->data = DW_BLOCK (attr)->data;
20779         }
20780       else
20781         {
20782           dwarf2_invalid_attrib_class_complaint ("location description",
20783                                                  SYMBOL_NATURAL_NAME (sym));
20784           baton->size = 0;
20785         }
20786
20787       SYMBOL_ACLASS_INDEX (sym) = (is_block
20788                                    ? dwarf2_locexpr_block_index
20789                                    : dwarf2_locexpr_index);
20790       SYMBOL_LOCATION_BATON (sym) = baton;
20791     }
20792 }
20793
20794 /* Return the OBJFILE associated with the compilation unit CU.  If CU
20795    came from a separate debuginfo file, then the master objfile is
20796    returned.  */
20797
20798 struct objfile *
20799 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
20800 {
20801   struct objfile *objfile = per_cu->objfile;
20802
20803   /* Return the master objfile, so that we can report and look up the
20804      correct file containing this variable.  */
20805   if (objfile->separate_debug_objfile_backlink)
20806     objfile = objfile->separate_debug_objfile_backlink;
20807
20808   return objfile;
20809 }
20810
20811 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
20812    (CU_HEADERP is unused in such case) or prepare a temporary copy at
20813    CU_HEADERP first.  */
20814
20815 static const struct comp_unit_head *
20816 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
20817                        struct dwarf2_per_cu_data *per_cu)
20818 {
20819   const gdb_byte *info_ptr;
20820
20821   if (per_cu->cu)
20822     return &per_cu->cu->header;
20823
20824   info_ptr = per_cu->section->buffer + per_cu->offset.sect_off;
20825
20826   memset (cu_headerp, 0, sizeof (*cu_headerp));
20827   read_comp_unit_head (cu_headerp, info_ptr, per_cu->objfile->obfd);
20828
20829   return cu_headerp;
20830 }
20831
20832 /* Return the address size given in the compilation unit header for CU.  */
20833
20834 int
20835 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
20836 {
20837   struct comp_unit_head cu_header_local;
20838   const struct comp_unit_head *cu_headerp;
20839
20840   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20841
20842   return cu_headerp->addr_size;
20843 }
20844
20845 /* Return the offset size given in the compilation unit header for CU.  */
20846
20847 int
20848 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
20849 {
20850   struct comp_unit_head cu_header_local;
20851   const struct comp_unit_head *cu_headerp;
20852
20853   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20854
20855   return cu_headerp->offset_size;
20856 }
20857
20858 /* See its dwarf2loc.h declaration.  */
20859
20860 int
20861 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
20862 {
20863   struct comp_unit_head cu_header_local;
20864   const struct comp_unit_head *cu_headerp;
20865
20866   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
20867
20868   if (cu_headerp->version == 2)
20869     return cu_headerp->addr_size;
20870   else
20871     return cu_headerp->offset_size;
20872 }
20873
20874 /* Return the text offset of the CU.  The returned offset comes from
20875    this CU's objfile.  If this objfile came from a separate debuginfo
20876    file, then the offset may be different from the corresponding
20877    offset in the parent objfile.  */
20878
20879 CORE_ADDR
20880 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
20881 {
20882   struct objfile *objfile = per_cu->objfile;
20883
20884   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20885 }
20886
20887 /* Locate the .debug_info compilation unit from CU's objfile which contains
20888    the DIE at OFFSET.  Raises an error on failure.  */
20889
20890 static struct dwarf2_per_cu_data *
20891 dwarf2_find_containing_comp_unit (sect_offset offset,
20892                                   unsigned int offset_in_dwz,
20893                                   struct objfile *objfile)
20894 {
20895   struct dwarf2_per_cu_data *this_cu;
20896   int low, high;
20897   const sect_offset *cu_off;
20898
20899   low = 0;
20900   high = dwarf2_per_objfile->n_comp_units - 1;
20901   while (high > low)
20902     {
20903       struct dwarf2_per_cu_data *mid_cu;
20904       int mid = low + (high - low) / 2;
20905
20906       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
20907       cu_off = &mid_cu->offset;
20908       if (mid_cu->is_dwz > offset_in_dwz
20909           || (mid_cu->is_dwz == offset_in_dwz
20910               && cu_off->sect_off >= offset.sect_off))
20911         high = mid;
20912       else
20913         low = mid + 1;
20914     }
20915   gdb_assert (low == high);
20916   this_cu = dwarf2_per_objfile->all_comp_units[low];
20917   cu_off = &this_cu->offset;
20918   if (this_cu->is_dwz != offset_in_dwz || cu_off->sect_off > offset.sect_off)
20919     {
20920       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
20921         error (_("Dwarf Error: could not find partial DIE containing "
20922                "offset 0x%lx [in module %s]"),
20923                (long) offset.sect_off, bfd_get_filename (objfile->obfd));
20924
20925       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->offset.sect_off
20926                   <= offset.sect_off);
20927       return dwarf2_per_objfile->all_comp_units[low-1];
20928     }
20929   else
20930     {
20931       this_cu = dwarf2_per_objfile->all_comp_units[low];
20932       if (low == dwarf2_per_objfile->n_comp_units - 1
20933           && offset.sect_off >= this_cu->offset.sect_off + this_cu->length)
20934         error (_("invalid dwarf2 offset %u"), offset.sect_off);
20935       gdb_assert (offset.sect_off < this_cu->offset.sect_off + this_cu->length);
20936       return this_cu;
20937     }
20938 }
20939
20940 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
20941
20942 static void
20943 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
20944 {
20945   memset (cu, 0, sizeof (*cu));
20946   per_cu->cu = cu;
20947   cu->per_cu = per_cu;
20948   cu->objfile = per_cu->objfile;
20949   obstack_init (&cu->comp_unit_obstack);
20950 }
20951
20952 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
20953
20954 static void
20955 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
20956                        enum language pretend_language)
20957 {
20958   struct attribute *attr;
20959
20960   /* Set the language we're debugging.  */
20961   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
20962   if (attr)
20963     set_cu_language (DW_UNSND (attr), cu);
20964   else
20965     {
20966       cu->language = pretend_language;
20967       cu->language_defn = language_def (cu->language);
20968     }
20969
20970   attr = dwarf2_attr (comp_unit_die, DW_AT_producer, cu);
20971   if (attr)
20972     cu->producer = DW_STRING (attr);
20973 }
20974
20975 /* Release one cached compilation unit, CU.  We unlink it from the tree
20976    of compilation units, but we don't remove it from the read_in_chain;
20977    the caller is responsible for that.
20978    NOTE: DATA is a void * because this function is also used as a
20979    cleanup routine.  */
20980
20981 static void
20982 free_heap_comp_unit (void *data)
20983 {
20984   struct dwarf2_cu *cu = data;
20985
20986   gdb_assert (cu->per_cu != NULL);
20987   cu->per_cu->cu = NULL;
20988   cu->per_cu = NULL;
20989
20990   obstack_free (&cu->comp_unit_obstack, NULL);
20991
20992   xfree (cu);
20993 }
20994
20995 /* This cleanup function is passed the address of a dwarf2_cu on the stack
20996    when we're finished with it.  We can't free the pointer itself, but be
20997    sure to unlink it from the cache.  Also release any associated storage.  */
20998
20999 static void
21000 free_stack_comp_unit (void *data)
21001 {
21002   struct dwarf2_cu *cu = data;
21003
21004   gdb_assert (cu->per_cu != NULL);
21005   cu->per_cu->cu = NULL;
21006   cu->per_cu = NULL;
21007
21008   obstack_free (&cu->comp_unit_obstack, NULL);
21009   cu->partial_dies = NULL;
21010 }
21011
21012 /* Free all cached compilation units.  */
21013
21014 static void
21015 free_cached_comp_units (void *data)
21016 {
21017   struct dwarf2_per_cu_data *per_cu, **last_chain;
21018
21019   per_cu = dwarf2_per_objfile->read_in_chain;
21020   last_chain = &dwarf2_per_objfile->read_in_chain;
21021   while (per_cu != NULL)
21022     {
21023       struct dwarf2_per_cu_data *next_cu;
21024
21025       next_cu = per_cu->cu->read_in_chain;
21026
21027       free_heap_comp_unit (per_cu->cu);
21028       *last_chain = next_cu;
21029
21030       per_cu = next_cu;
21031     }
21032 }
21033
21034 /* Increase the age counter on each cached compilation unit, and free
21035    any that are too old.  */
21036
21037 static void
21038 age_cached_comp_units (void)
21039 {
21040   struct dwarf2_per_cu_data *per_cu, **last_chain;
21041
21042   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
21043   per_cu = dwarf2_per_objfile->read_in_chain;
21044   while (per_cu != NULL)
21045     {
21046       per_cu->cu->last_used ++;
21047       if (per_cu->cu->last_used <= dwarf2_max_cache_age)
21048         dwarf2_mark (per_cu->cu);
21049       per_cu = per_cu->cu->read_in_chain;
21050     }
21051
21052   per_cu = dwarf2_per_objfile->read_in_chain;
21053   last_chain = &dwarf2_per_objfile->read_in_chain;
21054   while (per_cu != NULL)
21055     {
21056       struct dwarf2_per_cu_data *next_cu;
21057
21058       next_cu = per_cu->cu->read_in_chain;
21059
21060       if (!per_cu->cu->mark)
21061         {
21062           free_heap_comp_unit (per_cu->cu);
21063           *last_chain = next_cu;
21064         }
21065       else
21066         last_chain = &per_cu->cu->read_in_chain;
21067
21068       per_cu = next_cu;
21069     }
21070 }
21071
21072 /* Remove a single compilation unit from the cache.  */
21073
21074 static void
21075 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
21076 {
21077   struct dwarf2_per_cu_data *per_cu, **last_chain;
21078
21079   per_cu = dwarf2_per_objfile->read_in_chain;
21080   last_chain = &dwarf2_per_objfile->read_in_chain;
21081   while (per_cu != NULL)
21082     {
21083       struct dwarf2_per_cu_data *next_cu;
21084
21085       next_cu = per_cu->cu->read_in_chain;
21086
21087       if (per_cu == target_per_cu)
21088         {
21089           free_heap_comp_unit (per_cu->cu);
21090           per_cu->cu = NULL;
21091           *last_chain = next_cu;
21092           break;
21093         }
21094       else
21095         last_chain = &per_cu->cu->read_in_chain;
21096
21097       per_cu = next_cu;
21098     }
21099 }
21100
21101 /* Release all extra memory associated with OBJFILE.  */
21102
21103 void
21104 dwarf2_free_objfile (struct objfile *objfile)
21105 {
21106   dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
21107
21108   if (dwarf2_per_objfile == NULL)
21109     return;
21110
21111   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
21112   free_cached_comp_units (NULL);
21113
21114   if (dwarf2_per_objfile->quick_file_names_table)
21115     htab_delete (dwarf2_per_objfile->quick_file_names_table);
21116
21117   /* Everything else should be on the objfile obstack.  */
21118 }
21119
21120 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
21121    We store these in a hash table separate from the DIEs, and preserve them
21122    when the DIEs are flushed out of cache.
21123
21124    The CU "per_cu" pointer is needed because offset alone is not enough to
21125    uniquely identify the type.  A file may have multiple .debug_types sections,
21126    or the type may come from a DWO file.  Furthermore, while it's more logical
21127    to use per_cu->section+offset, with Fission the section with the data is in
21128    the DWO file but we don't know that section at the point we need it.
21129    We have to use something in dwarf2_per_cu_data (or the pointer to it)
21130    because we can enter the lookup routine, get_die_type_at_offset, from
21131    outside this file, and thus won't necessarily have PER_CU->cu.
21132    Fortunately, PER_CU is stable for the life of the objfile.  */
21133
21134 struct dwarf2_per_cu_offset_and_type
21135 {
21136   const struct dwarf2_per_cu_data *per_cu;
21137   sect_offset offset;
21138   struct type *type;
21139 };
21140
21141 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
21142
21143 static hashval_t
21144 per_cu_offset_and_type_hash (const void *item)
21145 {
21146   const struct dwarf2_per_cu_offset_and_type *ofs = item;
21147
21148   return (uintptr_t) ofs->per_cu + ofs->offset.sect_off;
21149 }
21150
21151 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
21152
21153 static int
21154 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
21155 {
21156   const struct dwarf2_per_cu_offset_and_type *ofs_lhs = item_lhs;
21157   const struct dwarf2_per_cu_offset_and_type *ofs_rhs = item_rhs;
21158
21159   return (ofs_lhs->per_cu == ofs_rhs->per_cu
21160           && ofs_lhs->offset.sect_off == ofs_rhs->offset.sect_off);
21161 }
21162
21163 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
21164    table if necessary.  For convenience, return TYPE.
21165
21166    The DIEs reading must have careful ordering to:
21167     * Not cause infite loops trying to read in DIEs as a prerequisite for
21168       reading current DIE.
21169     * Not trying to dereference contents of still incompletely read in types
21170       while reading in other DIEs.
21171     * Enable referencing still incompletely read in types just by a pointer to
21172       the type without accessing its fields.
21173
21174    Therefore caller should follow these rules:
21175      * Try to fetch any prerequisite types we may need to build this DIE type
21176        before building the type and calling set_die_type.
21177      * After building type call set_die_type for current DIE as soon as
21178        possible before fetching more types to complete the current type.
21179      * Make the type as complete as possible before fetching more types.  */
21180
21181 static struct type *
21182 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21183 {
21184   struct dwarf2_per_cu_offset_and_type **slot, ofs;
21185   struct objfile *objfile = cu->objfile;
21186
21187   /* For Ada types, make sure that the gnat-specific data is always
21188      initialized (if not already set).  There are a few types where
21189      we should not be doing so, because the type-specific area is
21190      already used to hold some other piece of info (eg: TYPE_CODE_FLT
21191      where the type-specific area is used to store the floatformat).
21192      But this is not a problem, because the gnat-specific information
21193      is actually not needed for these types.  */
21194   if (need_gnat_info (cu)
21195       && TYPE_CODE (type) != TYPE_CODE_FUNC
21196       && TYPE_CODE (type) != TYPE_CODE_FLT
21197       && !HAVE_GNAT_AUX_INFO (type))
21198     INIT_GNAT_SPECIFIC (type);
21199
21200   if (dwarf2_per_objfile->die_type_hash == NULL)
21201     {
21202       dwarf2_per_objfile->die_type_hash =
21203         htab_create_alloc_ex (127,
21204                               per_cu_offset_and_type_hash,
21205                               per_cu_offset_and_type_eq,
21206                               NULL,
21207                               &objfile->objfile_obstack,
21208                               hashtab_obstack_allocate,
21209                               dummy_obstack_deallocate);
21210     }
21211
21212   ofs.per_cu = cu->per_cu;
21213   ofs.offset = die->offset;
21214   ofs.type = type;
21215   slot = (struct dwarf2_per_cu_offset_and_type **)
21216     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
21217   if (*slot)
21218     complaint (&symfile_complaints,
21219                _("A problem internal to GDB: DIE 0x%x has type already set"),
21220                die->offset.sect_off);
21221   *slot = obstack_alloc (&objfile->objfile_obstack, sizeof (**slot));
21222   **slot = ofs;
21223   return type;
21224 }
21225
21226 /* Look up the type for the die at OFFSET in PER_CU in die_type_hash,
21227    or return NULL if the die does not have a saved type.  */
21228
21229 static struct type *
21230 get_die_type_at_offset (sect_offset offset,
21231                         struct dwarf2_per_cu_data *per_cu)
21232 {
21233   struct dwarf2_per_cu_offset_and_type *slot, ofs;
21234
21235   if (dwarf2_per_objfile->die_type_hash == NULL)
21236     return NULL;
21237
21238   ofs.per_cu = per_cu;
21239   ofs.offset = offset;
21240   slot = htab_find (dwarf2_per_objfile->die_type_hash, &ofs);
21241   if (slot)
21242     return slot->type;
21243   else
21244     return NULL;
21245 }
21246
21247 /* Look up the type for DIE in CU in die_type_hash,
21248    or return NULL if DIE does not have a saved type.  */
21249
21250 static struct type *
21251 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
21252 {
21253   return get_die_type_at_offset (die->offset, cu->per_cu);
21254 }
21255
21256 /* Add a dependence relationship from CU to REF_PER_CU.  */
21257
21258 static void
21259 dwarf2_add_dependence (struct dwarf2_cu *cu,
21260                        struct dwarf2_per_cu_data *ref_per_cu)
21261 {
21262   void **slot;
21263
21264   if (cu->dependencies == NULL)
21265     cu->dependencies
21266       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
21267                               NULL, &cu->comp_unit_obstack,
21268                               hashtab_obstack_allocate,
21269                               dummy_obstack_deallocate);
21270
21271   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
21272   if (*slot == NULL)
21273     *slot = ref_per_cu;
21274 }
21275
21276 /* Subroutine of dwarf2_mark to pass to htab_traverse.
21277    Set the mark field in every compilation unit in the
21278    cache that we must keep because we are keeping CU.  */
21279
21280 static int
21281 dwarf2_mark_helper (void **slot, void *data)
21282 {
21283   struct dwarf2_per_cu_data *per_cu;
21284
21285   per_cu = (struct dwarf2_per_cu_data *) *slot;
21286
21287   /* cu->dependencies references may not yet have been ever read if QUIT aborts
21288      reading of the chain.  As such dependencies remain valid it is not much
21289      useful to track and undo them during QUIT cleanups.  */
21290   if (per_cu->cu == NULL)
21291     return 1;
21292
21293   if (per_cu->cu->mark)
21294     return 1;
21295   per_cu->cu->mark = 1;
21296
21297   if (per_cu->cu->dependencies != NULL)
21298     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
21299
21300   return 1;
21301 }
21302
21303 /* Set the mark field in CU and in every other compilation unit in the
21304    cache that we must keep because we are keeping CU.  */
21305
21306 static void
21307 dwarf2_mark (struct dwarf2_cu *cu)
21308 {
21309   if (cu->mark)
21310     return;
21311   cu->mark = 1;
21312   if (cu->dependencies != NULL)
21313     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
21314 }
21315
21316 static void
21317 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
21318 {
21319   while (per_cu)
21320     {
21321       per_cu->cu->mark = 0;
21322       per_cu = per_cu->cu->read_in_chain;
21323     }
21324 }
21325
21326 /* Trivial hash function for partial_die_info: the hash value of a DIE
21327    is its offset in .debug_info for this objfile.  */
21328
21329 static hashval_t
21330 partial_die_hash (const void *item)
21331 {
21332   const struct partial_die_info *part_die = item;
21333
21334   return part_die->offset.sect_off;
21335 }
21336
21337 /* Trivial comparison function for partial_die_info structures: two DIEs
21338    are equal if they have the same offset.  */
21339
21340 static int
21341 partial_die_eq (const void *item_lhs, const void *item_rhs)
21342 {
21343   const struct partial_die_info *part_die_lhs = item_lhs;
21344   const struct partial_die_info *part_die_rhs = item_rhs;
21345
21346   return part_die_lhs->offset.sect_off == part_die_rhs->offset.sect_off;
21347 }
21348
21349 static struct cmd_list_element *set_dwarf2_cmdlist;
21350 static struct cmd_list_element *show_dwarf2_cmdlist;
21351
21352 static void
21353 set_dwarf2_cmd (char *args, int from_tty)
21354 {
21355   help_list (set_dwarf2_cmdlist, "maintenance set dwarf2 ", -1, gdb_stdout);
21356 }
21357
21358 static void
21359 show_dwarf2_cmd (char *args, int from_tty)
21360 {
21361   cmd_show_list (show_dwarf2_cmdlist, from_tty, "");
21362 }
21363
21364 /* Free data associated with OBJFILE, if necessary.  */
21365
21366 static void
21367 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
21368 {
21369   struct dwarf2_per_objfile *data = d;
21370   int ix;
21371
21372   /* Make sure we don't accidentally use dwarf2_per_objfile while
21373      cleaning up.  */
21374   dwarf2_per_objfile = NULL;
21375
21376   for (ix = 0; ix < data->n_comp_units; ++ix)
21377    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
21378
21379   for (ix = 0; ix < data->n_type_units; ++ix)
21380     VEC_free (dwarf2_per_cu_ptr,
21381               data->all_type_units[ix]->per_cu.imported_symtabs);
21382   xfree (data->all_type_units);
21383
21384   VEC_free (dwarf2_section_info_def, data->types);
21385
21386   if (data->dwo_files)
21387     free_dwo_files (data->dwo_files, objfile);
21388   if (data->dwp_file)
21389     gdb_bfd_unref (data->dwp_file->dbfd);
21390
21391   if (data->dwz_file && data->dwz_file->dwz_bfd)
21392     gdb_bfd_unref (data->dwz_file->dwz_bfd);
21393 }
21394
21395 \f
21396 /* The "save gdb-index" command.  */
21397
21398 /* The contents of the hash table we create when building the string
21399    table.  */
21400 struct strtab_entry
21401 {
21402   offset_type offset;
21403   const char *str;
21404 };
21405
21406 /* Hash function for a strtab_entry.
21407
21408    Function is used only during write_hash_table so no index format backward
21409    compatibility is needed.  */
21410
21411 static hashval_t
21412 hash_strtab_entry (const void *e)
21413 {
21414   const struct strtab_entry *entry = e;
21415   return mapped_index_string_hash (INT_MAX, entry->str);
21416 }
21417
21418 /* Equality function for a strtab_entry.  */
21419
21420 static int
21421 eq_strtab_entry (const void *a, const void *b)
21422 {
21423   const struct strtab_entry *ea = a;
21424   const struct strtab_entry *eb = b;
21425   return !strcmp (ea->str, eb->str);
21426 }
21427
21428 /* Create a strtab_entry hash table.  */
21429
21430 static htab_t
21431 create_strtab (void)
21432 {
21433   return htab_create_alloc (100, hash_strtab_entry, eq_strtab_entry,
21434                             xfree, xcalloc, xfree);
21435 }
21436
21437 /* Add a string to the constant pool.  Return the string's offset in
21438    host order.  */
21439
21440 static offset_type
21441 add_string (htab_t table, struct obstack *cpool, const char *str)
21442 {
21443   void **slot;
21444   struct strtab_entry entry;
21445   struct strtab_entry *result;
21446
21447   entry.str = str;
21448   slot = htab_find_slot (table, &entry, INSERT);
21449   if (*slot)
21450     result = *slot;
21451   else
21452     {
21453       result = XNEW (struct strtab_entry);
21454       result->offset = obstack_object_size (cpool);
21455       result->str = str;
21456       obstack_grow_str0 (cpool, str);
21457       *slot = result;
21458     }
21459   return result->offset;
21460 }
21461
21462 /* An entry in the symbol table.  */
21463 struct symtab_index_entry
21464 {
21465   /* The name of the symbol.  */
21466   const char *name;
21467   /* The offset of the name in the constant pool.  */
21468   offset_type index_offset;
21469   /* A sorted vector of the indices of all the CUs that hold an object
21470      of this name.  */
21471   VEC (offset_type) *cu_indices;
21472 };
21473
21474 /* The symbol table.  This is a power-of-2-sized hash table.  */
21475 struct mapped_symtab
21476 {
21477   offset_type n_elements;
21478   offset_type size;
21479   struct symtab_index_entry **data;
21480 };
21481
21482 /* Hash function for a symtab_index_entry.  */
21483
21484 static hashval_t
21485 hash_symtab_entry (const void *e)
21486 {
21487   const struct symtab_index_entry *entry = e;
21488   return iterative_hash (VEC_address (offset_type, entry->cu_indices),
21489                          sizeof (offset_type) * VEC_length (offset_type,
21490                                                             entry->cu_indices),
21491                          0);
21492 }
21493
21494 /* Equality function for a symtab_index_entry.  */
21495
21496 static int
21497 eq_symtab_entry (const void *a, const void *b)
21498 {
21499   const struct symtab_index_entry *ea = a;
21500   const struct symtab_index_entry *eb = b;
21501   int len = VEC_length (offset_type, ea->cu_indices);
21502   if (len != VEC_length (offset_type, eb->cu_indices))
21503     return 0;
21504   return !memcmp (VEC_address (offset_type, ea->cu_indices),
21505                   VEC_address (offset_type, eb->cu_indices),
21506                   sizeof (offset_type) * len);
21507 }
21508
21509 /* Destroy a symtab_index_entry.  */
21510
21511 static void
21512 delete_symtab_entry (void *p)
21513 {
21514   struct symtab_index_entry *entry = p;
21515   VEC_free (offset_type, entry->cu_indices);
21516   xfree (entry);
21517 }
21518
21519 /* Create a hash table holding symtab_index_entry objects.  */
21520
21521 static htab_t
21522 create_symbol_hash_table (void)
21523 {
21524   return htab_create_alloc (100, hash_symtab_entry, eq_symtab_entry,
21525                             delete_symtab_entry, xcalloc, xfree);
21526 }
21527
21528 /* Create a new mapped symtab object.  */
21529
21530 static struct mapped_symtab *
21531 create_mapped_symtab (void)
21532 {
21533   struct mapped_symtab *symtab = XNEW (struct mapped_symtab);
21534   symtab->n_elements = 0;
21535   symtab->size = 1024;
21536   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21537   return symtab;
21538 }
21539
21540 /* Destroy a mapped_symtab.  */
21541
21542 static void
21543 cleanup_mapped_symtab (void *p)
21544 {
21545   struct mapped_symtab *symtab = p;
21546   /* The contents of the array are freed when the other hash table is
21547      destroyed.  */
21548   xfree (symtab->data);
21549   xfree (symtab);
21550 }
21551
21552 /* Find a slot in SYMTAB for the symbol NAME.  Returns a pointer to
21553    the slot.
21554    
21555    Function is used only during write_hash_table so no index format backward
21556    compatibility is needed.  */
21557
21558 static struct symtab_index_entry **
21559 find_slot (struct mapped_symtab *symtab, const char *name)
21560 {
21561   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
21562
21563   index = hash & (symtab->size - 1);
21564   step = ((hash * 17) & (symtab->size - 1)) | 1;
21565
21566   for (;;)
21567     {
21568       if (!symtab->data[index] || !strcmp (name, symtab->data[index]->name))
21569         return &symtab->data[index];
21570       index = (index + step) & (symtab->size - 1);
21571     }
21572 }
21573
21574 /* Expand SYMTAB's hash table.  */
21575
21576 static void
21577 hash_expand (struct mapped_symtab *symtab)
21578 {
21579   offset_type old_size = symtab->size;
21580   offset_type i;
21581   struct symtab_index_entry **old_entries = symtab->data;
21582
21583   symtab->size *= 2;
21584   symtab->data = XCNEWVEC (struct symtab_index_entry *, symtab->size);
21585
21586   for (i = 0; i < old_size; ++i)
21587     {
21588       if (old_entries[i])
21589         {
21590           struct symtab_index_entry **slot = find_slot (symtab,
21591                                                         old_entries[i]->name);
21592           *slot = old_entries[i];
21593         }
21594     }
21595
21596   xfree (old_entries);
21597 }
21598
21599 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
21600    CU_INDEX is the index of the CU in which the symbol appears.
21601    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
21602
21603 static void
21604 add_index_entry (struct mapped_symtab *symtab, const char *name,
21605                  int is_static, gdb_index_symbol_kind kind,
21606                  offset_type cu_index)
21607 {
21608   struct symtab_index_entry **slot;
21609   offset_type cu_index_and_attrs;
21610
21611   ++symtab->n_elements;
21612   if (4 * symtab->n_elements / 3 >= symtab->size)
21613     hash_expand (symtab);
21614
21615   slot = find_slot (symtab, name);
21616   if (!*slot)
21617     {
21618       *slot = XNEW (struct symtab_index_entry);
21619       (*slot)->name = name;
21620       /* index_offset is set later.  */
21621       (*slot)->cu_indices = NULL;
21622     }
21623
21624   cu_index_and_attrs = 0;
21625   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
21626   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
21627   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
21628
21629   /* We don't want to record an index value twice as we want to avoid the
21630      duplication.
21631      We process all global symbols and then all static symbols
21632      (which would allow us to avoid the duplication by only having to check
21633      the last entry pushed), but a symbol could have multiple kinds in one CU.
21634      To keep things simple we don't worry about the duplication here and
21635      sort and uniqufy the list after we've processed all symbols.  */
21636   VEC_safe_push (offset_type, (*slot)->cu_indices, cu_index_and_attrs);
21637 }
21638
21639 /* qsort helper routine for uniquify_cu_indices.  */
21640
21641 static int
21642 offset_type_compare (const void *ap, const void *bp)
21643 {
21644   offset_type a = *(offset_type *) ap;
21645   offset_type b = *(offset_type *) bp;
21646
21647   return (a > b) - (b > a);
21648 }
21649
21650 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
21651
21652 static void
21653 uniquify_cu_indices (struct mapped_symtab *symtab)
21654 {
21655   int i;
21656
21657   for (i = 0; i < symtab->size; ++i)
21658     {
21659       struct symtab_index_entry *entry = symtab->data[i];
21660
21661       if (entry
21662           && entry->cu_indices != NULL)
21663         {
21664           unsigned int next_to_insert, next_to_check;
21665           offset_type last_value;
21666
21667           qsort (VEC_address (offset_type, entry->cu_indices),
21668                  VEC_length (offset_type, entry->cu_indices),
21669                  sizeof (offset_type), offset_type_compare);
21670
21671           last_value = VEC_index (offset_type, entry->cu_indices, 0);
21672           next_to_insert = 1;
21673           for (next_to_check = 1;
21674                next_to_check < VEC_length (offset_type, entry->cu_indices);
21675                ++next_to_check)
21676             {
21677               if (VEC_index (offset_type, entry->cu_indices, next_to_check)
21678                   != last_value)
21679                 {
21680                   last_value = VEC_index (offset_type, entry->cu_indices,
21681                                           next_to_check);
21682                   VEC_replace (offset_type, entry->cu_indices, next_to_insert,
21683                                last_value);
21684                   ++next_to_insert;
21685                 }
21686             }
21687           VEC_truncate (offset_type, entry->cu_indices, next_to_insert);
21688         }
21689     }
21690 }
21691
21692 /* Add a vector of indices to the constant pool.  */
21693
21694 static offset_type
21695 add_indices_to_cpool (htab_t symbol_hash_table, struct obstack *cpool,
21696                       struct symtab_index_entry *entry)
21697 {
21698   void **slot;
21699
21700   slot = htab_find_slot (symbol_hash_table, entry, INSERT);
21701   if (!*slot)
21702     {
21703       offset_type len = VEC_length (offset_type, entry->cu_indices);
21704       offset_type val = MAYBE_SWAP (len);
21705       offset_type iter;
21706       int i;
21707
21708       *slot = entry;
21709       entry->index_offset = obstack_object_size (cpool);
21710
21711       obstack_grow (cpool, &val, sizeof (val));
21712       for (i = 0;
21713            VEC_iterate (offset_type, entry->cu_indices, i, iter);
21714            ++i)
21715         {
21716           val = MAYBE_SWAP (iter);
21717           obstack_grow (cpool, &val, sizeof (val));
21718         }
21719     }
21720   else
21721     {
21722       struct symtab_index_entry *old_entry = *slot;
21723       entry->index_offset = old_entry->index_offset;
21724       entry = old_entry;
21725     }
21726   return entry->index_offset;
21727 }
21728
21729 /* Write the mapped hash table SYMTAB to the obstack OUTPUT, with
21730    constant pool entries going into the obstack CPOOL.  */
21731
21732 static void
21733 write_hash_table (struct mapped_symtab *symtab,
21734                   struct obstack *output, struct obstack *cpool)
21735 {
21736   offset_type i;
21737   htab_t symbol_hash_table;
21738   htab_t str_table;
21739
21740   symbol_hash_table = create_symbol_hash_table ();
21741   str_table = create_strtab ();
21742
21743   /* We add all the index vectors to the constant pool first, to
21744      ensure alignment is ok.  */
21745   for (i = 0; i < symtab->size; ++i)
21746     {
21747       if (symtab->data[i])
21748         add_indices_to_cpool (symbol_hash_table, cpool, symtab->data[i]);
21749     }
21750
21751   /* Now write out the hash table.  */
21752   for (i = 0; i < symtab->size; ++i)
21753     {
21754       offset_type str_off, vec_off;
21755
21756       if (symtab->data[i])
21757         {
21758           str_off = add_string (str_table, cpool, symtab->data[i]->name);
21759           vec_off = symtab->data[i]->index_offset;
21760         }
21761       else
21762         {
21763           /* While 0 is a valid constant pool index, it is not valid
21764              to have 0 for both offsets.  */
21765           str_off = 0;
21766           vec_off = 0;
21767         }
21768
21769       str_off = MAYBE_SWAP (str_off);
21770       vec_off = MAYBE_SWAP (vec_off);
21771
21772       obstack_grow (output, &str_off, sizeof (str_off));
21773       obstack_grow (output, &vec_off, sizeof (vec_off));
21774     }
21775
21776   htab_delete (str_table);
21777   htab_delete (symbol_hash_table);
21778 }
21779
21780 /* Struct to map psymtab to CU index in the index file.  */
21781 struct psymtab_cu_index_map
21782 {
21783   struct partial_symtab *psymtab;
21784   unsigned int cu_index;
21785 };
21786
21787 static hashval_t
21788 hash_psymtab_cu_index (const void *item)
21789 {
21790   const struct psymtab_cu_index_map *map = item;
21791
21792   return htab_hash_pointer (map->psymtab);
21793 }
21794
21795 static int
21796 eq_psymtab_cu_index (const void *item_lhs, const void *item_rhs)
21797 {
21798   const struct psymtab_cu_index_map *lhs = item_lhs;
21799   const struct psymtab_cu_index_map *rhs = item_rhs;
21800
21801   return lhs->psymtab == rhs->psymtab;
21802 }
21803
21804 /* Helper struct for building the address table.  */
21805 struct addrmap_index_data
21806 {
21807   struct objfile *objfile;
21808   struct obstack *addr_obstack;
21809   htab_t cu_index_htab;
21810
21811   /* Non-zero if the previous_* fields are valid.
21812      We can't write an entry until we see the next entry (since it is only then
21813      that we know the end of the entry).  */
21814   int previous_valid;
21815   /* Index of the CU in the table of all CUs in the index file.  */
21816   unsigned int previous_cu_index;
21817   /* Start address of the CU.  */
21818   CORE_ADDR previous_cu_start;
21819 };
21820
21821 /* Write an address entry to OBSTACK.  */
21822
21823 static void
21824 add_address_entry (struct objfile *objfile, struct obstack *obstack,
21825                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
21826 {
21827   offset_type cu_index_to_write;
21828   gdb_byte addr[8];
21829   CORE_ADDR baseaddr;
21830
21831   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21832
21833   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, start - baseaddr);
21834   obstack_grow (obstack, addr, 8);
21835   store_unsigned_integer (addr, 8, BFD_ENDIAN_LITTLE, end - baseaddr);
21836   obstack_grow (obstack, addr, 8);
21837   cu_index_to_write = MAYBE_SWAP (cu_index);
21838   obstack_grow (obstack, &cu_index_to_write, sizeof (offset_type));
21839 }
21840
21841 /* Worker function for traversing an addrmap to build the address table.  */
21842
21843 static int
21844 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
21845 {
21846   struct addrmap_index_data *data = datap;
21847   struct partial_symtab *pst = obj;
21848
21849   if (data->previous_valid)
21850     add_address_entry (data->objfile, data->addr_obstack,
21851                        data->previous_cu_start, start_addr,
21852                        data->previous_cu_index);
21853
21854   data->previous_cu_start = start_addr;
21855   if (pst != NULL)
21856     {
21857       struct psymtab_cu_index_map find_map, *map;
21858       find_map.psymtab = pst;
21859       map = htab_find (data->cu_index_htab, &find_map);
21860       gdb_assert (map != NULL);
21861       data->previous_cu_index = map->cu_index;
21862       data->previous_valid = 1;
21863     }
21864   else
21865       data->previous_valid = 0;
21866
21867   return 0;
21868 }
21869
21870 /* Write OBJFILE's address map to OBSTACK.
21871    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
21872    in the index file.  */
21873
21874 static void
21875 write_address_map (struct objfile *objfile, struct obstack *obstack,
21876                    htab_t cu_index_htab)
21877 {
21878   struct addrmap_index_data addrmap_index_data;
21879
21880   /* When writing the address table, we have to cope with the fact that
21881      the addrmap iterator only provides the start of a region; we have to
21882      wait until the next invocation to get the start of the next region.  */
21883
21884   addrmap_index_data.objfile = objfile;
21885   addrmap_index_data.addr_obstack = obstack;
21886   addrmap_index_data.cu_index_htab = cu_index_htab;
21887   addrmap_index_data.previous_valid = 0;
21888
21889   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
21890                    &addrmap_index_data);
21891
21892   /* It's highly unlikely the last entry (end address = 0xff...ff)
21893      is valid, but we should still handle it.
21894      The end address is recorded as the start of the next region, but that
21895      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
21896      anyway.  */
21897   if (addrmap_index_data.previous_valid)
21898     add_address_entry (objfile, obstack,
21899                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
21900                        addrmap_index_data.previous_cu_index);
21901 }
21902
21903 /* Return the symbol kind of PSYM.  */
21904
21905 static gdb_index_symbol_kind
21906 symbol_kind (struct partial_symbol *psym)
21907 {
21908   domain_enum domain = PSYMBOL_DOMAIN (psym);
21909   enum address_class aclass = PSYMBOL_CLASS (psym);
21910
21911   switch (domain)
21912     {
21913     case VAR_DOMAIN:
21914       switch (aclass)
21915         {
21916         case LOC_BLOCK:
21917           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
21918         case LOC_TYPEDEF:
21919           return GDB_INDEX_SYMBOL_KIND_TYPE;
21920         case LOC_COMPUTED:
21921         case LOC_CONST_BYTES:
21922         case LOC_OPTIMIZED_OUT:
21923         case LOC_STATIC:
21924           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21925         case LOC_CONST:
21926           /* Note: It's currently impossible to recognize psyms as enum values
21927              short of reading the type info.  For now punt.  */
21928           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
21929         default:
21930           /* There are other LOC_FOO values that one might want to classify
21931              as variables, but dwarf2read.c doesn't currently use them.  */
21932           return GDB_INDEX_SYMBOL_KIND_OTHER;
21933         }
21934     case STRUCT_DOMAIN:
21935       return GDB_INDEX_SYMBOL_KIND_TYPE;
21936     default:
21937       return GDB_INDEX_SYMBOL_KIND_OTHER;
21938     }
21939 }
21940
21941 /* Add a list of partial symbols to SYMTAB.  */
21942
21943 static void
21944 write_psymbols (struct mapped_symtab *symtab,
21945                 htab_t psyms_seen,
21946                 struct partial_symbol **psymp,
21947                 int count,
21948                 offset_type cu_index,
21949                 int is_static)
21950 {
21951   for (; count-- > 0; ++psymp)
21952     {
21953       struct partial_symbol *psym = *psymp;
21954       void **slot;
21955
21956       if (SYMBOL_LANGUAGE (psym) == language_ada)
21957         error (_("Ada is not currently supported by the index"));
21958
21959       /* Only add a given psymbol once.  */
21960       slot = htab_find_slot (psyms_seen, psym, INSERT);
21961       if (!*slot)
21962         {
21963           gdb_index_symbol_kind kind = symbol_kind (psym);
21964
21965           *slot = psym;
21966           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
21967                            is_static, kind, cu_index);
21968         }
21969     }
21970 }
21971
21972 /* Write the contents of an ("unfinished") obstack to FILE.  Throw an
21973    exception if there is an error.  */
21974
21975 static void
21976 write_obstack (FILE *file, struct obstack *obstack)
21977 {
21978   if (fwrite (obstack_base (obstack), 1, obstack_object_size (obstack),
21979               file)
21980       != obstack_object_size (obstack))
21981     error (_("couldn't data write to file"));
21982 }
21983
21984 /* Unlink a file if the argument is not NULL.  */
21985
21986 static void
21987 unlink_if_set (void *p)
21988 {
21989   char **filename = p;
21990   if (*filename)
21991     unlink (*filename);
21992 }
21993
21994 /* A helper struct used when iterating over debug_types.  */
21995 struct signatured_type_index_data
21996 {
21997   struct objfile *objfile;
21998   struct mapped_symtab *symtab;
21999   struct obstack *types_list;
22000   htab_t psyms_seen;
22001   int cu_index;
22002 };
22003
22004 /* A helper function that writes a single signatured_type to an
22005    obstack.  */
22006
22007 static int
22008 write_one_signatured_type (void **slot, void *d)
22009 {
22010   struct signatured_type_index_data *info = d;
22011   struct signatured_type *entry = (struct signatured_type *) *slot;
22012   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
22013   gdb_byte val[8];
22014
22015   write_psymbols (info->symtab,
22016                   info->psyms_seen,
22017                   info->objfile->global_psymbols.list
22018                   + psymtab->globals_offset,
22019                   psymtab->n_global_syms, info->cu_index,
22020                   0);
22021   write_psymbols (info->symtab,
22022                   info->psyms_seen,
22023                   info->objfile->static_psymbols.list
22024                   + psymtab->statics_offset,
22025                   psymtab->n_static_syms, info->cu_index,
22026                   1);
22027
22028   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22029                           entry->per_cu.offset.sect_off);
22030   obstack_grow (info->types_list, val, 8);
22031   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22032                           entry->type_offset_in_tu.cu_off);
22033   obstack_grow (info->types_list, val, 8);
22034   store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, entry->signature);
22035   obstack_grow (info->types_list, val, 8);
22036
22037   ++info->cu_index;
22038
22039   return 1;
22040 }
22041
22042 /* Recurse into all "included" dependencies and write their symbols as
22043    if they appeared in this psymtab.  */
22044
22045 static void
22046 recursively_write_psymbols (struct objfile *objfile,
22047                             struct partial_symtab *psymtab,
22048                             struct mapped_symtab *symtab,
22049                             htab_t psyms_seen,
22050                             offset_type cu_index)
22051 {
22052   int i;
22053
22054   for (i = 0; i < psymtab->number_of_dependencies; ++i)
22055     if (psymtab->dependencies[i]->user != NULL)
22056       recursively_write_psymbols (objfile, psymtab->dependencies[i],
22057                                   symtab, psyms_seen, cu_index);
22058
22059   write_psymbols (symtab,
22060                   psyms_seen,
22061                   objfile->global_psymbols.list + psymtab->globals_offset,
22062                   psymtab->n_global_syms, cu_index,
22063                   0);
22064   write_psymbols (symtab,
22065                   psyms_seen,
22066                   objfile->static_psymbols.list + psymtab->statics_offset,
22067                   psymtab->n_static_syms, cu_index,
22068                   1);
22069 }
22070
22071 /* Create an index file for OBJFILE in the directory DIR.  */
22072
22073 static void
22074 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
22075 {
22076   struct cleanup *cleanup;
22077   char *filename, *cleanup_filename;
22078   struct obstack contents, addr_obstack, constant_pool, symtab_obstack;
22079   struct obstack cu_list, types_cu_list;
22080   int i;
22081   FILE *out_file;
22082   struct mapped_symtab *symtab;
22083   offset_type val, size_of_contents, total_len;
22084   struct stat st;
22085   htab_t psyms_seen;
22086   htab_t cu_index_htab;
22087   struct psymtab_cu_index_map *psymtab_cu_index_map;
22088
22089   if (dwarf2_per_objfile->using_index)
22090     error (_("Cannot use an index to create the index"));
22091
22092   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
22093     error (_("Cannot make an index when the file has multiple .debug_types sections"));
22094
22095   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
22096     return;
22097
22098   if (stat (objfile_name (objfile), &st) < 0)
22099     perror_with_name (objfile_name (objfile));
22100
22101   filename = concat (dir, SLASH_STRING, lbasename (objfile_name (objfile)),
22102                      INDEX_SUFFIX, (char *) NULL);
22103   cleanup = make_cleanup (xfree, filename);
22104
22105   out_file = gdb_fopen_cloexec (filename, "wb");
22106   if (!out_file)
22107     error (_("Can't open `%s' for writing"), filename);
22108
22109   cleanup_filename = filename;
22110   make_cleanup (unlink_if_set, &cleanup_filename);
22111
22112   symtab = create_mapped_symtab ();
22113   make_cleanup (cleanup_mapped_symtab, symtab);
22114
22115   obstack_init (&addr_obstack);
22116   make_cleanup_obstack_free (&addr_obstack);
22117
22118   obstack_init (&cu_list);
22119   make_cleanup_obstack_free (&cu_list);
22120
22121   obstack_init (&types_cu_list);
22122   make_cleanup_obstack_free (&types_cu_list);
22123
22124   psyms_seen = htab_create_alloc (100, htab_hash_pointer, htab_eq_pointer,
22125                                   NULL, xcalloc, xfree);
22126   make_cleanup_htab_delete (psyms_seen);
22127
22128   /* While we're scanning CU's create a table that maps a psymtab pointer
22129      (which is what addrmap records) to its index (which is what is recorded
22130      in the index file).  This will later be needed to write the address
22131      table.  */
22132   cu_index_htab = htab_create_alloc (100,
22133                                      hash_psymtab_cu_index,
22134                                      eq_psymtab_cu_index,
22135                                      NULL, xcalloc, xfree);
22136   make_cleanup_htab_delete (cu_index_htab);
22137   psymtab_cu_index_map = (struct psymtab_cu_index_map *)
22138     xmalloc (sizeof (struct psymtab_cu_index_map)
22139              * dwarf2_per_objfile->n_comp_units);
22140   make_cleanup (xfree, psymtab_cu_index_map);
22141
22142   /* The CU list is already sorted, so we don't need to do additional
22143      work here.  Also, the debug_types entries do not appear in
22144      all_comp_units, but only in their own hash table.  */
22145   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
22146     {
22147       struct dwarf2_per_cu_data *per_cu
22148         = dwarf2_per_objfile->all_comp_units[i];
22149       struct partial_symtab *psymtab = per_cu->v.psymtab;
22150       gdb_byte val[8];
22151       struct psymtab_cu_index_map *map;
22152       void **slot;
22153
22154       /* CU of a shared file from 'dwz -m' may be unused by this main file.
22155          It may be referenced from a local scope but in such case it does not
22156          need to be present in .gdb_index.  */
22157       if (psymtab == NULL)
22158         continue;
22159
22160       if (psymtab->user == NULL)
22161         recursively_write_psymbols (objfile, psymtab, symtab, psyms_seen, i);
22162
22163       map = &psymtab_cu_index_map[i];
22164       map->psymtab = psymtab;
22165       map->cu_index = i;
22166       slot = htab_find_slot (cu_index_htab, map, INSERT);
22167       gdb_assert (slot != NULL);
22168       gdb_assert (*slot == NULL);
22169       *slot = map;
22170
22171       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE,
22172                               per_cu->offset.sect_off);
22173       obstack_grow (&cu_list, val, 8);
22174       store_unsigned_integer (val, 8, BFD_ENDIAN_LITTLE, per_cu->length);
22175       obstack_grow (&cu_list, val, 8);
22176     }
22177
22178   /* Dump the address map.  */
22179   write_address_map (objfile, &addr_obstack, cu_index_htab);
22180
22181   /* Write out the .debug_type entries, if any.  */
22182   if (dwarf2_per_objfile->signatured_types)
22183     {
22184       struct signatured_type_index_data sig_data;
22185
22186       sig_data.objfile = objfile;
22187       sig_data.symtab = symtab;
22188       sig_data.types_list = &types_cu_list;
22189       sig_data.psyms_seen = psyms_seen;
22190       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
22191       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
22192                               write_one_signatured_type, &sig_data);
22193     }
22194
22195   /* Now that we've processed all symbols we can shrink their cu_indices
22196      lists.  */
22197   uniquify_cu_indices (symtab);
22198
22199   obstack_init (&constant_pool);
22200   make_cleanup_obstack_free (&constant_pool);
22201   obstack_init (&symtab_obstack);
22202   make_cleanup_obstack_free (&symtab_obstack);
22203   write_hash_table (symtab, &symtab_obstack, &constant_pool);
22204
22205   obstack_init (&contents);
22206   make_cleanup_obstack_free (&contents);
22207   size_of_contents = 6 * sizeof (offset_type);
22208   total_len = size_of_contents;
22209
22210   /* The version number.  */
22211   val = MAYBE_SWAP (8);
22212   obstack_grow (&contents, &val, sizeof (val));
22213
22214   /* The offset of the CU list from the start of the file.  */
22215   val = MAYBE_SWAP (total_len);
22216   obstack_grow (&contents, &val, sizeof (val));
22217   total_len += obstack_object_size (&cu_list);
22218
22219   /* The offset of the types CU list from the start of the file.  */
22220   val = MAYBE_SWAP (total_len);
22221   obstack_grow (&contents, &val, sizeof (val));
22222   total_len += obstack_object_size (&types_cu_list);
22223
22224   /* The offset of the address table from the start of the file.  */
22225   val = MAYBE_SWAP (total_len);
22226   obstack_grow (&contents, &val, sizeof (val));
22227   total_len += obstack_object_size (&addr_obstack);
22228
22229   /* The offset of the symbol table from the start of the file.  */
22230   val = MAYBE_SWAP (total_len);
22231   obstack_grow (&contents, &val, sizeof (val));
22232   total_len += obstack_object_size (&symtab_obstack);
22233
22234   /* The offset of the constant pool from the start of the file.  */
22235   val = MAYBE_SWAP (total_len);
22236   obstack_grow (&contents, &val, sizeof (val));
22237   total_len += obstack_object_size (&constant_pool);
22238
22239   gdb_assert (obstack_object_size (&contents) == size_of_contents);
22240
22241   write_obstack (out_file, &contents);
22242   write_obstack (out_file, &cu_list);
22243   write_obstack (out_file, &types_cu_list);
22244   write_obstack (out_file, &addr_obstack);
22245   write_obstack (out_file, &symtab_obstack);
22246   write_obstack (out_file, &constant_pool);
22247
22248   fclose (out_file);
22249
22250   /* We want to keep the file, so we set cleanup_filename to NULL
22251      here.  See unlink_if_set.  */
22252   cleanup_filename = NULL;
22253
22254   do_cleanups (cleanup);
22255 }
22256
22257 /* Implementation of the `save gdb-index' command.
22258    
22259    Note that the file format used by this command is documented in the
22260    GDB manual.  Any changes here must be documented there.  */
22261
22262 static void
22263 save_gdb_index_command (char *arg, int from_tty)
22264 {
22265   struct objfile *objfile;
22266
22267   if (!arg || !*arg)
22268     error (_("usage: save gdb-index DIRECTORY"));
22269
22270   ALL_OBJFILES (objfile)
22271   {
22272     struct stat st;
22273
22274     /* If the objfile does not correspond to an actual file, skip it.  */
22275     if (stat (objfile_name (objfile), &st) < 0)
22276       continue;
22277
22278     dwarf2_per_objfile = objfile_data (objfile, dwarf2_objfile_data_key);
22279     if (dwarf2_per_objfile)
22280       {
22281         volatile struct gdb_exception except;
22282
22283         TRY_CATCH (except, RETURN_MASK_ERROR)
22284           {
22285             write_psymtabs_to_index (objfile, arg);
22286           }
22287         if (except.reason < 0)
22288           exception_fprintf (gdb_stderr, except,
22289                              _("Error while writing index for `%s': "),
22290                              objfile_name (objfile));
22291       }
22292   }
22293 }
22294
22295 \f
22296
22297 int dwarf2_always_disassemble;
22298
22299 static void
22300 show_dwarf2_always_disassemble (struct ui_file *file, int from_tty,
22301                                 struct cmd_list_element *c, const char *value)
22302 {
22303   fprintf_filtered (file,
22304                     _("Whether to always disassemble "
22305                       "DWARF expressions is %s.\n"),
22306                     value);
22307 }
22308
22309 static void
22310 show_check_physname (struct ui_file *file, int from_tty,
22311                      struct cmd_list_element *c, const char *value)
22312 {
22313   fprintf_filtered (file,
22314                     _("Whether to check \"physname\" is %s.\n"),
22315                     value);
22316 }
22317
22318 void _initialize_dwarf2_read (void);
22319
22320 void
22321 _initialize_dwarf2_read (void)
22322 {
22323   struct cmd_list_element *c;
22324
22325   dwarf2_objfile_data_key
22326     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
22327
22328   add_prefix_cmd ("dwarf2", class_maintenance, set_dwarf2_cmd, _("\
22329 Set DWARF 2 specific variables.\n\
22330 Configure DWARF 2 variables such as the cache size"),
22331                   &set_dwarf2_cmdlist, "maintenance set dwarf2 ",
22332                   0/*allow-unknown*/, &maintenance_set_cmdlist);
22333
22334   add_prefix_cmd ("dwarf2", class_maintenance, show_dwarf2_cmd, _("\
22335 Show DWARF 2 specific variables\n\
22336 Show DWARF 2 variables such as the cache size"),
22337                   &show_dwarf2_cmdlist, "maintenance show dwarf2 ",
22338                   0/*allow-unknown*/, &maintenance_show_cmdlist);
22339
22340   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
22341                             &dwarf2_max_cache_age, _("\
22342 Set the upper bound on the age of cached dwarf2 compilation units."), _("\
22343 Show the upper bound on the age of cached dwarf2 compilation units."), _("\
22344 A higher limit means that cached compilation units will be stored\n\
22345 in memory longer, and more total memory will be used.  Zero disables\n\
22346 caching, which can slow down startup."),
22347                             NULL,
22348                             show_dwarf2_max_cache_age,
22349                             &set_dwarf2_cmdlist,
22350                             &show_dwarf2_cmdlist);
22351
22352   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
22353                            &dwarf2_always_disassemble, _("\
22354 Set whether `info address' always disassembles DWARF expressions."), _("\
22355 Show whether `info address' always disassembles DWARF expressions."), _("\
22356 When enabled, DWARF expressions are always printed in an assembly-like\n\
22357 syntax.  When disabled, expressions will be printed in a more\n\
22358 conversational style, when possible."),
22359                            NULL,
22360                            show_dwarf2_always_disassemble,
22361                            &set_dwarf2_cmdlist,
22362                            &show_dwarf2_cmdlist);
22363
22364   add_setshow_boolean_cmd ("dwarf2-read", no_class, &dwarf2_read_debug, _("\
22365 Set debugging of the dwarf2 reader."), _("\
22366 Show debugging of the dwarf2 reader."), _("\
22367 When enabled, debugging messages are printed during dwarf2 reading\n\
22368 and symtab expansion."),
22369                             NULL,
22370                             NULL,
22371                             &setdebuglist, &showdebuglist);
22372
22373   add_setshow_zuinteger_cmd ("dwarf2-die", no_class, &dwarf2_die_debug, _("\
22374 Set debugging of the dwarf2 DIE reader."), _("\
22375 Show debugging of the dwarf2 DIE reader."), _("\
22376 When enabled (non-zero), DIEs are dumped after they are read in.\n\
22377 The value is the maximum depth to print."),
22378                              NULL,
22379                              NULL,
22380                              &setdebuglist, &showdebuglist);
22381
22382   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
22383 Set cross-checking of \"physname\" code against demangler."), _("\
22384 Show cross-checking of \"physname\" code against demangler."), _("\
22385 When enabled, GDB's internal \"physname\" code is checked against\n\
22386 the demangler."),
22387                            NULL, show_check_physname,
22388                            &setdebuglist, &showdebuglist);
22389
22390   add_setshow_boolean_cmd ("use-deprecated-index-sections",
22391                            no_class, &use_deprecated_index_sections, _("\
22392 Set whether to use deprecated gdb_index sections."), _("\
22393 Show whether to use deprecated gdb_index sections."), _("\
22394 When enabled, deprecated .gdb_index sections are used anyway.\n\
22395 Normally they are ignored either because of a missing feature or\n\
22396 performance issue.\n\
22397 Warning: This option must be enabled before gdb reads the file."),
22398                            NULL,
22399                            NULL,
22400                            &setlist, &showlist);
22401
22402   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
22403                _("\
22404 Save a gdb-index file.\n\
22405 Usage: save gdb-index DIRECTORY"),
22406                &save_cmdlist);
22407   set_cmd_completer (c, filename_completer);
22408
22409   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
22410                                                         &dwarf2_locexpr_funcs);
22411   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
22412                                                         &dwarf2_loclist_funcs);
22413
22414   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
22415                                         &dwarf2_block_frame_base_locexpr_funcs);
22416   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
22417                                         &dwarf2_block_frame_base_loclist_funcs);
22418 }